Unit 2 Control Statements
Unit 2 Control Statements
Decision Making
The decision making in a programming language is similar to decision making in real life. In
a programming language, many times we need to execute some set of instructions in one
situation and in another situation, we have to execute other set of instructions. The programmer
uses decision making for specifying one or more conditions to be evaluated by the program.
The decision making always returns the Boolean result true or false.
o if statement
o if-else statement
o if-else-if ladder
o nested if else statement
if statement
It is a simple form of decision making. It decides whether
the statements will be executed or not, i.e., it checks the
condition and returns true if the given condition is satisfied.
Syntax
if(condition)
{
// instructions to be executed;
}
Example : Write a program to check whether the entered
number is less than 10? If yes display the same.
#include<stdio.h>
int main()
{
int num;
printf("Enter the number");
scanf("%d",&num);
if(num<10)
{
printf("Entered number is less than 10");
}
return 0;
}
/*Enter the number 9
Entered number is less than 10*/
/* OR
Enter the number 12*/
if-else statement
The if statement only returns the result when the condition is true. But if we want to returns
something when the condition is false, then we need to use the if-else statement. The if-else
statement tests the condition. If the condition is true, it executes if block and if the condition is
false, it executes the else block.
Syntax
if(condition)
{
// Instructions to be executed
}
else
{
// instructions to be executed
}
OR
if(expression is true)
{
Instruction 1
Instruction 2
}
else
{
Instruction 3
Instruction 4
}
Example 1
Write the program to find roots of quadratic equation using if else
#include<stdio.h>
#include<math.h>
int main()
{
int a,b,c;
float root1,root2;
printf("Enter the coefficients a,b,c");
scanf("%d%d%d",&a,&b,&c);
if(b*b>=4*a*c)
{
root1=-b+sqrt(b*b-4*a*c);
root2=-b-sqrt(b*b-4*a*c);
printf("root1=%f",root1);
printf("\nroot2=%f",root2);
}
else
{
printf("roots are imaginary");
}
return 0;
}
/*Output
Enter the coefficients a,b,c
4
9
2
root1=-2.000000
root2=-16.000000*/
if-else-if ladder
Here a user can take decision among multiple options. It starts execution in a top-down
approach. When the condition gets true, it executes the associated statement, and the rest of the
conditions are bypassed. If it does not find any condition true, it returns the final else statement.
This construct is known as the if else if ladder. The condition is evaluated from the top of ladder
downwards. As soon as a true condition is found, the statement associated with it is executed
and control is transferred to the statement -x (skipping all other ladder). When all n conditions
become false then final else block containing default statement will be executed figure shows
the logic of execution of if else ladder.
#include <stdio.h>
int main()
{
int i;
printf("Enter the value of i");
scanf("%d",&i);
if (i == 10)
{
printf("i is 10");
}
else if (i == 15)
{
printf("i is 15");
}
else if (i == 20)
{
printf("i is 20");
}
else
{
printf("i is not present");
}
return 0;
}
/*Output
Enter the value of i
20
i is 20*/
Example: To find largest number out of four //Grade of student
numbers. #include<stdio.h>
#include<stdio.h> int main()
int main () {
{ int marks;
int a,b,c,d,largest; printf("Enter the marks of a student:");
printf("Enter the values of a,b,c,d: "); scanf("%d",&marks);
scanf("%d%d%d%d",&a,&b,&c,&d); if(marks<=100&&marks>=90)
if(a>b && a>c && a>d) { printf("Grade=AA");
{ largest=a; }
} else if(marks<90&&marks>=80)
else if(b>c && b>a && b>d) { printf("Grade=AB");
{ largest=b; }
} else if(marks<80&&marks>=70)
else if(c>d && c>a && c>b) { printf("Grade=BB");
{ largest=c; }
} else if(marks<70&&marks>=60)
else { printf("Grade=BC");
{ largest=d; }
} else if(marks<60&&marks>=50)
printf("largest number=%d",largest); { printf("Grade=CC");
return 0; }
} else if(marks<50&&marks>=45)
/*Output { printf("Grade=CD");
Enter the values of a,b,c,d: }
25 else if(marks<45&&marks>=40)
36 { printf("Grade=DD");
65 }
32 else if(marks<40&&marks>0)
largest number=65*/ { printf("Fail");
}
else
{
printf("Enter a score between 0 and 100");
}
return 0;
}
/*Output
Enter the marks of a student:
78
Grade=BB*/
Nested if statement
When we write an entire if-else within either the body of if statement or the body of else
statement is called as nested if else. The if – else structure has the following syntax:
if (Condition1)
{
if(Condition2)
{
Statement1;
}
else
{
Statement2;
}
}
else
{
if(Condition3)
{
Statement3;
}
else
{
Statement4;
}
}
In this example of nested if-else, it first tests Condition1, if this condition is TRUE then it tests
Condition2, if Condition2 evaluates to TRUE then Statement1 is executed otherwise
Statement2 will be executed. Similarly, if Condition1 is FALSE then it tests Condition3, if
Condition3 evaluates to TRUE then Statement3 is executed otherwise Statement4 is executed.
How Nested IF ELSE work in C Language?
First, it will check the first if condition i.e. the outer if condition and if it is true, then the outer
else block will be terminated. So, the control moves inside the first or the outer if block. Then
again it checks the inner if condition and if the inner if condition is true, then the inner else
block gets terminated. So, in this case, the outer if and inner if block statements get executed.
Now, if the outer if condition is true, but the inner if condition is false, then the inner if block
gets terminated. So, in this case, the outer if and inner else block statements get executed.
Now, if the outer if condition is false, then the outer if block gets terminated and control moves
to the outer else block. And inside the outer else block, again it checks the inner if condition,
and if the inner if condition is true, then the inner else block gets terminated. So, in this case,
the outer else and inner if block statements get executed.
Now, if the outer if condition is false as well as the if condition inside the outer else blocks also
failed, then the if block gets terminated. And in this case, the outer else and inner else block
statements get executed. This is how statements get executed in Nested if. Now we will see the
flow chart of nested if blocks.
First, it will check the outer if condition, and if the outer if condition is true, then the control
comes inside and it will check the inner if condition, and if the inner if condition is true, then
the outer if block statements and inner if block statements get executed. And after execution,
it will come to end.
Suppose, the outer if condition is true but the inner if condition is failed, then the outer if block
statements and the inner else block statement get executed. And once the statement gets
executed, it will come to end.
Suppose, the outer if condition is failed, then the control directly comes to the else block and
checks the inner if condition. And again, for the inner if condition two options are there. If the
inner if condition is true, then it will execute the outer else block and inner if block statement,
and if the inner if condition is false, then it will execute the outer else block and inner else
block statements and then comes to end.
//Comparison between 3 numbers /*Interest based on variable rate
#include<stdio.h>
P>=10000; R=20%
int main()
{ P>=8000 && P<10000 R=18
int num1, num2, num3; P<8000 R=16*/
printf("Enter three numbers:\n");
scanf("%d%d%d",&num1, &num2, &num3); #include<stdio.h>
if(num1>num2) int main()
{
if(num1>num3)
{
{ float P,N,R,SI;
printf("Largest = %d", num1);
printf("Enter Premier and years");
}
else scanf("%f%f",&P,&N);
{ if(P>=10000)
printf("Largest = %d", num3);
} {
} R=20;
else
}
{
if(num2>num3) else
{
{
printf("Largest = %d", num2);
} if(P>=8000&&P<10000)
else {
{
printf("Largest = %d", num3); R=18;
} }
}
else
return 0;
} {
/*Output R=16;
Enter three numbers: 23 36 65
Largest = 65*/ }
}
SI=P*N*R/100;
printf("Simple interest=%f",SI);
return 0;
}
C switch - case Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possible values of a single variable called switch
variable. Here, We can define various statements in the multiple cases for the different values
of a single variable. The syntax of switch statement is given below:
switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is used to
transfer the program control to a predefined label. The goto statement can be used to repeat
some part of the code for a particular condition. It can also be used to break the multiple loops
which can't be done by using a single break statement. However, using goto is avoided these
days since it makes the program less readable and complicated.
Syntax:
label:
//some part of the code;
goto label;
Example.
/*Multiplication table of number*/
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
return 0;
}
/*Output-
Enter the number whose table you want to print? 12
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120*/
When should we use goto?
The only condition in which using goto is preferable is when we need to break the multiple
loops using a single statement at the same time. Consider the following example.
#include <stdio.h> Example 3. // Program to calculate the sum and
int main() average of positive numbers
{ // If the user enters a negative number, the
int i, j; sum and average are displayed.
for(i=0;i<10;i++) #include <stdio.h>
{ int main()
for(j=0;j<5;j++) {
{ int maxInput = 100;
printf("%d\t %d \n",i,j); int i;
if(j == 3) double number, average, sum = 0.0;
{ for (i = 1; i <= maxInput; i++)
goto out; {
} printf("%d. Enter a number: ", i);
} scanf("%lf", &number);
} /*go to jump if the user enters a negative
out: number*/
printf("came out of the loop"); if (number < 0.0)
} {
/*Output goto jump;
0 0 }
0 1 sum += number;
0 2 }
0 3 jump:
came out of the loop*/ average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
/*Output
1. Enter a number: 21
2. Enter a number: 23
3. Enter a number: 21
4. Enter a number: 25
5. Enter a number: 36
6. Enter a number: -2
Sum = 126.00
Average = 25.20*/
Loop Control Statements in C
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. In loop control structure of the C sequence of statements are executed until
some condition for the termination of loop are satisfied.
Why use loops in C language?
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow
of the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the printf statement 10 times, we can print inside a loop which runs up
to 10 iterations.
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
As the sequence of statements in C are executed until some condition for the termination of
loop are satisfied the programs on loop control structure consists of two segments one known
as body of the loop and other is control statement. The control statement tests the condition and
direct control where to be transmitted. Depending on the position of control statement the loop
control structures are classified in to two types which are entry controlled and exit controlled
loop-controlled structure.
Entry Control Loop Exit Control Loop
Entry control loop checks condition first and The exit control loop first executes the body of
then body of the loop will be executed. the loop and checks condition at last.
If Test condition is false, loop body will not If Test condition is false, loop body will be
be executed. executed once.
The body of the loop may or may not be The body of the loop will be executed at least
executed at all. once because the condition is checked at last
for, while are an example of an entry control Do…while is an example of an exit control
loop loop.
Entry Controlled Loops are used when Exit Controlled Loop is used when checking of
checking of test condition is mandatory test condition is mandatory after executing the
before executing loop body. loop body.
Entry Control Loop Exit Control Loop
In case of loop control structure introduction and location of test condition is important because
repetition of loop body or number execution of statement in the loop body is depending on test
condition. Test condition will transfer the control of execution inside the loop for repetition of
loop body or out of loop. If test condition is wrong it also set infinite loop so loop control
structure consists of
1. Setting and initialization of counter variable.- Generally we use an iterator variable
(like int i = 0;) in the initialization statement to use this variable in the update expression
and in the exit condition of the loop.
2. Body of loop- It has some set of statements that we want to repeat and an update
expression, these are known as the body of the loop.
3. Test condition
4. Update expression - Increment or decrement in the counter variable
Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for
1. do while loop in C
do while loop is exit controlled, loop. Exit controlled means in do while first the code
inside the loop will be executed and then the condition is checked. The do-while loop continues
until a given condition satisfies. It is also called post tested loop. It is used when it is necessary
to execute the loop at least once. The do-while loop is mostly used in menu-driven programs
where the termination condition depends upon the end user.
do while loop syntax
do do
{ {
//code to be executed Do this;
} Do this;
while(condition); --------
}
while(condition is true);
2. while loop
While loop is simplest of all looping structures in C. It is entry-controlled loop. Syntax and
flowchart of while loop is as shown in below.
How while loop works?
Test condition is at the entry of the loop, first test is evaluated and if the condition is true, then
the body of the loop is executed. After execution of body, test condition is once again evaluated
and if it is true body is executed once again. This process is repeated execution of the body
continues until the test condition finally becomes false and control transferred out of loop. On
exit the program continues with statement immediately after the body of the loop. The body of
loop may have one or more statements. The body of loop is enclosed in curly brackets.
while (condition test)
{
//Statements to be executed repeatedly
// Increment (++) or Decrement (--) Operation
}
/*Print sum of 1 to 10nos*/ /*factorial of number*/
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int i=1,sum=0; int a,fact=1;
while(i<=10) printf("enter the number");
{ scanf("%d",&a);
printf("%4d",i); while(a>=1)
sum=sum+i; {
i++; fact=fact*a;
} a--;
printf("\n Sum of 1 to 10 nos= %d",sum); }
return 0; printf("factorial of number= %d",fact);
} return 0;
/*Output }
1 2 3 4 5 6 7 8 9 10 /*Output
Sum of 1 to 10 nos= 55*/ enter the number
5
factorial of number= 120*/
/*sum of digits of number*/ /*sort odd and even nos and take separate addition of odd
and even*/
#include<stdio.h>
#include<stdio.h>
int main()
int main()
{ {
int n, k,sum=0; int n,b,c=1,odd=0,even=0;
printf("Enter number"); printf("Enter number");
scanf("%d",&n);
scanf("%d",&n);
printf("odd\teven");
while(n>0)
while(c<=n)
{ {
k=n%10; b=c%2;
sum=sum+k; if(b==0)
{
n=n/10;
even=even+c;
}
printf("\t%d",c);
printf("sum of digits=%d",sum);
return 0; }
else
}
{
/*Enter number 2365
odd=odd+c;
sum of digits=16*/ printf("\n%d",c);
}
c++;
}
printf("\nsum of even=%d\tsum of odd=%d",even,odd);
return 0;
}
/*Output
Enter number10
odd even
1 2
3 4
5 6
#include<stdio.h>
7 8
int main() 9 10
{ sum of even =30 sum of odd=25*/
int a,i=1,fact=1;
printf("Enter No");
scanf("%d",&a);
do
{
fat=fat*i;
i++;
}
while(i<=a);
printf("factorial=%d",fact);
return 0;
}
3. for loop in C
This is the most popular entry-controlled loop. This statement provides a more concise loop
control structure. This statement allows us to specify three things in single statement. These
are
1. Initialization- setting a loop counter to initial value.
2. Test Condition – test condition on loop counter variable to direct flow of execution.
3. Update expression - Increment or decrement in the counter variable.
Syntax of for loop
for(initialization; check/test condition; update)
{
// body consisting of multiple statements
}
• initialization statement – the loop control variable is initialized here.
• Check/test condition is the condition that determines if the looping should continue.
So long as condition is true, the body of the loop is executed.
• The update statement updates the loop control variable after the statements in the loop
body are executed again if condition is true else exit from the loop.
condition in outer loop. The program control checks whether the condition is true or not. If
the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of the outer
loop and increment or decrement in the outer loop. After incrementing the value of the loop
counter, the condition is checked again. If the condition is true, then the inner loop will be
executed again.
o This process will continue until the condition of the outer loop is true.
Program to demonstrate nested for loop. Working of the program
/*check no is prime or not*/ 1. Outer loop start with i=1 and condition
#include<stdio.h> i<=3 is true. So value of I is printed and
int main() control moves to inner loop.
{ 2. In inner loop j=0 so condition inner loop
int i,j; is true so control enters in the body of inner
for(i=1;i<=3;i++) loop and prints the value of j.
{ 3. Printing of j starts from 0 to the 3 till the
printf("\ni=%d\n",i); condition inside loop becomes false. After
for(j=0;j<=3;j++) false condition control moves to outer loop.
{ 4. Counter variable i in outer loop updated
printf("\t%d\t",j); and becomes 2 again condition is true
} control moves to body of outer loop and
} prints value of i=2.
return 0; 5. Again inner loop start to execute from j=0
} to3. Till the true condition.
/*Output This process repeats till the condition
i=1 outside loop is true when it false control
0 1 2 3 moves out of the outer loop.
i=2
0 1 2 3
i=3
0 1 2 3*/
/*multiplication table of 1 to 10 nos*/
#include<stdio.h>
int main()
{
int i,j,m;
for(i=1;i<=10;i++)
{
for(j=1;j<=10;j++)
{
m=i*j;
printf("%d\t",m);
}
printf("\n");
}
return 0;
}
/*Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100 */
Print following output using for loop Print following output using for loop
1 1
22 23
333 456
4444 7 8 9 10
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int i,j; int i,j=1,k;
for(i=1;i<=4;i++) for(i=1;i<=4;i++)
{ {
for(j=1;j<=i;j++) for(k=1;k<=i;k++)
{ {
printf("%d\t",i); printf("%d\t",j);
} j++;
printf("\n"); }
} printf("\n");
return 0; }
} return 0;
}
Print following output using for loop Print following output using for loop
* 6543210
** 543210
43210
***
3210
****
210
*****
10
#include<stdio.h>
0
int main()
#include<stdio.h>
{ int main()
int i,k; {
for(i=1;i<=5;i++) int i,k;
{ for(i=6;i>=0;i--)
for(k=1;k<=i;k++) {
{ for(k=i;k>=0;k--)
printf("*\t"); {
printf("%d\t",k);
}
}
printf("\n");
printf("\n");
}
}
return 0;
return 0;
} }
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop. he continue statement skips the current iteration
of the loop and continues with the next iteration.
How continue statement works?
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int i; int i;
for (i = 0; i < 10; i++) for (i = 0; i < 10; i++)
{ {
if (i == 4) if (i == 4)
{ {
break; continue;
} }
printf("%d\n", i); printf("%d\n", i);
} }
return 0; return 0;
} }/*Output
/* Output 0
0 1
1 2
2 3
3 5
6
7
8
9