Chater-3: Selection and Looping Statements
Give the brief explanation for below topics
Aims and Objectives
####################################
Introduction
####################################
SELECTION –MAKING DECESION:-
SELECTION CONTROL STATEMENTS:- Based on the decision it will executes the statements, these
are two types:-
1. Two way selection (example :if)
2. Multi way selection (example :else if ladder, switch)
1).TWO-WAY SELECTION:- Selection allows us to choose b/w two (or) more alternatives. It
allows us to make decisions. The basic decision statement in the computer is two-way selection.
The decision is described to the computer as a conditional stmt that can be either true /
false. If the condition is false, then a different action or set of actions is executed. Regardless of
which set of actions is executed, program centimes with the next stmt.
IF STATEMENT:-Generally , the control in a program will be in sequential order. i.e., it execute the
statements in top-down approach.
‘if’ is used control the sequence of statements based on a given condition. ‘if’ can be
used in the following forms.
(i) Simple if:- This ‘if’ statements contains true part. i.e; Whenever the condition is true, then
only the statement(or) statements will get executed.
Syntax: if (condition)
{
Stmt block;
}
Stmt-X;
Explanation
###########################
FlowChart
Conditio Tru
n e
fals Statement block
Statement -X e
Department of BS&H Page 1
NRI Institute of Technology, Pothavarappadu
next statement
Department of BS&H Page 2
NRI Institute of Technology, Pothavarappadu
Ex:- 1. if(a>b)
printf(“a is big”);
2. if (x==10)
{
x=x+10;
printf(“%d,”, x)
}
Examples:
Write a program to check whether the entered number is less than 10 if yes display the same?
#include<stdio.h>
#include<conio.h>
void main()
{
int v;
clrscr();
printf(“enter the number”);
scanf(“%d”,&v);
if(v<10)
printf(“\n number entered is less than 10”);
getch();
}
Output:
Enter the number 9
Number entered is less than 10
Write a program to check equivalence of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int m,n;
clrscr();
printf(“enter two numbers”); scanf(“%d
%d”,&m,&n)
if(m-n==0)
printf(“\n two numbers are equal”); getch();
}
Output:
enter two numbers 5 5 two
numbers are equal
Department of BS&H Page 3
NRI Institute of Technology, Pothavarappadu
Write a program to check whether the candidate age is greater than 17 or not .if yes display the message
“eligible for voting”
void main()
{
int age;
clrscr();
printf(“\n enter age”);
scanf(“%d”,age);
if(age>17)
prinft(“eligible for voting”);
getch();
}
Output:
enter age 18 eligible
for voting
Write a program to find whether the given number is positive or negative
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“enter a number\n”); scanf(“%d”,&n);
if(n>0)
printf(“the number is positive \n”); getch();
}
Output:
enter a number 10 the
number is positive enter
a number -8
Write a program for comparision of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2; clrscr();
printf(“enter two numbers”);
scanf(“%d%d”,&n1,&n2);
if(n1>n2)
printf(“%d is greater than %d”,n1,n2);
if(n1<n2)
printf(“%d is less than %d”,n1,n2);
Department of BS&H Page 4
NRI Institute of Technology, Pothavarappadu
if(n1==n2)
printf(“%d is equal to %d”,n1,n2);
getch();
}
Output:
Enter two numbers 10 12
10 is less than 12
Enter two numbers 15 11
15 is greater than 11
IF – ELSE STATEMENT:- C implements two-way selection with the if-else statement. An if –else
statement is a composite statement used to make a decision b/w two alternatives.
if –else structure contains two parts. One is true part & other is the false part but only of these
two parts is executed based on the condition tested.
SYNTAX:-
if (test condition)
{
Stmt block- 1; /* true block*/
}
else
{
Stmt bock- 2; /* false block*/
}
Stmt-X;
Flowchart:
false true
Condition
Statement block2 Statement block1
Statement-x
Next statement
Ex:-
if (a>b)
printf(“a is big”);
else
Department of BS&H Page 5
NRI Institute of Technology, Pothavarappadu
printf (“b is big”);
In the above syntax, stmt block 1 will be executed if the condition becomes true. Otherwise
stmt block 2 will be executed. Stmt .X will be executed in both cases.
NOTE:- While writing if –else stmt
(i) The expression must be enclosed in paranthesis.
(ii) No semicolon (;) is needed for an if –else stmt:
(iii)The expression can have side effects.
(iv) Both the true & false stmt can be any stmt (even another if-else stmt) or they can be a null
stmt.
Examples:
Read the values of a,b,c through the keyboard. Add them and after addition check if it is range
of 100 and 200 or not. Print the sepearte message for each. #include<stdio.h>
#include<conio.h> void
main()
{
int a,b,c,d;
clrscr();
printf(“enter three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
d=a+b+c;
if(d<=200 && d>=100)
printf(“sum is in between 100 and 200”); else
printf(“out of range”); getch();
}
Output:
Enter three numbers 50 52 54 Sum
is in between 100 and 200
Write a program to find the roots of a quadratic equation by using if else condition
#include<stdio.h>
#include<conio.h>
void main()
{
int b,a,c;
float x1,x2;
clrscr();
printf(“enter values for a,b,c”);
scanf(“%d %d%d”,&a,&b,&c);
if(b*b>4*a*c)
{
x1=-b+sqrt(b*b-4*a*c)/2*a;
x2=-b-sqrt(b*b-4*a*c)/2*a;
printf(“\n x1=%f x2=%f”,x1,x2);
}
else
printf(“roots are imaginary”);
getch();
}
Department of BS&H Page 6
NRI Institute of Technology, Pothavarappadu
Output:
Enter values for a b c 5 1 5
Roots are imaginary
Write a program to find whether the given number is even or odd
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“enter a number to check);
scanf(“%d”,&n);
if(n%2==0)
printf(“%d is an even number “,n);
else
printf(‘%d is an odd number”,n);
getch();
}
Output:
Enter a number to check 7 7
is an odd number
Enter a number to check 4 4
is an even number
Write a program to find the biggest among two numbers
#include<stdio.h>
#include<conio.h>
Void main()
{
int x,y,big;
Clrscr();
Printf(“enter two numbers”);
scanf(“%d%d”,&x,&y);
if(x>y)
big=x;
else
big=y;
printf(“biggest number %d”,big); getch();
}
Output:
Enter two numbers 5 6
Biggest number 6
Write a program to check whether a given character is vowel or not.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf(“enter any character”);
scanf(%c”,&ch);
Department of BS&H Page 7
NRI Institute of Technology, Pothavarappadu
if(ch==’a’||ch==’e’||ch==’I’||ch==’o’||ch==’u’||ch==’A’||ch==’E’||ch==’I’||ch==’O ’||ch==’U’)
printf(“ you entered vowel”); else
printf(“you didn’t entered vowel”); getch();
}
Output:
Enter any character e
You entered vowel
NESTED IF-ELSE:- Whenever a series of decisions are to be made, more than one if-else students are
to be used within one another known as nested if-else.
SYNTAX:-
if (test condition 1)
{
if (text condition 2)
stmt block-1;
else
Stmt block 2;
}}
else
Stmt block3;
Stmt-x;
Department of BS&H Page 8
NRI Institute of Technology, Pothavarappadu
Flowchart:
false true
Conditio
n1
F T
Condition2
Statement 3
Statement 2 Statement 1
Statement x
Next statement
Ex:
if(a>b)
{
if(a>c)
printf(“a is big”);
else
printf(“c is big”);
}
else if (b>c)
{
printf(“b is big”);
}
else
printf(“c is big”);
Write a program to find the maximum of three numbers
#include<stdio.h>
#include<conio.h>
void main()
{
Iint x,y,z,max; clrscr();
printf(“enter three numbers”); scanf(“%d%d
%d”,&x,&y,&z);
Department of BS&H Page 9
NRI Institute of Technology, Pothavarappadu
if(x>y)
{
if(x>z)
max=x;
else
max=z;
}
else
{
if(y>z)
max=y;
else
max=z;
}
printf(“maximum =%d “,max);
getch();
}
Output:
Enter three numbers 1 2 3 Maximum=3
Write a program for comparison of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
printf(“enter two numbers”);
scanf(“%d%d”,&x,&y);
if(x>=y)
if(x>y)
printf(“%d is greater than %d”,x,y); printf(“%d is
else
equal to %d”,x,y);
else
printf(“%d is less than %d”,x,y);
}
Output:
Enter two numbers 10 20
10 is less than 20
Enter two numbers 50 40
50 is greater than 40
Department of BS&H Page 10
NRI Institute of Technology, Pothavarappadu
Multi way selection:
In addition to 2-way selection most programming languages provide another selection concept
known as Multiway Selection. Multiway Selection chooses among several altermatives.
ELSE-IF LADDER:- Whenever a condition has to be tested based on the falsity of the above
condition, else-if ladder can be used.
SYNTAX:-
if (test condition1)
{
Stmt block -1;
}
else if (test condition2)
{
Stmt block-2;
}
else if (test condition 3)
{
Stmt block-3;
}
else
{
Default stmt;
}
Stmt – X;
Here test condition 1 ,test condition 2,test condition 3-------------test condition n are
mutually exclusive. That is ,only one test condition of all will be true. There are n+1
blocks of statements.
Initially test condition1 is checked if it is true block of statements would get executed,all the
other block of statements would be skipped. If test condition 1 is false ,test condition 2 is
checked if it is true the block of statements would get executed all other statements would be
skipped. If none of the expressions is found to be true the last block of statements would get
executed.
Department of BS&H Page 50
NRI Institute of Technology, Pothavarappadu
Flowchart:
T F
Conditi
on1
Statement 1 T F
Condition 2
TF
Statement2
Conditio
n3
Statement3 Default statement
Statement x
Next statement
Ex:-
If (a>b&&a>c&&a>b)
Printf(“a is big”);
Else if (b>c&&b>d)
Printf(“b is big”);
Else if (c>d)
Printf (“c is big”); Else
Printf(“d is big”);
Write a program to find the maximum of three numbers using else-if ladder
#include<stdio.h> #include<conio.h>
Department of BS&H Page 51
NRI Institute of Technology, Pothavarappadu
void main()
{
int x,y,z,max;
clrscr();
printf(“enter three numbers”); scanf(“%d%d
%d”,&x,&y,&z);
if((x>y)&&(x>z))
max=x;
else if((y>x)&&(y>z))
max=y;
else
max=z;
printf(“maximum =%d \n”,max); getch();
}
Output:
Enter three numbers 1
23
Maximum=3
Write a program to calculate area of square/rectangle/circle/triangle depending upon user choice.
#include<stdio.h>
#include<conio.h>
void main()
{
int choice;
float area,a,b,c,s; printf(“main
menu \n”); printf(“1. area of
square\n”);
printf(“2.area of rectangle\n”);
printf(“3.area of circle\n”);
printf(“4.area of triangle\n”);
printf(“enter your choice\n”);
scanf(“%d”,&choice);
if(choice==1)
{
printf(“enter the side of square”);
scanf(“%f”,&a);
area=a*a;
printf(“area of square is %f”,area);
}
else if(choice==2)
{
printf(“enter the length and breadth of rectangle”); scanf(“%f
%f”,&a,&b);
Department of BS&H Page 52
NRI Institute of Technology, Pothavarappadu
area=a*b;
printf(“area of rectangle is %f”,area);
}
else if(choice==3)
{
printf(“enter the radius of circle”);
scanf(“%f”,&a);
area=3.14*a*a;
printf(“area of circle is %f”,area);
}
else if(choice==4)
{
printf(‘enter three sides of triangle”);
scanf(“%f%f%f”,&a,&b,&c); s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c)); printf(“area
of triangle is %f”,area);
}
else
printf(“wrong choice\n”);
getch();
}
Output:
main menu 1.area
of square
2.area of rectangle
3.area of circle 4.area
of triangle enter your
choice 2
enter the length and breadth of rectangle 4 6 area
of rectangle is 24
Write a program to sort six numbers and find the largest one by using else if ladder
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d,e,f; clrscr();
printf(“enter numbers”); scanf(“%d%d%d%d%d
%d’,&a,&b,&c,&d,&e,&f);
if((a>b)&&(a>c)&&(a>d)&&(a>e)&&(a>f))
printf(“highest of six numbers is %d”,a); else
if((b>c)&&(b>d)&&(b>e)&&(b>f)
printf(“highest of six numbers is %d”,b); else
if((c>d)&&(c>e)&&(c>f))
Department of BS&H Page 53
NRI Institute of Technology, Pothavarappadu
printf(“highest of six numbers is %d’,c); else
if((d>e)&&(d>f))
printf(“highest of six numbers is %d”,d); else
if(e>f)
printf(‘highest of six numbers is %d”,e);
else
printf(“highest of six numbers is %d”,f);
getch();
}
Output:
enter numbers 12 13 14 15 16 17
highest of six numbers is 17
Write a program that reads marks in three subjects ,calculate average marks and assigns grade as
per following specifications
If marks Then grade
>=90 A
75-90 B
60-75 C
50-60 D
<50 Fail
#include<stdio.h>
#include<conio.h>
void main()
{
float m1,m2,m3,average;
clrscr();
printf(“enter the marks in three subjects”);
scanf(“%f%f%f’,&m1,&m2,&m3);
average=(m1+m2+m3)/3;
printf(“average marks are %f”,average);
if(average>=90)
printf(“grade is A”);
else if(average>75 &&average<90)
printf(“grade is B”);
else if(average>=60 &&average<75)
printf(“grade is C”);
else if(average>=50 &&average<60)
printf(“grade is D”);
else
printf(“fail”);
getch();
}
Output:
Enter the marks in three subjects 90 70 82
Department of BS&H Page 54
NRI Institute of Technology, Pothavarappadu
Average marks are 80.6666
Grade is B
Switch statement:
The switch statement is a multi way branch statement. In the program if there is a possibility to
make a choice from a number of options, this structured selection is useful. The switch statement
requires only one argument of any data type,which is checked with the number of case
options .The switch statement evaluates expression and then looks for its value among the case
constants. If the value matches with case constant, this particular case statement is executed. If
not default is executed. Here switch,case,default are reserved keywords. Every case statements
terminates with ‘:’. The break statement is used to exit from current case structure. The switch
statement is useful for writing the menu driven program.
The syntax of the switch case statement is as follows:
switch(variable or expression)
{
case constant a: statement;
break;
aase constant b:statement; break;
default: statement;
}
The switch expression: in the block ,the variable can be a character or an integer. The integer
expression following the keyword switch will yield an integer value only. The integer may be any
value 1,2,3 and so on. In case a character constant ,the values may be given in the alphabetic order
such ‘x’,’y’,’z’.
Switch organization: The switch expression should not be terminated with a semicolon and or
with any other symbol. The entire case structure following switch() should be enclosed with curly
braces. The keyword case is followed by a constant. Every constant terminates with a colon. Each
case statement must contain different constant values. Any number of case statements can be
provided. If the case structure contains multiple statements, they need not be enclosed with curly
braces. Here the keywords case and break perform the job of opening and closing curly braces
respectively
Switch execution: When one of the cases satisfies, the statements following it are executed. In
case there is no match the default case is executed. The default can be put anywhere in switch()
expression. The switch() statement can also be written without the default statement. The break
statement used in switch causes the control to go outside the switch block. By mistake if no
break statements are given all the cases following it are executed.
Department of BS&H Page 55
NRI Institute of Technology, Pothavarappadu
Switch(exp
rable)
Case Statement 1 break
constant 0
Case
constant 1 Statement 1 break
default
Statement 1
break
End of switch
Write a program to provide multiple functions such as 1.addition 2.subtraction 3.multiplication
4.division 5.remainder using switch statement. #include<stdio.h>
#include<conio.h> void
main()
{
int a,b,c,ch;
clrscr(); printf(“menu”);
printf(“1.addition”);
printf(“2.subtraction”);
Department of BS&H Page 56
NRI Institute of Technology, Pothavarappadu
printf(“3.multiplication”);
printf(“4.division”);
printf(“5.remainder”);
printf(“6.exit”); printf(“enter
your choice”);
scanf(“%d”,&ch);
if(ch<6&&ch>=1)
{
printf(“enter two numbers”); scanf(“%d
%d”,&a,&b);
}
switch(ch)
{
case 1: c=a+b;
printf(“addition %d’,c);
break;
case 2:c=a-b;
printf(“subtraction %d”,c);
break;
case 3: c=a*b;
printf(“multiplication %d”,c); break;
case 4:c=a/b;
printf(“division %d”,c);
break;
case 5:c=a%b;
printf(“remainder %d’,c); break;
case 6:exit();
break;
default:printf(“invalid choice”);
}
}
Write a program to read a day number and print corresponding day of the week
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf(“enter any number in between 1 to 7”);
scanf(“%d”,&num);
switch(num)
{
case 1:printf(“it is Sunday”);
Department of BS&H Page 57
NRI Institute of Technology, Pothavarappadu
break;
case 2:printf(“it is Monday”);
break;
case 3: printf(“it is Tuesday”);
break;
case 4: printf( “it is wedensday”); break;
case 5: printf(“ it is Thursday”);
break;
case 6: printf(“it is Friday”); break;
case 7:printf(“it is Saturday”);
break;
default: print(“wrong number “);
}
getch();
}
output:
enter any number in between 1 to 7 3 It
is Tuesday.
Switch statement with out break statement
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
printf(“enter any value”);
scanf(“%d”,&x); switch(x)
{
case 1: printf(“tenali”); case
2:printf(“vizag”);
case 3:printf(“Hyderabad”); break;
}
getch()
}
Output:
enter any value 1
tenali
vizag Hyderabad
Nested switch case:
Department of BS&H Page 58
NRI Institute of Technology, Pothavarappadu
The c supports nested switch statements. The inner switch can be a part of an outer switch. The
inner and outer switch case constants may be the same. No conflicts arise even if they are the
same. A few examples are given below on the basis of nested switch statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
printf(“enter a number”);
scanf(“%d”,x);
switch(x)
{
case 0: printf(“the number is even”);
break;
case 1: printf(“the number is odd”);
break;
default:
y=x%2;
switch(y)
{
case 0: printf(“number is even”); break;
default: printf(“number is odd”);
}
}
getch();
}
Output:
Enter a number 5
Number is odd
Explanation: in the above given program the first switch statement is used for displaying the
message such as even or odd numbers when the entered numbers are 0 and 1 respectively .When
the entered number is other than 0 and 1 its remainder is calculated with modulus operator and
stored in the variable ‘y’ is used in the inner switch statement. If the remainder is 0 the message
displayed will be number is even otherwise for non zero it will be number is odd.
Example programs:
1. Calculates the area of circle or rectangle.
#define PI 3.14
#include<stdio.h>
#include<conio.h> void
main()
Department of BS&H Page 59
NRI Institute of Technology, Pothavarappadu
{
float n1,n2;
char ch;
clrscr();
printf(“press C or R for the area of circle or rectangle respectively”); scanf(“%c’,&ch);
if(ch==’C’||ch==’c’)
{
printf(“enter radius”); scanf(“%f”,&n1);
printf(“area of circle is %f’,PI*n1*n2);
}
if(ch==’R’||ch==’r’)
{
printf(“enter length and width”);
scanf(“%f%f”,n1,n2);
printf(“area of rectangle is %f”,n1*n2);
}
}
Output:
press C or R for the area of circle or rectangle respectively C Enter
radius 5
Area of circle 78.539750
2. Program that accepts sales amount and then calculates discount as 10% of sales amount if sales
amount is more than 5000 otherwise as 5% of sales amount. #include<stdio.h>
#include<conio.h> void
main()
{
float sales,discount;
printf(“enter the sales”);
scanf(“%f’,&sales);
if(sales>5000)
discount=.10*sales;
else
discount=.05*sales;
printf(“discount is %f”,discount); getch();
}
Output:
Enter the sales 8000
Discount is 800
3. Program to display profit or loss after obtaining cost and selling prices.
#include<stdio.h>
Department of BS&H Page 60
NRI Institute of Technology, Pothavarappadu
#include<conio.h> void
main()
{
float sp,cp,lp;
printf(“enter the cost price”); scanf(“%f”,&cp);
printf(“enter the selling price”);
scanf(“%f’,&sp);
lp=sp-cp;
if(lp==0)
printf(“no loss and profit”); else
if(lp>0)
printf(“profit has occurred amd amount of profit is %f”,lp);
else
printf(“loss has occurred and amount of loss is %f”,abs(lp));
getch();
}
Output:
enter the cost price 90 enter
the selling price 100
profit has occurred and amount of profit is 10 4.Program for
temperature conversion as per user choice #include<stdio.h>
#include<conio.h> void
main()
{
int choice;
float tempf,tempc;
clrscr();
printf(“temperature conversion menu\n”);
printf(“1. Faherenheit to Celsius \n”); printf(“2.
Celsius to faherenheit \n”); printf(“enter your
choce”); scanf(“%d’,&choice);
if(choice==1)
{
printf(“enter the temperature in Fahrenheit”);
scanf(“%f”,&tempf);
tempc=(tempf-32)/1.8;
printf(“temperature in Celsius is %f”,tempc);
}
else if(choice==2)
{
printf(“enter the temperature in Celsius”);
scanf(“%f”,&tempc);
Department of BS&H Page 61
NRI Institute of Technology, Pothavarappadu
tempf=(tempc*1.8)+32;
printf(“temperature in Fahrenheit %f”,tempf);
}
else
printf(“wrong choce”);
getch();
}
Output:
Temperature conversion menu
1.fahrenheit to Celsius 2.celsius
to Fahrenheit
Enter your choice 2
Enter the temperature in Celsius 37
Temperature in Fahrenheit 98.59999
5. Program to check whether a given year is leap year or not
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf(“enter a year”);
scanf(“%d’,&year);
if(year %100==0) if(year
%400==0)
printf(“it’s a centuary leap year”); else
printf(“it’s a centuary year but not a leap year”); else
if(year %4==0)
printf(“leap year”);
else
printf(“not leap year”);
getch();
}
Output:
enter a year 2005 not
leap year
6. Program to check whether a character is an uppercase or lowercase alphabet or a digit or a special
symbol
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
Department of BS&H Page 62
NRI Institute of Technology, Pothavarappadu
printf(“enter any character”);
scanf(“%c”,&ch);
if(ch>=’A’&&ch<=’Z’)
printf(“you entered an uppercase alphabet”); else
if(ch>=’a’&&ch<=’z’)
printf(“you entered a lowercase character”); else
if(ch>=’0’ &&ch<=’9’)
printf(“you entered a digit”);
else
printf(“you entered a special character”);
getch();
}
Output:
enter any character y
you entered a lowercase character
7. Write a program to calculate the square of those numbers only whose least significant digit
is 5
#include<stdio.h>
#include<conio.h>
void main()
{
int s,d;
clrscr();
printf(“enter a number”);
scanf(“%d”,%s); d=s%10;
if(d==5)
{
s=s/10; printf(“square=%d%d”,s*s+
+,d*d);
}
else
printf(“invalid number”);
}
Department of BS&H Page 63
NRI Institute of Technology, Pothavarappadu
Output:
enter a number 25
square=625
Danglng else Problem
########################################
nested if-else Statements
########################################
Additional Examples with explanation and flow chart
########################################
Department of BS&H Page 64
NRI Institute of Technology, Pothavarappadu
ITERATIVE LOOPS
Loops are used to repeat a block of code. Being able to have your program repeatedly
execute a block of code is one of the most basic but useful tasks in programming.
There are three basic types of loops which are:
“while loop”
“do while loop”
“for loop”
While loop:
Explanation
###############################
#######
Syntax:
while (test expression)
{
Single statement;
or
Block of statements;
}
Description:
In the beginning of while loop, test expression is checked. If it is true, codes inside the
body of while loop,i.e, code/s inside parentheses are executed and again the test expression is
checked and process continues until the test expression becomes false. Flow chart:
Example:
/* C program to print first 10 natural numbers*/
#include<stdio.h>
#include<conio.h> Void
main()
{
int a=0;
clrscr();
while(a<10)
{
Printf(“%d\t”,a);
Department of BS&H Page 65
NRI Institute of Technology, Pothavarappadu
a++;
Department of BS&H Page 66
NRI Institute of Technology, Pothavarappadu
}
}
Output:
1 2 3 4 5 6 7 8 9 10
Example:
/* C Program to find factorial of a number using while loop*/
#include<stdio.h>
#include<conio.h> void
main()
{
int n,f=1;
printf("Enter the number:\n");
scanf("%d",&n);
while(n>0)
{
printf("%d",n);
f=f*n;
n--;
}
printf("The factorial of the integer is:%d",f); getch();
}
Output:
Enter the number:
5
The factorial of the integer is:
120
do...while loop:
In C, do...while loop is very similar to while loop. Only difference between these two loops is that,
in while loops, test expression is checked at first but, in do...while loop code is executed at first then
the condition is checked. So, the code are executed at least once in do...while loops.
Expand the explanation
####################
Syntax:
do
{
Single statement;
or
Block of statements;
}
while (test expression);
Department of BS&H Page 67
NRI Institute of Technology, Pothavarappadu
Expand The explanation
############
Department of BS&H Page 68
NRI Institute of Technology, Pothavarappadu
Description:
At first codes inside body of do is executed. Then, the test expression is checked. If it is
true, code/s inside body of do are executed again and the process continues until test expression
becomes false(zero).
Notice, there is semicolon in the end of while (); in do...while loop.
Flow chart:
Example
/* C program to print first 10 natural numbers*/
#include<stdio.h>
#include<conio.h> Void
main()
{
int a=0;
clrscr();
do
{
Printf(“%d\t”,a);
a++;
} while(a<10);
}
Output:
1 2 3 4 5 6 7 8 9 10
Example 2 :
/* C Program to find factorial of a number using while loop*/
#include<stdio.h>
#include<conio.h> void
main()
{
int n,f=1;
printf("Enter the number:\n");
scanf("%d",&n);
do
Department of BS&H Page 69
NRI Institute of Technology, Pothavarappadu
{
printf("%d",n);
f=f*n;
n--;
} while(n>0);
printf("The factorial of the integer is:%d",f); getch();
}
Output:
Enter the number:
5
The factorial of the integer is:
120
For loop
Syntax:
for(initial expression; test expression; update expression)
{
Single statement;
or
Block of statements;
}
Description:
The initial expression is initialized only once at the beginning of the for loop. Then, the test
expression is checked by the program. If the test expression is false, for loop is terminated. But, if
test expression is true then, the codes are executed and update expression is updated. Again, the test
expression is checked. If it is false, loop is terminated and if it is true, the same process repeats
until test expression is false.
This flowchart describes the working of for loop in C programming.
Flow chart:
Department of BS&H Page 70
NRI Institute of Technology, Pothavarappadu
/* C Program to find factorial of a number using for loop*/
#include<stdio.h>
#include<conio.h> void
main()
{
int n,i,f=1;
printf("Enter the number:\n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
f=f*i;
}
printf("The factorial of the integer is:%d",f); getch();
}
Output:
Enter the number:
5
The factorial of the integer is:
120
Example
/* C program to print first 10 natural numbers using for loop*/
#include<stdio.h>
#include<conio.h> Void
main()
{
int i;
clrscr();
for(i=0;i<=10;i++)
{
Printf(“%d\t”,a);
}
}
Output:
1 2 3 4 5 6 7 8 9 10
Example
/* C program to print even numbers between 1 and n*/
#include<stdio.h>
#include<conio.h> Void
main()
{
int i,n;
clrscr();
Department of BS&H Page 71
NRI Institute of Technology, Pothavarappadu
printf("Enter the number:\n");
scanf("%d",&n); for(i=1;i<=10;i+
+)
{
If(i%2==0)
Printf(“%d\t”,i);
}
}
Output:
2 4 6 8 10
Example
/* C program to print odd numbers between 1 and n*/
#include<stdio.h>
#include<conio.h> Void
main()
{
int i,n;
clrscr();
printf("Enter the number:\n");
scanf("%d",&n); for(i=1;i<=10;i+
+)
{
If(i%2==1)
Printf(“%d\t”,i);
}
}
Output:
1 3 5 7 9
break and continue Statement
There are two statement built in C, break; and continue; to interrupt the normal flow of
control of a program. Loops performs a set of operation repeatedly until certain condition becomes
false but, it is sometimes desirable to skip some statements inside loop and terminate the loop
immediately without checking the test expression. In such cases, break and continue statements are
used.
break Statement:
In C programming, break is used in terminating the loop immediately after it is
encountered. The break statement is used with conditional if statement Syntax:
break;
The break statement can be used in terminating all three loops for, while and do...while loops.
Department of CSE Page 70
NRI Institute of Technology, Pothavarappadu
The figure below explains the working of break statement in all three type of loops.
Examples:
/* C program to demonstrate the working of break statement by terminating a loop, if user inputs
negative number*/
# include <stdio.h>
#include<conio.h> void
main()
{
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break; //for loop breaks if num<0.0
} sum=sum+num;
average=sum/(i-1);
} printf("Average=%.2f",average);
Output:
Maximum no. of inputs 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07
Department of CSE Page 71
NRI Institute of Technology, Pothavarappadu
continue Statement:
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are
used.
Syntax:
continue;
The continue statement can be used in terminating all three loops for, while and do...while loops.
The figure below explains the working of continue statement in all three type of loops.
Example:
//program to demonstrate the working of continue statement in C programming
/*Write a C program to find the product of 4 integers entered by a user. If user enters 0 skip it.*/
# include <stdio.h> int
main()
{
int i,num,product; for(i=1,product=1;i<=4;+
+i)
{
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; / *In this program, when num equals to zero, it skips the
statement product*=num and continue the loop. */
product*=num;
}
printf("product=%d",product);
return 0;
}
Output
Enter num1: 3
Enter num2: 0
Enter num3: -5
Enter num4: 2
product= - 30
Department of CSE Page 72
NRI Institute of Technology, Pothavarappadu
Loop initialization and updating:
Loop Initialization:
• Programs typically require some type of preparation before executing loops.
• Loop initialization, which happens before a loop’s first iteration, is a way to prepare the
loop. It may be explicit or implicit.
• In explicit initialization, we write code to set the values of key variables used by the loop.
Implicit initialization relies on a “preexisting situation to control the loop.
Updating a Loop:
• A loop update is what happens inside a loop’s block that eventually causes the loop to
satisfy the condition, thus ending the loop.
• Updating happens during each loop iteration.
• Without a loop update, the loop would be an infinite loop.
Event and counter controlled loops:
Event-Controlled Loops
• In an event-controlled loop, an event is something that happens in the loop’s
execution block that changes the loop’s control expression from true to false.
• The program can update the loop explicitly or implicitly.
• We cannot predict the maximum number of iterations during the run of a program.
Department of CSE Page 73
NRI Institute of Technology, Pothavarappadu
Counter controlled loops:
• In a counter-controlled loop, we can control the number of loop iterations.
• In such a loop, we use a counter, which we must initialize, update and test.
• The number the loop assigns to the counter doesn’t need to be a constant value.
• To update, we can increment or decrement the counter.
APPLICATIONS OF LOOPS:
/*c program to find the sum of N natural numbers*/
#include<stdio.h>
#include<conio.h> void
main()
{
int i,n,sum=0;
Department of CSE Page 74
NRI Institute of Technology, Pothavarappadu
printf(“enter the
value of N”);
scanf(“%d”,&n)
; for(i=1;i<=n;i+
+)
{
sum=sum+i;
}
printf(“the sum
is%d”,sum);
getch();
}
OUTPUT
ent
er
the
val
ue
of
N
5
The sum is 15
/*c program to find
m power n*/
#include<stdio.h>
#include<conio.h>
void main()
{
int
I,n,m,product=1;
printf(“enter the
value of M”);
scanf(“%d”,&m
);
printf(“enter the
value of N”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
product =product*m;
}
Department of CSE Page 75
NRI Institute of Technology, Pothavarappadu
printf(“the result is
%d”,product);
getch();
}
OUTPUT
ent
er
the
val
ue
of
M
5
ent
er
the
val
ue
of
N
3
The result is 125
********
Use of Comma Operator in for Loop
##############################
Differences for while, do-while and for loop
#################################
Special Control Statement
#################################
goto Statement
#################################
return Statement
#################################
exit Statement
#################################
Difference between break and continue Statements
#################################
null Statement
Department of CSE Page 76
NRI Institute of Technology, Pothavarappadu
#################################
Additional Programs
##################
Summary
################
Review Questions
################
Multiple Choice Questions
#####################
(From placement cell) minimum50 -100 bits as per syllabus
Department of CSE Page 77
NRI Institute of Technology, Pothavarappadu