ITP Notes for I B.
Tech CSM - A, SVCET, Chittoor
NIT - II
U
Control Structures
Control statements control the flowofexecutionofthestatementsofaprogram.Thevarious
types of control statements in C language are as under:
I. Sequential
II. Conditional
III. Iteration
Sequential control:
In sequential control, the C program statements are executed sequentially i.e., one after the
another from beginning to end.
xample for simple sequential program
E
#include<stdio.h>
int main()
{
int x , y, sum;
printf(“Enter the two numbers”);
scanf(“%d%d”,&x,&y);
sum=x+y;
printf(“The sum of the two numbers is =%d”,sum);
}
Output:
Enter the two numbers33
4
The sum of the two numbers is =37
Conditional Control Structure/Statement (Selection Control or Decision Control):
● In conditional control , the execution of statements depends upon the condition-test.
● Iftheconditionevaluatestotrue,thenasetofstatementsisexecuted,otherwiseanotherset
of statements is followed.
● This control is also called Decision Control because it helps in making decisions about
which set of statements is to be executed.
Decision control structure in C can be implemented by using:-
1. If statement
2. If-else statement
3. Nested if else statement
4. else-if ladder
1
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
. case control structure
5
6. conditional operator
Iteration Control ( Loops )
● Iterations or loops are used when we want to execute a statement or block of statements
several times.
● The repetition of loops is controlled with the help of a test condition.
● The statements in the loop keeponexecutingrepetitivelyuntilthetestconditionbecomes
false.
● There are the following three types of loops:-
1. While loop
2. Do-while loop
3. For loop
Decision control
onditional Control (Selection Control or Decision Control) : In conditional control, the
C
execution ofstatementsdependsuponthecondition-test.Iftheconditionevaluatestotrue,thenaset
of statements is executed,otherwiseanothersetofstatementsisfollowed.Thiscontrolisalsocalled
Decision Control because it helps in making decisions about which set of statements is to be
executed.
Decision control structure in C can be implemented by using:
1. Simple if statement
2. if-else statement
3. Nested if else statement
4. else-if ladder
5. case control structure
6. conditional operator
1. Simple if statement:
Thisisthemostsimpleformofdecisioncontrolstatement.Inthisform,asetofstatementsare
executed only if the condition given withifevaluatestotrue.Itsgeneralsyntaxandflowchartisas
under:
if(condition)
{
Statements ;
}
2
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
xample program to understand the if statement:
E
/* program to check whether the given number is negative*/
#include<stdio.h>
int main()
{
int num;
printf(“Enter the number:”);
scanf(“%d”,&num);
if(num<0)
{
printf(“The entered number is negative”);
}
}
Output:
Enter the number:-9
The entered number is negative
2. if- else statement:
This is a bi-directional control statement. This statement is used to testaconditionandtake
one of the two possible actions. If the condition evaluates to true then one statement (or block of
statements) is executed otherwise another statement (or block of statements) is executed.
The general form and flowchart of if-else statement is as under:
if(condition)
{
block of statements;
}
else
{
block of statements;
}
3
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
xample program to illustrate if-else statement:
E
/*Program to find the biggest of two numbers*/
#include<stdio.h>
int main()
{
int num1,num2 ;
printf("Enter two numbers:");
scanf("%d %d",&num1,&num2);
if(num1>num2)
{
printf("The number %d is big.",num1);
}
else
{
printf("The number %d is big.",num2);
}
}
utput:
O
Enter two numbers:
43
54
The number 54 is big.
3. Nested if-else statement:
If we have if-else statements within either the body of an if statement or the body of else
statement or in the body of bothifandelse, thenthis is known as nesting of if else statement.
The general syntax of nested if-else statement is as follows:
if(condition1)
{
if(condition2)
{
statements;
}
4
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
e lse
{
statements;
}
}
else
{
if(condition3)
{
statements;
}
else
{
statements;
}
}
Example program to explain nesting of if else:
/*program to find the largest of three numbers*/
#include<stdio.h>
int main()
{
int a, b,c,large;
printf(“Enter three numbers:”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
large=a;
else
large=c;
}
else
{
if(b>c)
large=b;
else
large=c;
}
printf(“Largest number is %d”,large);
}
utput:
O
Enter three numbers:
22
55
4
Largest number is 55
5
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
4.Else if ladder:
Thisisatypeofnestinginwhichthereisanif-elsestatementineveryelsepartexceptthelast
else part. This type of nesting is called else if ladder.
The general syntax and flowchart of else if ladder is as follows:-
if(condition1)
statementA;
else if(condition2)
statementB;
else if(condition3)
statementC;
else
statementD;
xample program for else if ladder::
E
/*program to find the grade of the student*/
#include<stdio.h>
int main()
{
int marks;
printf(“Enter the percentage of the student:”);
scanf(“%d”,&marks);
if(marks>=80)
printf(“A grade”);
else if(marks>=70)
printf(“B grade”);
else if(marks>=60)
printf(“C grade”);
6
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
else if(marks>=50)
printf(“D grade”);
else
printf(“FAIL”);
}
utput:
O
Enter the percentage of the student:89
A grade
5.Switch case statement:
witchcasestatementsareasubstituteforlongifstatementsandhavemoreflexibilityanda
S
clearer format than else-if ladder.
This statement is used to select one out of the several numbers of alternatives present in a
block.Thisselectionstatementsuccessivelyteststhevalueofanexpressionagainstalistofintegeror
character constants. When a match is found, the statements associated with that constant are executed.
The general syntax of switch case statement is as follows:
switch(expression)
{
case constant1: statements;
case constant2: statements;
case constant3: statements;
………………………
………………………
case constantN: statements;
default : statement;
}
Hereswitch,caseanddefaultare keywords.
● The expression following the switch keyword must give an integer value. This
expression can be any integer or character variable, or a function call thatreturnsan
integer.
● It can also be an arithmetic, relational, logical or bitwise expression yielding an integer.
● It can be integer or character constant also.
● Data types long int and short int are also allowed.
The constant following the case keyword should be of integer or character type. We cannot use
floating point or string constant.
Example program for switch case statement
/*program to print day of the week*/
#include<stdio.h>
int main()
{
int day;
printf("Enter the day number from 1 to 7 : ");
scanf("%d",&day);
switch(day)
{
case 1: printf("monday");
7
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
reak;
b
case 2:printf("tuesday");
break;
case 3: printf("wednesday");
break;
case 4:printf("thursday");
break;
case 5: printf("friday");
break;
case 6:printf("saturday");
break;
case 7: printf("sunday");
break;
default:printf("wrong input");
}
}
utput:
O
Enter the day number from 1 to 7 : 6
saturday
OTE:Inswitchcasestatements,ifwedonotassociateabreakstatementwitheverycasethenfrom
N
thecaseforwhichtheexpressionmatcheswiththeconstant,allthestatementsareexecuteduntilthe
switch case block ends. This situation is referred to as Fall Through.
6. Conditional operator:
It is alsocalledasternaryoperatorandisusedtoperformsimpleconditionaloperations.Itis
used to do operations similar to if-else statement.
The general syntax of conditional operator is as under:
Test expression? expression1:expression2;
Here firstly the test expression is evaluated.
If the test expression evaluates totruethentheexpression1isevaluatedanditbecomesthevalueof
the whole expression.
Ifthetestexpressionevaluatestofalsethentheexpression2isevaluatedanditbecomesthevalueof
the whole expression.
For eg., a>b ? a : b
Herefirstlytheexpressiona>bisevaluated.Ifitevaluatestotruethenthevalueofabecomes
the value of the whole expression otherwisevalueof bbecomes the value of the whole expression.
Iterations/Loops
Iterationsorloopsareusedwhenwewanttoexecuteastatementorblockofstatementsseveral
times.
The repetition of loops is controlled with the help of a test condition. The statementsinthe
loop keep on executing repetitively until the test condition becomes false.
There are the following three types of loops:-
8
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
. While loop
1
2. Do-while loop
3. For loop
ll these loops are explained as under:
A
while loop :
I tisthefundamentalloopingstatementinC.Itissuitedforproblemswhereitisnotknownin
advance how many times a statement or block of statements will be executed.
The generalsyntaxof while loop is as under:
Initialization;
while(condition)
{
Statement(s)
Increment / Decrement;
}
We can able to understand theworking of while loopwith the help of flow chart below:
. F
1 irstly theconditiongiven withwhileis evaluated.
2. If the condition evaluates to true then the statements given in the body of the loop are
executed.
3. Aftertheexecutionofallthestatementstheconditionisagaincheckedandifitagainevaluates
to true then the statements given in the body of the loop are again executed.
4. Inthiswaythestatementsareexecutedagainandagainuntiltheconditiongivenevaluatesto
false.
or terminating the loop, a termination condition is givenintheloopbodywhichmakesthe
F
conditionfalseatsomepointoftimeandasaresultofwhichtheloopterminates.Ifwedonotgivethe
termination condition then the loop goes onrepeatingagainandagaininfinitetimes.Suchloopsare
referred to asinfinite loops.
1 . Example program for while loop
/*Program to print numbers 1 to 5 */
#include<stdio.h>
int main()
9
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
{
int i;
i=1;
while(i<=5)
{
printf("\n%d",i);
i++;
}
}
Output:
1
2
3
4
5
2 . Example program for while loop
/*program to find the sum of digits of the given number.*/
#include<stdio.h>
int main()
{
int n,num,rem,sum=0;
printf(“Enter the number : ”);
scanf(“%d”,&num);
n=num;
while(num>0)
{
rem=num%10;
sum =sum+rem;
num=num/10;
}
printf(“The sum of the digits of %d is = %d”,n,sum);
}
Output:
Enter the number : 455
The sum of the digits of 455 is = 14
do-while loop :
➢
The do-while statement is also used for looping.
➢ Itissimilartowhileloopandisusedforproblemswhereitisnotknowninadvancehowmany
times the statement or block of statements will be executed.
➢ However,unlikewhileloop,incaseofdo-while,firstlythestatementsinsidetheloopbodyare
executed and then the condition is evaluated.
➢ As a result of which this loop is executed at least once even if the condition is initially false.
➢ After that the loop is repeated until the condition evaluates to false.
➢ Sinceinthislooptheconditionistestedaftertheexecutionoftheloop,itisalsoknownasthe
post test loop.
10
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
he general syntax of do-while loop is as follows:
T
Initialization;
do
{
Statement(s)
Increment / Decrement;
}while(condition);
The flow chart ofdo-whileis given as under:
1 . Example program fordo-whileloop
/*Program to print numbers 4 to 1 */
#include<stdio.h>
int main()
{
int i;
i=4;
do
{
printf("\n%d",i);
i--;
}while(i>=1);
}
Output:
4
3
2
1
2 . Example program fordo-whileloop
/*program to find the sum of digits of the given number.*/
#include<stdio.h>
int main()
{
11
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
int n,num,rem,sum=0;
printf(“Enter the number : ”);
scanf(“%d”,&num);
n=num;
do
{
rem=num%10;
sum =sum+rem;
num=num/10;
}while(num>0) ;
printf(“The sum of the digits of %d is = %d”,n,sum);
}
Output:
Enter the number : 567
The sum of the digits of 567 is = 18
Difference between while and do-while loop
for loop :
he general syntax of for loop consists of three expressions separated by semicolons. It is
T
given as follows:-
12
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
f or(initialization;termination condition;increment / decrement)
{
Statement(s);
}
1. I nitialization is executed only once when the loop starts and is used to initialize the loop
variables.
2. Termination conditionis a condition and is testedbefore each iteration of the loop.
3. Increment / decrement is an update expression used to update the loop variable and is
executed each time after the body of the loop is executed.
he flow chart of for loop is given as follows:
T
1 . Example program forforloop
// Program to print numbers 1 to 5
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
printf("\n%d",i);
}
}
utput:
O
1
2
3
4
5
13
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
2 . Example program forforloop
/* program to generate the Fibonacci series */
/* The Fibonacci sequence is a sequence where the nexttermisthesumoftheprevioustwoterms.
The first two terms of the Fibonacci sequence are 0 followed by 1.*/
#include<stdio.h>
int main()
{
int x,y,z;
int i,n;
x=0;
y=1;
printf("Enter the number of terms : ");
scanf("%d",&n);
printf("\n%d",x);
printf("\n%d",y);
for(i=1;i<n;i++)
{
z=x+y;
printf("\n%d",z);
x=y;
y=z;
}
}
Output:
Enter the number of terms : 5
0
1
1
2
3
5
● A llthethreeexpressionsintheforloopareoptionalandthereforewecanomitanyorallthe
three expressions but in any case the two separating semi colons should always be present.
● Ifweomitthetestexpressionthenitisalwaysassumedtobetrueandthereforetheloopnever
terminates and becomes an infinite loop.
● Ifwewanttomakesuchloopsafiniteloopthenaseparateterminateconditionisgivenwithin
the loop body
Jump statements (or) Unconditional control transfer statements
J ump statements are used to transfer the control from one part of the program to another part.
The various jump statements in C are as under:
1. break statement
2. continue statement
3. goto statement
1. break statement:
14
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
hebreakstatement is used inside the loops or switch statement. This statement causes
T
an immediate exit from the loop or the switch case block in which it appears.
It can be written as
break;
xample program forbreak
E
/*Program to understand the use of break statement*/
#include<stdio.h>
int main()
{
int n;
for(n=1;n<=5;n++)
{
if(n==3)
{
printf(“Loop is terminated using break statement \n”);
break;
}
printf(“Number = %d \n”,n);
}
printf(“Out of for loop \n”);
}
Output:
Number = 1
Number = 2
Loop is terminated using break statement
Outside of for loop
15
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
2. continue statement :
hecontinuestatementisusedinsidethebodyoftheloopstatement.Itisusedwhenwewant
T
to go to the next iteration of the loop after skipping some of the statements of the loop.
The continue statement is written as under:
continue;
I t is generally used with a condition.
●
● When a continue statement is encountered all the remaining statements (statements after
continue) in the current iteration are not executed and the loop continues with the next
iteration.
● The difference between break and continue isthatwhenabreakstatementisencountered
theloopterminatesandthecontrolistransferredtothenextstatementfollowingtheloopi.e.,
outside of for loop, but when a continuestatementisencounteredtheloopisnotterminated
and the control is transferred to the beginning of the loop.
● In while and do-while loops, after continue statement the control is transferred to the test
conditionandthentheloopcontinues,whereasinforloopaftercontinuestatementthecontrol
is transferred to update expression and then the condition is tested.
Example program forcontinue
/*Program to understand the use of break statement*/
#include<stdio.h>
int main()
{
int n;
for(n=1;n<=5;n++)
{
if(n==3)
{
printf(“Loop is continued with next iteration using continue statement \n”);
continue;
}
printf(“Number = %d \n”,n);
}
16
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
printf(“Out of for loop \n”);
}
Output:
Number = 1
Number = 2
Loop is continued with next iteration using continue statement
Number = 4
Number = 5
Outside of for loop
3. goto statement:
he C goto statement is a jump statement which is sometimes also referred to as an
T
unconditionaljumpstatement.Thegotostatementcanbeusedtojumpfromanywheretoanywhere
within a function.
Syntax 1:
oto label;
g
...................
...................
label:
....................
....................
yntax 2:
S
label:
...................
...................
goto label;
....................
....................
➔
Here label is any valid C identifier and is followed by colon.
➔ The goto statement transfers the control to the statement after the label.
➔ If the label is placed after the goto statementthenthecontrolistransferredforwardanditis
known as forward jump. If the label is placed before the goto statement then the control is
transferred backward and the jump is called backward jump.
➔ In the forward jump all the statements between the goto statement and the label are skipped.
➔ In case of backward jump all the statement between the goto statement and the label are
executed.
➔ There should always be a statement after any label.
Example program forgoto
#include<stdio.h>
int main()
{
int a;
printf("\nEnter a value : ");
17
ITP Notes for I B.Tech CSM - A, SVCET, Chittoor
s canf("%d",&a);
printf("Hello");
if(a == 0){
goto label;
}
printf("World");
label:printf("Exit");
}
Output 1:
Enter a value : 9
HelloWorldExit
Output 2:
Enter a value : 0
HelloExit
18