CPPS-Module2
CPPS-Module2
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
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.
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.
printf(“\n Hello”);
}
#include<stdio.h>
void main()
{
int n;
Output 1:- When user enters -2 then, the test expression (num<0) becomes true.
Output 2 :- When user enters 5 then, the test expression (num<0) becomes false and
Print This will execute always.
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.
Syntax:
if (test expression)
{
Statements will execute if test expression is true;
}
else
{
Statements will execute if test expression is false;
}
# include <stdio.h>
void main()
{
int age;
printf("Enter the person age");
scanf("% d",&age);
if(age>=18)
{
else
printf("person is not eligible to vote");
#include<stdio.h>
void main()
{
int n;
printf(“Enter the value of n”);
scanf(“% d”,&n);
}
}
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");
if (Expression 1)
{
if (expression 2)
{
Block- A;
else
Block –B;
}
}
else
{
Block-c;
}
Exp1 False
Exp2
False True
Block-B
Block-A
Block-C
#include <stdio.h>
int main()
{
int a, b, 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;
}
4. Else- if ladder
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;
}
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.
#include<stdio.h>
void main( )
{
int 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;
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( )
{
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
Syntax:-
switch( expression )
{
case value1: statements1;
break;
case value 2: statements2;
break;
case value 3: statements3;
break;
……
……
[default : statements4;]
}
switch (s)
{
case ‘r’ : printf(“stop at signal”);
break;
case ‘y’ : printf(“ready to go”);
break;
break;
default : printf(“error in giving input”);
break;
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”);
}
}
int n;
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)
1. break
2. continue
3. goto
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
int main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==2) continue;
printf("%d\t",i);
}
return 0;
}
3. goto
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;
top: sum=sum+i;
i=i+1;
if(i<=n)goto top;
return 0;
}
1. Looping (Repetition)
Looping means Execution of same set of instruction for given number of times OR until a
specified result obtained.
- If the condition is checked before each iteration of loop, such loops called as pre-test loop.
Since in pre-test loop, condition is checked at the top of loop so called as top-testing or entry
controlled loop.
Body of loop
- If the condition is checked after each iteration of loop, such loops called as post-test loop.
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:-
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:
BASIS FOR
WHILE DO-WHILE
COMPARISON
} while( Condition );
Iterations The iterations do not occur if, The iteration occurs at least
# include <stdio.h>
Output:
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;
}
}
Output:
1 1
2 4
3 9
4 16
5 25
#include<stdio.h>
void main()
{
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);
}
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( )
{
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.
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.
#include <stdio.h>
Value of i is 1
Value of i is 2
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++;
#include <stdio.h>
main()
{
int i = 10;
do
{
printf("Hello %d\n", i );
i = i -1;
}while ( i > 0 );
}
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.
#include <stdio.h>
main()
{
int i = 10;
do{
printf("Hello %d\n", i );
i = i -1;
if( i == 6 )
{
break;
}
}while ( i > 0 );
}
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
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
BASIS FOR
WHILE DO-WHILE
COMPARISON
} while( Condition );
Iterations The iterations do not occur if, The iteration occurs at least
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:
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:
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.
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);
}
}
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:
int main()
for( ; ;)
main ()
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j <3; j++)
{
printf ("% d,% d ",i, j);
}
printf("\n");
}
main ()
{
int 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
int main()
int i,j,k;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(" %d",i);
}
printf("\n");
}
22
333
4444
55555
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
int main()
int i,j,k;
for(i=1;i<=5;i++)
for(j=4;j>=i;j--)
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;
A
AB
ABC
ABCD
ABCDE
ABCDEF
void main ()
{
int i, j;
{
for (j=0; j<3; j++)
{
printf (" * ");
}
printf("\n");
}
* * *
* * *
* * *
void main ()
{
int i, j;
*
* *
* * *
* * * *
nCr = n!/r!(n-r)!
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
#include <stdio.h>
int main()
{
int n,r,row, space, ncr;
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");
}
}
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