Unit - 2
Unit - 2
Unit - 2
UNIT-2
Control Structures
Simple sequential programs Conditional Statements (if, if-else, switch), Loops (for, while, do while)
Break and Continue.
The control statements help users specify the order of execution of the instructions present in a program.
These make it possible for the program to make certain decisions, perform various tasks repeatedly, or even
jump from any one section of the code to a different section. Control statements serve to control the
execution flow of a program.
Control statements in C are classified into selection statements, iteration statements, and jump statements.
Selection statements serve to execute code based on a certain circumstance. Iteration statements loop
through a code block until a condition is met. Jump statements serve to move control from one section of a
program to another.
The if statement, for loop, while loop, switch statement, break statement, and continue statement are C's
most widely used control statements.
A selection statement selects among a set of statements depending on the value of a controlling expression.
Or
Moving execution control from one place/line to another line based on condition
Or
Conditional statements control the sequence of statement execution, depending on the value of a integer
expression
1
1: if
2: switch.
1: simple if statement.
2: if –else statement
4: else if ladder.
1: simple if statement:
Syntax: if (condition/expression)
True statement;
Statement-x;
Working:
If the condition/expression is true, then the true statement will be executed otherwise the true Statement
block will be skipped and the execution will jump to the statement-x. The “true statement‟ may be a single
statement or group of statement.
If there is only one statement in the if block, then the braces are optional. But if there is more than one
statement the braces are compulsory
Flowchart:
2
Example 1:
#include<stdio.h>
int main()
{
int number;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
return 0;
}
Output:
Enter a number: 4
4 is even number
Output
2. If-else Statement: The if-else statement is an extension of the simple if statement. The general form
is. The if...else statement executes some code if the test expression is true (nonzero) and some other code
if the test expression is false (0).
Syntax:
if (condition)
{
true statements;
}
else
{
false statements;
}
Statement-x;
Working:
If the condition is true, then the true statement and statement-x will be executed and if the condition is false,
then the false statement and statement-x is executed.
Or
If test expression is true, codes inside the body of if statement is executed and, codes inside the body of
else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes inside the body of
if statement is skipped.
Flowchart:
4
Example:
Program to check whether an integer entered by the user is odd or even
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output:
Enter an integer: 7
7 is an odd integer.
5
Program to check whether a person is eligible to vote or not.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
}
}
Output
Example
#include<stdio.h>
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2");
7
//Below – if-else is nested inside another if block
if (var1 >var2)
{
else
{
printf("var2 is greater than var1");
}
}
else
{
{
int i = 10;
if (i = = 10)
{
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
if (i < 12)
printf("i is smaller than 12 too\n");
else
8
return 0;
Output
i is smaller than 15
int main()
if(num1>num2)
if(num1>num3)
else
else
9
/* This is nested if-else */
if(num2>num3)
else
return(0);
Output:
Run 1:
---------------
12↲
33↲
-17↲
Largest = 33
Run 2:
---------------
-18↲
-31↲
10
-17↲
Largest = -17
4. if-else- if ladder:
in C programming, if-else-if statement is also known as if-else-if ladder. It is used when there are more
than two possible action based on different conditions.
Syntax:
if( condition-1)
Statement-1;
else if(condition-2)
Statement-2;
else if(condition-3)
Statement-3;
else if(condition-n)
Statement-n;
else
Default-statement;
11
}
Statement-x;
Working:
In the above syntax of if-else-if, if the Condition1 is TRUE then the Statement1 will be executed
and control goes to next statement in the program following if-else-if ladder.
If Condition1 is FALSE then Condition2 will be checked, if Condition2 is TRUE then Statement2
will be executed and control goes to next statement in the program following if-else-if ladder.
Similarly, if Condition2 is FALSE then next condition will be checked and the process continues.
If all the conditions in the if-else-if ladder are evaluated to FALSE, then Default Statement will be
executed.
Flow Chart:
Example: Program to calculate the grade of the student according to the specified marks.
#include <stdio.h>
int main()
12
{
int marks;
printf("Enter your marks?");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A ...");
}
{
printf("You scored grade C ...");
}
else
{
printf("Sorry you are fail ...");
}
}
Output:
13
Congrats! You scored grade A...
Example 2: C program to find largest from three numbers given by user to explain working of if-
else-if statement or ladder
#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter three numbers: \n");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
{
printf("Largest = %d", a);
}
else if(b>a && b>c)
{
printf("Largest = %d", b);
}
else
{
printf("Largest = %d", c);
}
return(0);
}
Output
Run 1:
-------------
Enter three numbers:
12 ↲
33 ↲
-17 ↲
Largest = 33
Run 2:
-------------
Enter three numbers:
-18 ↲
-31 ↲
14
-17 ↲
Largest = -17
#include<stdio.h>
int main()
{
int day;
printf("Enter day number: ");
scanf("%d", &day);
if(day==1)
{
printf("SUNDAY.");
}
else if(day==2)
{
printf("MONDAY.");
}
else if(day==3)
{
printf("TUESDAY.");
}
else if(day==4)
{
printf("WEDNESDAY.");
}
else if(day==5)
{
printf("THURSDAY.");
}
else if(day==6)
{
15
printf("FRIDAY.");
}
else if(day==7)
{
printf("SATURDAY.");
}
else
{
printf("INVALID DAY.");
}
return(0);
}
Output:
Run 1:
-------------
Enter day number: 4↲
WEDNESDAY.
Run 2:
-------------
Enter day number: 2↲
MONDAY.
Run 3:
-------------
Enter day number: 10↲
INVALID DAY.
#include<stdio.h>
int main()
16
printf("Enter four numbers:\n");
lg = a;
lg = b;
lg = c;
else
lg = d;
return(0);
Output:
Run 1:
-------------
17
Enter four numbers:
21.4↲
54.4↲
34.5↲
-67.5↲
Largest = 54.400000
Switch statement:
When there are several options and we have to choose only one option from the available ones, we can use
switch statement. Depending on the selected option, a Particular task can be performed. A task represents
one or more statements.
Syntax:
switch (expression)
case value-1:
statement/block-1;
break;
case value-2:
statement/block t-2;
break;
case value-3:
statement/block -3;
break;
case value-4:
statement/block -4;
18
break;
default:
default- statement/block t;
break;
The expression following the keyword switch in any „C‟ expression that must yield an integer value. It
must be an integer constants like 1, 2, and 3.
The keyword case is followed by an integer or a character constant, each constant in each must be different
from all the other. First the integer expression following the keyword switch is evaluated. The value it gives
is searched against the constant values that follow the case statements. When a match is found, the program
executes the statements following the case. If no match is found with any of the case statements, then the
statements following the default are executed.
3: The default is optional and can be placed anywhere, but usually placed at end.
19
The working of the switch statement in C is as follows:
Step 1: The switch variable is evaluated.
Step 2: The evaluated value is matched against all the present cases.
Step 3A: If the matching case value is found, the associated code is executed.
Step 3B: If the matching code is not found, then the default case is executed if present.
Step 4A: If the break keyword is present in the case, then program control breaks out of the switch
statement.
Step 4B: If the break keyword is not present, then all the cases after the matching case are executed.
Step 5: Statements after the switch statement are executed.
Example:
#include<stdio.h>
main()
{
int a;
switch(a)
{
case 1:
printf("You chose One");
20
break;
case 2:
printf("You chose Two");
break;
case 3:
break;
case 5: printf("You chose Five.");
break;
default :
OUTPUT:
Points to Remember
It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of codes
will get executed after the matching block
21
Output: A B C
The output was supposed to be only A because only the first case matches, but as there is no break statement
after the block, the next blocks are executed, until the cursor encounters a break.
default case can be placed anywhere in the switch case. Even if we don't include the default case switch
statement works.
#include<stdio.h>
int main()
int day;
scanf("%d", &day);
switch(day)
case 1: printf("SUNDAY.");
break;
case 2: printf("MONDAY.");
break;
22
case 3: printf("TUESDAY.");
break;
case 4: printf("WEDNESDAY.");
break;
case 5: printf("THURSDAY.");
break;
case 6: printf("FRIDAY.");
break;
case 7: printf("SATURDAY.");
break;
break;
return(0);
Output:
run 1:
------------------
Enter day number: 3↲
TUESDAY.
Run 2:
------------------
Enter day number: -3↲
INVALID DAY.
#include<stdio.h>
int main()
23
{
float a,b, r;
char op;
printf("Available Operations.\n");
printf("Which Operation?\n");
scanf("%c", &op);
switch(op)
scanf("%f%f",&a, &b);
r = a+b;
break;
scanf("%f%f",&a, &b);
r = a-b;
break;
scanf("%f%f",&a, &b);
r = a*b;
24
printf("%f * %f = %f", a, b, r);
break;
scanf("%f%f",&a, &b);
if(b!=0)
r = a/b;
printf("%f/%f = %f",a,b,r);
else
break;
break;
return(0);
Output:
Run 1:
------------------
Available Operations.
+ for Addition.
- for Subtraction.
25
* for Multiplication.
/ for Division.
Which Operation?
*↲
13↲
17↲
13 * 17 = 221
Run 2:
------------------
Available Operations.
+ for Addition.
- for Subtraction.
* for Multiplication.
/ for Division.
Which Operation?
^↲
Invalid Operation.
How it Works
26
A sequence of statements are executed until a specified condition is true. This sequence of statements to be
executed is kept inside the curly braces { } known as the Loop body. After every execution of loop body,
condition is verified, and if it is found to be true the loop body is executed again. When the condition check
returns false, the loop body is not executed.
The loops in C language are used to execute a block of code or a part of the program several times. In other
words, it iterates/repeat a code or group of code many times.
Or
Looping means a group of statements are executed repeatedly, until some logical condition is satisfied.
Suppose that you have to print table of 2, then you need to write 10 lines of code. By using the
1: for loop
2: while loop
27
3: do-while loop
1: for loop:
The for loop is most commonly used looping statement. It is pre-tested loop and it is used when the number
of repetitions (iterations) are known in advance. The syntax of the loop consists three parts, they are, control
variable initialization, condition and control variable update. These three parts are separated by semicolon.
Note: Curly braces are optional if body of loop consists single statement.
for Loop Working: In for loop control variable is initialized first. After initialization of control variable,
it tests condition. Based on the outcome of condition, loop is continued or stopped.
If the condition evaluates to FALSE, then loop will be terminated (goes to next statement following loop).
If the condition evaluates to TRUE, then statements within body of loop are executed.
After execution of statements, value of loop control variable is updated and condition is checked again.
And the process is repeated.
28
Example: Program to print “Programming is fun.” 10 times
#include<stdio.h>
int main()
int i;
for(i=1;i<=10; i++)
printf("Programming is fun.\n");
return(0);
Output:
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
#include<stdio.h>
29
int main()
int i, n;
printf("Enter n: ");
scanf("%d", &n);
for(i=1;i<=n; i++)
printf("Programming is fun.\n");
return(0);
Output
Enter n: 5 ↲
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
Programming is fun.
While Loop:
Syntax:
Variable initialization;
While (condition)
30
Statements;
#include<stdio.h>
#include<conio.h>
31
void main()
int i;
clrscr();
i=1;
while(i<=10)
printf("%d\n",i);
i++;
getch();
Output
10
32
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
scanf("%d", &num);
while(num!=0)
rem = num%10;
num = num/10;
getch();
Output
Run1:
---------------
Sum is 15
--------------- Run2:
33
Sum is 29
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
scanf("%d", &num);
while(num!=0)
rem = num%10;
num = num/10;
getch();
Output
Run1:
---------------
Reverse is 4321
34
do-while:
Syntax
control_variable_initialization;
do
Statement;
control_variable_update;
} while (condition);
Working:
The do-while loop is an exit controlled loop statement the body of the loop are executed first and then the
condition is evaluated. If it is true, then the body of the loop is executed once again. The process of
execution of body of the loop is continued until the condition finally becomes false and the control is
transferred to the statement immediately after the loop. The statements are always executed at least once.
35
There is given the simple program of c language do while loop where we are printing the table of 1
#include<stdio.h>
int main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
return 0;
Output:
10
Program to print table for the given number using do while loop
#include<stdio.h>
int main(){
int i=1,number=0;
36
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
Output
Enter a number: 5
10
15
20
25
30
35
40
45
50
Example 3: C program to check whether a given number is Palindrome or not using do-while.
#include<stdio.h>
#include<conio.h>
void main()
{
int num, rem, rev=0, copy;
37
clrscr();
copy = num;
do
{
rem = num%10;
rev = rev*10 + rem;
num = num/10;
} while(num!=0);
if(rev==copy)
{
printf("PALINDROME");
}
else
{
printf("NOT PALINDROME");
}
getch();
}
Output:
Run1:
---------------
NOT PALINDROME
Run2:
PALINDROME
38
Unconditional Control Statements
In c, there are control statements that do not need any condition to control the program execution flow.
These control statements are called as unconditional control statements. C programming language provides
the following unconditional control statements...
break
continue
goto
The above three statements do not need any condition to control the program execution flow.
The break statement ends the loop immediately when it is encountered. The break statement is used to
perform the following two things...
2. break statement is also used to terminate looping statements like while, do-while and for.
The syntax for break statement is as follows –
When a break statement is encountered inside the switch case statement, the execution control moves out
of the switch statement directly. For example, consider the following program
#include<stdio.h>
int main()
int day;
switch(day)
case 1: printf("SUNDAY.");
break;
case 2: printf("MONDAY.");
break;
case 3: printf("TUESDAY.");
break;
case 4: printf("WEDNESDAY.");
break;
case 5: printf("THURSDAY.");
break;
case 6: printf("FRIDAY.");
break;
case 7: printf("SATURDAY.");
break;
break;
return(0);
Output:
run 1:
------------------
40
Enter day number: 3↲
TUESDAY.
Run 2:
------------------
INVALID DAY.
When the break statement is encountered inside the looping statement, the execution control moves out of
the looping statements. The break statement execution is as shown in the following figure.
.Example:
#include<stdio.h>
main( )
int i;
if (i==3)
break;
Output
123
continue: The continue statement skips the current iteration of the loop and continues with the next
iteration
41
Example
#include<stdio.h>
main( ){
int i;
if (i==2)
continue;
printf("%d", i)
Output
12345
int i = 0;
42
{
if (i == 4)
break;
printf("%d\n", i);
i++;
Output:
Continue example:
int i = 0;
if (i == 4)
i++;
continue;
printf("%d", i);
i++;
43
Output:
012356789
44
goto Statement:
The goto statement allows us to transfer control of the program to the specified label.
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the goto statement is encountered, the control of the program jumps to
label: and starts executing the code.
Example:
#include<stdio.h>
void main()
int age;
g: //label name
s: //label name
scanf("%d", &age);
if(age>=18)
45
goto g; //goto label g
else
Output:
*****
46