Module – II
Control and loop statements
Marimuthu R
Control and Loop statements
Used to make decision based on the conditions.
The statements which ‘control’ the flow of the
execution, are known as control statements.
There are 2 types of control statements
1.Decision making / Selection statements
2.Loop / Iterative statements
•Decision making / Selection
statements
The decision making statements are
1.if statement
2.if –else statement
3.Nested if statement
4.if –else ladder
5.switch statements
The if….else Statement :
Syntax :
if(expression)
{
true- block statements;
}
else
{
false – block statements;
}
true express false
ion
true false
block block
stateme statemen
nt t
Program
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int n = 50; int n = 50;
if (n== 44) if (n== 44)
printf("n is 44"); {
n++; printf("n is 44");
printf("%d", n); n++;
return 0; }
} printf("%d", n);
return 0;
}
Program
#include<stdio.h>
void main()
{ int y;
printf("Enter the year : ");
scanf("%d",&y);
if(y%4= =0)
printf("%d is a leap year \n“,y);
else
printf("%d is not a leap year \n“,y);
}
#include <stdio.h>
int main () {
int a = 100;
if( a < 20 ) {
printf("a is less than 20\n" );
}
else
{
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
4. The else – if ladder:
If there is an if else statement nested in each else of an
if-else construct, it is known as the else..if ladder.
Syntax:
if (condition 1)
statement – 1;
else if (condition 2)
statement – 2;
else if (condition 3)
statement – 3;
else
statement-4;
4. The else – if ladder:
The conditions are evaluated from the top to
downwards.
If none of the conditions are true, the final else will be
executed.
#include <stdio.h>
int main () {
int a = 100;
if( a == 10 ) {
printf("Value of a is 10\n" );
}
else if( a == 20 )
{
printf("Value of a is 20\n" );
}
else if( a == 30 )
{
printf("Value of a is 30\n" );
} else
{
printf("None of the values is matching\n" );
}
printf("Exact value of a is: %d\n", a );
return 0;
}
Nested if…else statements
The if clause and the else part may contain a
compound statement.
Either or both may contain another if or if….else
statement. This is called the nesting of if…else
statements.
Syntax: if(condition 1)
{ if(condition 2)
{
statement – 1;
}
else
{
statement – 2;
}
}
else
{
statement – 3;
}
E.g.
if(a>b)
{ if(a>c)
printf(“a is largest”);
else
printf(“c is largest”);
}
else
{
if(b>c)
printf(“b is largest”);
else
printf(“c is largest”);
}
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
if (i > 7)
printf("i is greater than 7 \n");
else
printf("i is smaller than 7");
}
return 0;
}
if-else-if Ladder
• The if else if statements are used when the user has to
decide among multiple options.
• The C if statements are executed from the top down.
• As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed,
and the rest of the C else-if ladder is bypassed.
• If none of the conditions is true, then the final else
statement will be executed. if-else-if ladder is similar to
the switch statement.
#include <stdio.h>
int main()
{
int i = 20;
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");
}
Switch Statement :
When one of the many alternative is to be
selected, we can use an if statement to
control the selection.
For this reason ‘C’ has a built in multiway
decision statement known as switch.
The switch statement tests the value of a
given variable against a list of case value
and when a match is found, a block of
statement associated with that case is
executed.
5. The Switch Statement
Syntax:
switch(expression)
{
case value-1: block-1
break;
case value-2: block-2
break;
………..
default: default-block
}
Rules for switch statement
• Only those expressions are allowed in switch which
results in an integral constant value.
• Float value is not allowed in switch & case
statements.
•Case label must be integer or character.
• Variable expressions are not allowed in case labels.
Whereas macros are allowed.
•Case label must be unique. No two case labels can
have the same value. Case label must end with
colon.
•The break statement is optional. The default label is
optional. There can be at most one default label.
•The default may be placed any where but usually
placed at the end
•It is permitted to nest switch statement.
Program to display the numbers in words
using switch (Max:2)
#include<stdio.h>
void main()
{
int n;
printf(“\n Enter no”);
scanf(“%d”,&n);
switch(n)
{
case 0 : printf(“ZERO”);
break;
case 1 : printf(“ONE”);
break;
case 2 : printf(“TWO”);
break;
}
}
Write a menu driven program for add, sub,
multi, div of two nos. using switch
#include<stdio.h>
void main()
{
int a,b,c,opt;
printf("\n Enter 2 nos");
scanf("%d%d",&a,&b);
printf("\n1.Add\n2.Sub \n3.Multi\n4.Div");
printf("\n Enter your option");
scanf("%d",&opt);
switch(opt)
{
case 1 :c=a+b;
printf("\nAdd =%d",c);
break;
case 2 : c=a-b;
printf("\nSub=%d",c);
break;
case 3 : c=a*b;
printf("\nMult=%d",c);
break;
case 4 : c=a/b;
printf("\nDiv=%d",c);
break;
default : printf("\nInvalid i/p");
}
}
Accept the selling price and cost price from the
user. Find out if the seller has made profit or
loss.
#include<stdio.h>
void main()
{
int a,b;
printf("Enter the cost price and selling price ");
scanf("%d%d",&a,&b);
if(b>a)
printf("Seller has made profit which is : %d",b-a);
else if(a > b)
printf("Seller has incurred loss which is %d",a-b);
else
printf("Seller has neither made profit nor loss\n");
}
entered is an alphabet, a number or a
special character.
#include<stdio.h>
void main()
{
char n;
printf("Enter a character : ");
scanf("%c",&n);
if(n>=65 && n<=90 || n>=97 && n<=122)
printf("%c is an alphabet\n",n);
else if(n>=48 && n<=57)
printf("%c is a number \n",n);
else
printf("%c is a special symbol",n);
}
A company insures its drivers in the following cases If the driver
is married, If the driver is unmarried, male & above 30 years of
age, If the driver is unmarried, female & above 25 years of age.
In all other cases the driver is not insured. If the marital status,
gender & age of driver is input write a program to determine if
the driver is insured or not.
#include <stdio.h>
void main()
{
int age;
char ms, gender;
printf("Marital status : (M/U)\nGender : (M/F)\n\n");
printf("Enter the marital status , age & Gender of driver:
");
scanf("%c %d %c",&ms,&age,&gender);
if(ms == 'M'|| (ms == 'U' && age>30 && gender =='M') ||(ms
== 'U' && age>25 && gender =='F'))
printf("The driver is insured\n");
else
printf("The driver is not insured");
Loop
If we want to perform the same series of actions in the same way ,more
than once it will be done by using “Loop”.
Loop
It is ability to perform a set of instructions repeatedly.
Two types of Loops
1)Top –Tested (Entry controlled loop )
2)Bottom-Tested (Exit controlled loop)
Entry controlled loop : In this looping the condition is evaluated
before the loop body is executed.
Exit controlled loop: In this looping the condition is evaluated after the
loop body is executed.
The c language provides three statements for performing loop
operation.
•The while statement
•The do statement
•The for statement.
While Loop
It is often used when the number of times the loop is to be
executed is not known in advance but depends on the test
condition.
The while is an entry controlled loop statement.
Syntax :
while(test condition)
{
body of the loop;
}
While Loop
The condition is evaluated and the statement (loop body )is
executed as long as the expression is TRUE.
Since it is an entry controlled loop, if the expression evaluate to
false the first time itself, the loop body will not be executed even
once.
Ex:
int count = 1;
while (count <= 5)
{
printf(“\n%d”,count);
count++;
}
Points to remember
The loop control variable must be initialized.
The loop body must contain a statement to alter the value of the
control variable.
Nested While Loop
Similar to nested if statements, loops can be nested as
well.
That is, the body of a loop can contain another loop.
For each iteration of the outer loop, the inner loop
iterates completely.
Syntax :
while(exp1) --------->Outer Loop
{
while(exp2) --------->Inner Loop
{
loop body of while (exp2);
}
}
Nested While Loop
•How many times will the string "Here" be
printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
printf("Here");
count2++;
}
count1++;
}
The do-while Statement
•It is a bottom tested loop i.e. it evaluates the condition after the
execution of loop body.
•This means that the statements within the loop are executed at
least once.
•Syntax:
do
{
loop body;
}while(condition);
Comparing while and do
while loop
While Loop Do while Loop
•It is a top tested loop •It is a bottom tested
•Condition is evaluated loop
before the executing loop •Condition is evaluated
body. after the execution of
•If the condition is false loop body.
very first time, the loop •The loop body is
body will never executed. executed at least once.
Program
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
char ch =‘a’; Int i=100;
while (ch) while (i)
{ {
Printf(“%d”, ch); Printf(“%d”, i);
ch++; i++;
} }
} }
Do-while Program
#include <stdio.h>
int main()
{
float number, sum = 0; // the body of the loop is executed at least once
do
{
printf("Enter a number: ");
scanf("%f", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2f",sum);
return 0;
}
for loop
•It is very flexible, powerful and most commonly used
loop in C. It is useful when the number of iterations are
known in advance.
Syntax :
for( initialization; test-condition ;
increment or decrement)
{
Body of the loop;
}
The for Statement
A for loop is functionally equivalent to the following
while loop structure:
initialization;
for(initialize;condition;inc/dec)
while(condition) {
statements;
}
{
statement;
increment/decrement;
}
The for Statement
The increment section can perform any
calculation
int num;
for (num=30; num > 0; num -= 5)
{
printf(“%d”, num);
}
Output : 30 25 20 15 10 5
Nested For Loop
•Nested loops consist of an outer loop with
one or more inner loops.
•e.g.,
for (i=1;i<=100;i++)
{
for(j=1;j<=50;j++)
{
…
}
}
•The above loops will be executed for 100*50
times.
/* Program to display the output on the screen */
#include<stdio.h>
void main()
{
int i,j,n;
printf("Enter the value of n :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
printf("*");
printf("\n");
}
}
/* Program to Display 0 to 9 */
#include<stdio.h>
void main()
{
int x;
for(x=0; x<=9 ; x++)
{
printf(“%d”,x);
}
printf(“\n”);
}
Jumps in Loops :
There are four statements which are used to
perform jumps in loops – break, continue,
goto, exit().
break statement :
When the break statement is encountered
inside a loop, the loop is immediately exited
and the program continues with the
statement immediately following the loop.
Syntax :
break;
•Break in while •Break in do while
loop
while (……..) loop
do
{ {
……………….. ………………..
……………….. ………………..
if (condition) if (condition)
break; break;
……………… ………………
}
} while(….) ;
#include <stdio.h>
int main()
{
int n, i, sum=0;
while(1)
{
printf("\nEnter number");
scanf("%d“, &n);
if(n<0)
break;
sum = n+sum;
}
printf("%d", sum);
return 0;
}
continue statement
The use of the continue statement is to skip
the statements which are followed by
‘continue’ and continue with the next
iteration of the loop.
Syntax : continue;
continue in while loop
while (……..)
{
………………..
………………..
if (condition)
continue;
………………
}
#include <stdio.h>
int main()
{
int i, n=2;
for(i=1;i<=20;i++)
{
if (i==n)
{
n = n+2;
continue;
}
printf("%d \n", i);
}
return 0;
}
#include<stdio.h>
#include<math.h>
void main()
{
int count,negative;
float no,sqroot;
printf("Enter 9999 To Stop\n");
count=0; negative=0;
while(count<=20)
{
printf("\nEnter a number :");
scanf("%f",&no);
if(no==9999)
break;
//break statement
if( no < 0 )
{
negative++;
continue; // continue statement
}
sqroot = sqrt(no);
printf("Numer = %f\n Square root = %f\n\
n",no,sqroot); count++;
}//while
printf("\nPositive Numbers = %d\n",count);
printf("\nNegative Numbers = %d\n",negative);
}
goto Statement :
C support go to statement to jump
unconditionally from one point to another in
the program.
Syntax: goto label; label:
……..
Statement;
……..
……….
……..
……….
label:
……….
Statement;
goto Statement
Backward Jump.
If a label is before the statement goto, a loop
will be formed and some statements will be
executed repeatedly, such a jump is known
as Backward Jump.
Forward Jump:
If the label is placed after the goto label,
some statements will be skipped and the
jump is known as a forward jump.
e.g. x=1;
loop:
x++;
if(x<100)
goto loop;
Program – Forward goto statement
#include<stdio.h>
void main()
{
int age;
printf("Enter Age");
scanf("%d", &age);
if (age>=18)
goto VOTE;
Else
printf("Not eligible for vote");
goto ter;
VOTE: printf("Eligible for vote");
ter: return 0;
}
Backward goto statement
#include<stdio.h>
void main()
{
label:
printf("Hello World infinite times");
goto label;
return 0;
}
Using exit() function
The exit() function causes immediate
termination of the entire program.
e.g.
void main()
{
int code;
printf(“\n enter the security code”);
scanf(“%d”,&code);
if(code<0)
exit(0);
----------
}
Program
#include<stdio.h>
#include<stdlib.h>
float sum (int x, int y);
int main()
{
int a=10, b=20;
printf("%f\n",sum(a,b) );
a=20, b=30;
printf("%f\n",sum(a,b) );
return 0;
}
float sum(int x, int y)
{
float z;
z = x+y;
exit (0);
}
Example – 1 : Program to find factorial of given no::
#include<stdio.h>
void main()
{
int i,n;
long fact;
printf(“\n Enter no”);
scanf("%d",&n);
fact=1;
for(i=1;i<=n;i++)
{
fact=fact*i;
printf("\n%d",fact);
}
}
Example: Two numbers are entered through the
keyboard. Write a program to find the value of one
number raised to the power of other.
#include<stdio.h>
void main()
{
int a,b,pow=1,i;
printf("Enter the 2 numbers : ");
scanf("%d%d",&a,&b);
for(i=0;i<b;i++)
{
pow=pow*a;
printf("%d\n",pow);
}
printf("\n%d^%d is %d\n",a,b,pow);
}
Accept a number through the keyboard. Display whether
the given number is prime or not.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int i, num,r,flag;
printf(" Enter the number : ");
scanf("%d",&num);
for(i=2;i<num;i++)
{
r = num % i;
if(r==0)
flag++;
}
if(flag==0)
{
printf(" %d is a prime no",num);
exit(0);
}
printf(" %d is not a prime number ",num);
}
Pyramid Structure Star Pattern
#include <stdio.h>
int main()
{
int n,n1,out,in,sp;
printf("\n Enter n value: ");
scanf("%d", &n);
n1=n;
for(out=1;out<=n*2;out+=2) // outer loop
{
for(sp=n1;sp>=0;sp--) // for spaces
printf(" ");
for(in=1;in<=out;++in) // to print *
{
printf("*");
}
printf("\n");
n1--; // decrement space position
}
}
Write a program to read a no. and check if
it is palindrome or not.
#include<stdio.h>
void main()
{
int n,temp,r;
int rev=0;
printf("Enter a number : ");
scanf("%d",&n);
temp=n;
while(n != 0)
{ r= n%10;
rev = rev*10 + r;
n/=10;
}
if(rev==temp)
printf("%d is Palindrome \n",temp);
else
printf(“%d is not Palindrome\n”,temp);
}