0% found this document useful (0 votes)
2 views

CPPS-Module2

Uploaded by

br2see
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CPPS-Module2

Uploaded by

br2see
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

MODULE II

BRANCHING AND LOOPING: Two way selection (if, if-else, nested if-else, cascaded if-else),
switch statement, ternary operator? Go to, Loops (For, do-while, while) in C, break and continue,
programming examples and exercises

BRANCHING AND LOOPING:

What is branching and looping?


In programming we have to perform (Execute) some statements when condition met or may need
to skip some statements. These statements are called as Branch statements.
Branching is deciding what actions to take and looping is deciding how many times to take a
certain action.

C provides two styles of flow control:


 Branching
 Looping

Branch statements are classified into two ways,

1. Conditional Branch statements.


2. Unconditional Branch statements.

1. Conditional Branch statements.

 Simple if (single selection)


 if-else (two way selection)
 nested if
 else-if ladder
 switch

The if, if...else and nested if...else statement are used to make one-time decisions in C
Programming, that is, to execute some code/s and ignore some code/s depending upon the test
expression.

1. simple if

This is the simplest form of the conditional branching statements. Here condition is
evaluated, if it evaluate true a statement or group of statement is executed.

Dr Shobha N, Asst Prof, CSE Page 1


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Syntax:
if (expression)
{
Statement to be executed if expression is true ;
}
- If the expression is evaluated and found to be true, statement/s inside the body of if is
executed but if expression is false, statement/s inside body of if is ignored.
- Usage of braces is optional, when only one statement is there.
- Multiple statements should be written in pair of braces { }.
- No semicolon is required after if.

‘C’ programming using simple if statement:

1. ‘C’ program to check given number is even or not.


#include<stdio.h>
void main()
{
int n;
printf (“Enter the value of n”);
scanf (“% d”,&n);
if(n% 2==0) // checking whether number even or not

printf(“number is=% d”,n);

printf(“\n Hello”);
}

Dr Shobha N, Asst Prof, CSE Page 2


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

2. Write a C program to print the number entered by user is negative.

#include<stdio.h>
void main()
{
int n;

Printf(“Enter the number to check”);


Scanf(“% d”,&n);
if (n<0) // checking whether number i s less than 0 o r not
{
printf(“the number is=% d”,n);
}

Printf(“This will execute always”);


}

Output 1:- When user enters -2 then, the test expression (num<0) becomes true.

Hence, Number = -2 is displayed in the screen.

Output 2 :- When user enters 5 then, the test expression (num<0) becomes false and
Print This will execute always.

Note: Above program is same as to check whether given no is positive or not.

2. if-else

The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false.
It is two way selection statements

If multiple statements have to be executed, it has to be written into pair of braces. If only one
statement has to be executed then use of pair of braces is optional.

Dr Shobha N, Asst Prof, CSE Page 3


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Syntax:

if (test expression)
{
Statements will execute if test expression is true;
}
else
{
Statements will execute if test expression is false;
}

‘C’ programming using simple if-else statement:

1. WAC program to check whether user is eligible for voting or not

# include <stdio.h>
void main()
{
int age;
printf("Enter the person age");
scanf("% d",&age);

if(age>=18)
{

printf("person is eligible to vote");


//printf("Hello world");
}

else
printf("person is not eligible to vote");

Dr Shobha N, Asst Prof, CSE Page 4


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

2. Write a C program to check whether a number entered by user is even or odd

#include<stdio.h>
void main()
{
int n;
printf(“Enter the value of n”);
scanf(“% d”,&n);

if(n% 2==0) // checking whether number even or not


{
printf(“given number is even number);
}
else
{

printf(“given number is odd number);

}
}

3. Program to accept a number and check the given number is Armstrong or not.
# include <stdio.h>
void main( )
{
int n, a, b, c, d;
printf ("Enter a Three Digit Number: ");
scanf ("%d", &n);
a=n/100; 1 153 = 13+53+33 =1+125+27= 153 153/100
123 =1+8+27=36

b=((n/10)%10); 5

c=n%10; 3

d=a*a*a+b*b*b+c*c*c;

if (n==d)
printf ("The Given Number is Armstrong number");

else
printf ("The Given Number is Not Armstrong number");

Dr Shobha N, Asst Prof, CSE Page 5


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

4. WAC program to find out biggest of two numbers.


5. Write above program with simple if.
3. Nested if

- Nested if means one if statement contains another if statements.


- Nested if statement also called as multi-way decision.
- The control of program moves into inner if statement when the outer if statement
evaluated true.
Syntax:-

if (Expression 1)
{
if (expression 2)
{
Block- A;
else
Block –B;
}
}
else
{
Block-c;
}

Flowchart for nested-if :-


True

Exp1 False
Exp2

False True

Block-B
Block-A

Block-C

Program to find greatest of three numbers using if else

#include <stdio.h>

int main()
{

Dr Shobha N, Asst Prof, CSE Page 6


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

int a, b, c, ;

printf("\n enter the value of a b c");


scanf("%d%d%d", &a, &b, &c);
if(a>b)
{
if(a>c)

printf("\n a is greater");
else
printf("\n c is geater");

else
{
if(c>b)
printf("\n c is greater");
else
printf("\n b is greater");

}
return 0;
}

‘C’ programming using nested- if statement:


1. WAC program to find greatest number among 3 numbers.

4. Else- if ladder

Dr Shobha N, Asst Prof, CSE Page 7


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

The nested if...else statement is used when program requires more than one test
expression.

Syntax :-
if (test expression1)
{
Statements will execute if test expression1 is true;
}
else if(test expression2)
{
Statements will execute if test expression1 is false and expression2 is true;
}

else if (test expression3)


{
Statements to be executed if test expression1 and expression2 are false and test expression 3 is true;
}
….
….
else
{
Statements to be executed if all conditions are false;
}

How nested if...else works?

Nested if()...else statements take more execution time compared to an if()...else ladder because the
nested if()...else statements check all the inner conditional statements once the outer
conditional if() statement is satisfied,
whereas the if()..else ladder will stop condition testing once any of the if() or the else
if() conditional statements are true.

‘C’ programming using else- if ladder statement:

1. WAC program to check grade.

#include<stdio.h>
void main( )
{

Dr Shobha N, Asst Prof, CSE Page 8


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

int marks;

printf(“Enter the marks ”);


scanf(“%d”, &marks);

if(marks<=34)
printf(“Grade Fail”);
else if(marks<=59)
printf(“Grade Second”);
else if(marks<=69)
printf(“Grade First”);
else if(marks<=79)
printf(“Grade Distinction”);
else
printf(“Grade out standing”);

int main()
{

int marks;

printf("\n enter the marks");


scanf("%d", &marks);

if(marks<=34)
printf("Grade Fail");
else if(marks<=59)
printf("Grade Second");
else if(marks<=69)
printf("Grade First");
else if(marks<=79)
printf("Grade Distinction");
else
printf("Outstanding");

return 0;
}

2. WAC program to display the output stop, ready, or go based on traffic signal input
given by user.

#include<stdio.h>
void main( )

Dr Shobha N, Asst Prof, CSE Page 9


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

{
char s;
printf ("enter the light colour");
scanf("%c",&s);

if (s=='r')
printf("Red-stop at signal");
else if (s=='g')
printf("Green-go");
else if(s=='y')
printf("Yellow- ready to move");
}

3. Write a C program to relate two intege rs entered by user using = or > or <
sign.

#include<stdio.h>
Void main()
{
int n1 ,n2 ;
printf(“enter two numbers to check”);
scanf(% d% d”, n1,n2)
if (n1== n2)
printf(“entered number are equal”);
else
if (n1>n2)
printf(“n1 is greater number”);
else
printf(“n2 is greater number”);
}

5. Switch

A switch statement is a conditional statement, which tests a value between many


different values. (When decision has to made between many alternatives)

It should begin with switch keyword followed by value expression in parenthesis.

Value expression can be integer value or character.

Syntax:-

Dr Shobha N, Asst Prof, CSE Page 10


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

switch( expression )
{
case value1: statements1;
break;
case value 2: statements2;
break;
case value 3: statements3;
break;
……
……
[default : statements4;]
}

‘C’ programming using switch statement:

1. WCP to display the output stop, ready, go.


#include<stdio.h>
void main( )
{
Char s;
Printf (“enter the colour”);
Scanf(“%c”,&s);

switch (s)
{
case ‘r’ : printf(“stop at signal”);

break;
case ‘y’ : printf(“ready to go”);

break;

Dr Shobha N, Asst Prof, CSE Page 11


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

case ‘g’ : printf(“go”);

break;
default : printf(“error in giving input”);

break;

2. Program to accept any single digit number and print it in words .


# include <stdio.h>
Void main( )
{

int n;
clrscr( );
printf(“enter a number :”);
scanf(“%d “,&n);
switch(n)
{
case 0: printf(“ZERO”);
break;
case 1: printf(“ONE”);
break;
case 2: printf(“TWO”);
break;
case 3: printf(“THREE”);
break;
case 4: printf(“FOUR”);
break;
case 5: printf(“FIVE”);
break;
case 6: printf(“SIX”);
break;
case 7: printf(“SEVEN”);
break;
case 8: printf(“EIGHT”);
break;
case 9: printf(“NINE”);
break;

default:
printf(“please enter the number between 0 and 9”);
}
}

Dr Shobha N, Asst Prof, CSE Page 12


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

int n;

printf("enter a number :");


scanf("%d",&n);
switch(n)
{
case 0: printf("ZERO");
break;
case 1: printf("ONE");
break;
case 2: printf("TWO");
break;
case 3: printf("THREE");
break;
case 4: printf("FOUR");
break;
case 5: printf("FIVE");
break;
case 6: printf("SIX");
break;
case 7: printf("SEVEN");
break;
case 8: printf("EIGHT");
break;
case 9: printf("NINE");
break;

default:
printf("please enter the number between 0 and 9");
}

3. WAC program to get the number through keyboard and print whether it is divisible
by 3 and 5 both. Hint: ( if (n%3==0 &&n%5==0)

Unconditional branch statements


An unconditional branch statement is a construct which alter the sequential control flow without
checking any condition.

1. break
2. continue
3. goto

Dr Shobha N, Asst Prof, CSE Page 13


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

1. break
1. used to break any type of loop as well as switch statements
2. breaking loop means terminating loops
3. break statements will be the last statement.
4. In break, control comes out of loop and statement following loop will be executed
5. If break appears in the inner loop of nested loop, control comes out of inner loop only,
not from outer loop

Example:

#include<stdio.h>

void main()

int i=1;

while(i<=8)

printf("%d\t", i);

if(i==7)

break;

i++;

2. Continue

Continue statement break the current iteration.

int main()
{
int i;

for(i=1;i<=5;i++)
{
if(i==2) continue;
printf("%d\t",i);
}

Dr Shobha N, Asst Prof, CSE Page 14


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

return 0;
}

3. goto

it transfer the control to the specified statement in a program.

Syntax:

goto label_name
_____
_____

label_name: statements;

disadvantage
Using goto and writing program is an unstructured programming.
It is difficult to debug the program.

int main()
{
int i=0, n, sum=0;

printf("enter the number of terms");


scanf("%d", &n);

top: sum=sum+i;
i=i+1;
if(i<=n)goto top;

printf("sum of series=%d", sum);

return 0;
}

Dr Shobha N, Asst Prof, CSE Page 15


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

1. Looping (Repetition)

Looping means Execution of same set of instruction for given number of times OR until a
specified result obtained.

Q What is pre-test loop?

- If the condition is checked before each iteration of loop, such loops called as pre-test loop.

- Conditional expression is evaluated true or false at the beginning of loop.

Since in pre-test loop, condition is checked at the top of loop so called as top-testing or entry
controlled loop.

Ex: for, while loop.

Body of loop

Q What is post-test loop?

- If the condition is checked after each iteration of loop, such loops called as post-test loop.

- First body of loop is executed then expression evaluated true or false.

Since condition is checked at the bottom of loop it is also called as bottom-testing or Exit
controlled loop. Ex. Do-while loop

- In post test, body of test condition is executed at least once.(one OR more times)

Body of loop

Loops in ‘c ‘ Language:-

Dr Shobha N, Asst Prof, CSE Page 16


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

1. While loop :-
The while loop checks whether the test expression is true or not. If it is true, code
inside the body of while loop is executed, that is, code inside the braces { } are
executed.

Then again the test expression is checked whether test expression is true or not. This
process continues until the test expression becomes false

Syntax:-

while ( expression )
{
Single statement
or
Block of statements;
}

Flowchart:

Dr Shobha N, Asst Prof, CSE Page 17


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

BASIS FOR
WHILE DO-WHILE
COMPARISON

General Form while ( condition) { do{

statements; //body of loop .

} statements; // body of loop.

} while( Condition );

Controlling In 'while' loop the controlling In 'do-while' loop the

Condition condition appears at the start controlling condition appears at

of the loop. the end of the loop.

Iterations The iterations do not occur if, The iteration occurs at least

the condition at the first once even if the condition is

iteration, appears false. false at the first iteration.

Alternate name Entry-controlled loop Exit-controlled loop

Semi-colon Not used Used at the end of the loop

‘C’ programming using while-loop :


1. ‘C’ Program to print natural number from 1 to 10 by

# include <stdio.h>
Output:

Dr Shobha N, Asst Prof, CSE Page 18


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Void main( ) 1 2 3 4 5 6 7 8 9 10
{
int i=1;
while( i<=10)
{
printf(“%d\n”,i);
i=i+1;
}
}

2. ‘c’ program to print square of number .


#include<stdio.h>
Void main( )
{
int i=1 , j=1;
while (i <=5)
{
j=i*i;
Printf(“%d\t %d”, i ,j);
i=i+1;
}
}

Output:
1 1
2 4
3 9
4 16
5 25

3. ‘C’ Program to print number from 1 to 10 in reverse order.


# include <stdio.h>
Void main( ) Output:
{ 10 9 8 7 6 5 4 3 2 1
int n =10;
while ( n>=0)
{
printf(“%d \n”,n);
n--;
}

4. WAC program to find gcd and lcm of given integers.

#include<stdio.h>
void main()
{

Dr Shobha N, Asst Prof, CSE Page 19


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

int a,b,m,n;
int lcm,gcd,r;
Output:
clrscr(); Input - m=4 n=2
printf("Enter two numbers\n"); Gcd=
scanf("%d%d",&m,&n); Lcm=
a=m;
b=n;
while(n!=0)
{
r=m%n;
m=n;
n=r;
}
gcd=m;
lcm=(a*b)/gcd;
printf("GCD =%d“, gcd);
printf("LCM =%d” , lcm);
}

5. Write a C program to find the factorial of a numbe r, whe re the numbe r is


ente red by use r. (Hints: factorial of n = 1*2*3*...*n

Method-1 Method-2
#include<stdio.h> #include<stdio.h>
Void main( ) Void main( )
{ {
int n, fact=1 ; int n ,temp , fact=1;
printf(“enter the number”); printf(“enter the number”);
scanf(“% d”,&n); scanf(“% d”,&n);
while(n>0) temp=n;
{ while (n>0)
fact=fact*n; {
--n; fact=fact*temp;
} temp=temp-1;
Printf(“factorial=% d”,fact); }
} printf(“% d\n”, fact);
}
Output:
Enter number=5
Factorial=120
6. WAC program that will generate and print first n Fibonacci numbers.
#include<stdio.h>
Void main( )
{

Dr Shobha N, Asst Prof, CSE Page 20


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

int i=0, j=0, n , sum=1;


printf(“enter the limit of series”);
scanf(“%d”, &n);
while(sum<n)
{
Printf(“%d”, sum);
i=j;
j=sum;
sum=i+j;
}
Printf(“sum of series=%d”, sum);
}

Output: Limit of series n=5 --- 1 1 2 3 5

2. Do -While loop :-

Syntax:

do
{
statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the
loop execute again. This process repeats until the given condition becomes false.

Dr Shobha N, Asst Prof, CSE Page 21


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in C programming language checks its condition at the bottom of the
loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.

do ... while is just like a while loop except that the test condition is checked at the end of the
loop rather than the start. This has the effect that the content of the loop are always executed
at least once.

‘C’ programming using Do-While loop :

1. ‘c’ program to print numbers from 10 to 19 using do-while loop

#include <stdio.h> Output:


void main () value of a: 10
{ value of a: 11
int a = 10; // local variable definition value of a: 12
value of a: 13
do value of a: 14
{ value of a: 15
value of a: 16
printf("value of a: %d\n", a);
value of a: 17
a = a + 1; value of a: 18
} while( a < 20 ); value of a: 19
}

2. ‘c’ program to print number using conditional statement.

#include <stdio.h>
Value of i is 1
Value of i is 2

Dr Shobha N, Asst Prof, CSE Page 22


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Value of i is 3
Void main() Value of i is 4
{
int i=1;
do
{
printf("Value of i is %d\n",i);
i++;

} while (i<=4 && i>=2);

3. ‘c’ program to print number in reverse order.

#include <stdio.h>

main()
{
int i = 10;
do
{
printf("Hello %d\n", i );
i = i -1;

}while ( i > 0 );
}

This will produce following output:

Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1

You can make use of break to come out of do...while loop at any time.

Dr Shobha N, Asst Prof, CSE Page 23


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

#include <stdio.h>

main()
{
int i = 10;

do{
printf("Hello %d\n", i );
i = i -1;
if( i == 6 )
{
break;
}
}while ( i > 0 );
}

This will produce following output:

Hello 10
Hello 9
Hello 8
Hello 7
Hello 6

Ex ample 1 :

int main()
{
int j=0
do
{
printf("Value of variable j is: %d", j);
j++;
} while (j<=5);

}
Output:
Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3
Value of variable j is: 4
Value of variable j is: 5
Value of variable j is: 6

Dr Shobha N, Asst Prof, CSE Page 24


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Ex ample 2 :

#include <stdio.h>
main()
{
int j = -5; // initialization
do
{
printf("%d\n", j);
j = j + 1;
}
while(j <= 0); // condition

4. Write a C program to add all the numbers ente red by a user until user
ente rs 0.
#include<stdio.h>
Void main()
{
int sum=0,num;
Output :-
do Enter number 3
{ Enter number -2
Printf(“enter the number”); Enter number 0
scanf(“% d”,&num); Sum=1
sum=sum+num;
}
While (num!=0);
Printf(“sum=% d”,sum);
}
In this C program, user is asked a number and it is added with sum. Then, only the test
condition in the do...while loop is checked. If the test condition is true,i.e, num is not
equal to 0, the body of do...while loop is again executed until num equals to zero.

BASIS FOR
WHILE DO-WHILE
COMPARISON

General Form while ( condition) { do{

statements; //body of loop .

Dr Shobha N, Asst Prof, CSE Page 25


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

BASIS FOR
WHILE DO-WHILE
COMPARISON

} statements; // body of loop.

} while( Condition );

Controlling In 'while' loop the controlling In 'do-while' loop the

Condition condition appears at the start controlling condition appears at

of the loop. the end of the loop.

Iterations The iterations do not occur if, The iteration occurs at least

the condition at the first once even if the condition is

iteration, appears false. false at the first iteration.

Alternate name Entry-controlled loop Exit-controlled loop

Semi-colon Not used Used at the end of the loop

3. The for loop

Dr Shobha N, Asst Prof, CSE Page 26


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Syntax:-
for ( initialization ; condition test ; increment or decrement)
{
statements needs to be repeated;

}
How for loop works in C programming?
The initialization statement is executed only once at the beginning of the for loop.
Then the condition test is checked by the program. if test condition is true then the
statements inside body of for loop is executed. Afterwards increment /decrement will
be done. If the test expression is false, for loop is terminated.

Example 1 :
#include<stdio.h>
Void main()
{
int i; Output:
for (i=1; i<=3; i++) hello, World
hello, World
{
hello, World
printf("hello, World\n");
}
}

Explanation:

Dr Shobha N, Asst Prof, CSE Page 27


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

The for loop in C is executed as follows:

1. The initial counter value is initialized. This initialization is done only once for the
entire for loop.
2. After the initialization, test condition is checked. Test condition can be any relational
or logical expression. If the test condition is satisfied i.e. true then the block of statement
inside the for loop is executed
3. After the execution of the block of statement, increment/decrement of the counter is
done. After performing this, the test condition is again evaluated. The step 2 and 3 are
repeated till the test condition returns false.

Example 2 :

#include<stdio.h>
void main() Output:
{ 1 1 This will be repeated 5 times
int i; 2 2 This will be repeated 5 times
for(i=1; i<=5;i++) 3 3 This will be repeated 5 times
{
printf("%d This will be repeated 5 times\n", i); 4 4 This will be repeated 5 times
5 5 This will be repeated 5 times
}
6 End of the program
printf("End of the program");
}

In the above program, value 1 is assigned to i. The for loop would be executed till the value
of i is less than or equal to 5.

Example 3 :

Note : It is necessary to write the semicolon in for loop as shown in the below:

for( i= 1; i< 10 ; i++)

Consider, case 1:

1 for(i=0; i<10;)
2{
3 printf(“Interment/decrement not used above”)
4 i=i+1;
5}

In the above program, Increment is done within the body of for loop. Still semicolon is
necessary after the test condition.

Dr Shobha N, Asst Prof, CSE Page 28


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Consider, case 2 :

1 i=0;
2 for(; i<10; i++)
3{
4 printf(“Interment/decrement not used above”)
5}

In the above program, Initialization is done before the start of for loop. Still semicolon is
necessary before the test condition.
Example 4 :

#include<stdio.h>
Void main()
{
const int max=5;
int i ;
for(i=0 ;i<max ;i++)
printf(%d”,i)
}

Output:- 0 1 2 3 4

Example 5 :

#include<stdio.h>
void main()
{
int i;
for(i=0; i<10 ; i++)
{
printf("hello\n");
printf("world \n");
}
}

Example 5 :

#include <stdio.h>
int main() Output:
{
int i; 0123456789
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}

Dr Shobha N, Asst Prof, CSE Page 29


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

‘C’ programming using for loop :

1. Program to print ODD numbers from 1 to 10


# include <stdio.h>
void main( )
{
int i;
for (i=1; i<=10; i+=2)

printf(“%d\n”,i);
}

2. Program to print natural numbers from 1 to 10 in Reverse


# include <stdio.h>
Void main( )
{
int i;
for (i=10; i>=1; i--)
printf(“%d\n”,i);
}

3. Program to accept a number and print mathematical table of the given no.
# include <stdio.h>
main( )
{
int i,t;
printf(“which table u want:”);
scanf(“%d”,&t);
for (i=1; i<=10; i++)
printf(“\n%d*%d=%d”, t ,i , i*t);
}

4. Write a program to find the sum of first n natural numbers where n is entered
by user. Note: 1,2,3... are called natural numbers.
#include<stdio.h>
Main()
{
int n, count,sum=0;
Printf(“enter value of n”);
Scanf(%d”,&n);
For (count=1; count<=n ; ++count)
{
Sum=sum+count;
}
Printf(summation=%d”,sum);
}
Output:

Dr Shobha N, Asst Prof, CSE Page 30


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

The infinite loop

A loop becomes infinite loop if a condition never becomes false.

int main()

for( ; ;)

printf("loop will run forever");

Nested for Loops

main ()
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j <3; j++)
{
printf ("% d,% d ",i, j);
}
printf("\n");
}

0,0 0,1 0,2


1,0 1,1 1,2
2,0 2,1 2,2

main ()
{
int i, j;

for (i=1; i<=10; i++)


{
for (j=1; j<=10; j++)
{

Dr Shobha N, Asst Prof, CSE Page 31


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

printf ("% d*% d=% d ", i,j,i*j);


}

printf("\n");
}

1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9 1*10=10
2*1=2 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18
2*10=20
3*1=3 3*2=6 3*3=9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27
3*10=30
4*1=4 4*2=8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36
4*10=40
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45
5*10=50
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 6*7=42 6*8=48 6*9=54
6*10=60
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63
7*10=70
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 8*9 =72
8*10=80
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
9*10=90
10*1=10 10*2=20 10*3=30 10*4=40 10*5=50 10*6=60 10*7=70 10*8=80
10*9=90 10*10=100

Program to print right angle triangle

int main()

int i,j,k;

for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(" %d",i);
}
printf("\n");
}

Dr Shobha N, Asst Prof, CSE Page 32


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

22

333

4444

55555

Program to print right angle triangle

int main()

int i,j,k;

for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(" %d",j);
}
printf("\n");
}
}

12

123

1234

12345

To print number pyramid using for loop

int main()

int i,j,k;

for(i=1;i<=5;i++)

for(j=4;j>=i;j--)

Dr Shobha N, Asst Prof, CSE Page 33


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

printf(" ");

for(k=i;k>=1;k--)
printf(" %d ",k);

printf("\n");

2 1

3 2 1

4 3 2 1

5 4 3 2 1

Character triangle

main ()
{
int i, j;

for (i=65; i<=70; i++)


{
for (j=65; j<=i; j++)

printf ("%c", j);


printf("\n");
}
}

A
AB
ABC
ABCD
ABCDE
ABCDEF

void main ()
{
int i, j;

for (i=0; i<3; i++)

Dr Shobha N, Asst Prof, CSE Page 34


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

{
for (j=0; j<3; j++)
{
printf (" * ");
}
printf("\n");
}

* * *
* * *
* * *

void main ()
{
int i, j;

for (i=0; i<=3; i++)


{
for (j=0; j<=i; j++)
{
printf (" * ");
}
printf("\n");
}

*
* *
* * *
* * * *

Dr Shobha N, Asst Prof, CSE Page 35


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Program to find binomial coefficient

nCr = n!/r!(n-r)!

1. C program to calculate binomial coefficient


#include <stdio.h>
void main()
{
int n,i,r;
int x,y,z,ncr;
printf("Enter the value of n and r");
scanf("%d%d",&n,&r);
x=y=z=1;
//x for factorial n
for(i=n;i>=1;i--)
{
x=x*i;
}
//y for factorial n-r
for (i=n-r;i>=1;i--)
{
y=y*i;
}
// z for factorial r
for(i=r;i>=1;i--)
{
z=z*i;
}
ncr=x/(y*z);
printf("%dC%d=%d",n,r,ncr);
}
Output:
Enter the value of n and r 4 2
4C2=6

Dr Shobha N, Asst Prof, CSE Page 36


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

Pascal’s triangle

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

0C0
1C0 1C1
2C0 2C1 2C2
3C0 3C1 3C2 3C3
4C0 4C1 4C2 4C3 4C4

nCr= n!/r!(n-r)!=0C0=0!/0!(0-0)!=1

nCr = n!/r!(n-r)!
if r==0, 0C0 , 1C0 , 2C0, 3C0, 4C0 = 1
else

nCr= nCr-1 * (n-r+1)/r =


1* (4-1+1)/1 = 4
= 4*(4-2+1)/2= 4*3/2=12/2=6

#include <stdio.h>
int main()
{
int n,r,row, space, ncr;

Dr Shobha N, Asst Prof, CSE Page 37


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

printf("\n enter number of rows");


scanf("%d", &row);
for(n=0;n<row;n++)
{

for(space=1;space<row-n;space++)

{
printf(" ");
}

for(r=0;r<=n;r++)
{
if(n==0||r==0)
{
ncr=1;
printf(" %d ",ncr);
}
else
{
ncr=ncr*(n-r+1)/r;
printf(" %d ",ncr);
}
}
printf("\n");
}
}

Dr Shobha N, Asst Prof, CSE Page 38


C Progr amming for Problem Solving (18CPS13/23), Module-2 BNM Institute of T echnolo gy

a=1, b=2, c=3,d=4


e=a<b>=c!=a==b<=a

e=a+b<b+c>=c/a==d*a-b;

a+b<b+c&&c/a==d*b||b/a>c

100/20<=10-5+100%10-20==5>=1!=20

8>5&&3==1!=0<3

Dr Shobha N, Asst Prof, CSE Page 39

You might also like