Control Statements
Control Statements
CONTROL STATEMENTS
In C, programs are executed sequentially in the order of which they appear. This condition
does not hold true always. Sometimes a situation may arise where we need to execute a
certain part of the program. Also it may happen that we may want to execute the same part
more than once. Control statements enable us to specify the order in which the various
instructions in the program are to be executed. They define how the control is transferred
to other parts of the program. Control statements are classified in the following ways:
The selection statements are also known as Branching or Decision Control Statements.
Decision making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed
if the condition is determined to be true, and optionally, other statements to be executed if
the condition is determined to be false.
if Statement
The keyword if tells the compiler that what follows is a decision control instruction. The if
statement allows us to put some decision -making into our programs. The general form of
the if statement is shown Fig 2:
if (total_purchase >=1000)
Multiple statements may be grouped by putting them inside curly braces {}. For example:
if (total_purchase>=1000)
{
gift_count++;
printf("You are gifted a pen drive.\n");
For readability, the statements enclosed in {} are usually indented. This allows the
programmer to quickly tell which statements are to be conditionally executed. As we will
see later, mistakes in indentation can result in programs that are misleading and hard to
read.
Programs:
#include<stdio.h>
int main()
{
int no;
printf("Enter a no : ");
scanf("%d", &no);
if(no<0)
{
printf("no entered is negative");
no = -no;
}
printf("value of no is %d \n",no);
return 0;
}
Output:
Enter a no: 6
value of no is 6
Output:
Enter a no: -2
value of no is 2
Output:
Enter 2 nos: 6 0
Division is not possible
if-else Statement
The if statement by itself will execute a single statement, or a group of statements, when
the expression following if evaluates to true. By using else we execute another group of
statements if the expression evaluates to false.
if (a > b)
{ z = a;
printf(“value of z is :%d”,z);
}
else
{ z = b;
printf(“value of z is :%d”,z);
}
The group of statements after the if is called an ‘if block’. Similarly, the statements after
the else form the ‘else block’.
Programs:
Output:
Enter an integer 3
Odd
Output:
Enter an integer 4
Even
return 0;
}
Output:
Enter a year to check if it is a leap year 1996
1996 is a leap year
Output:
Enter a year to check if it is a leap year 2015
2015 is not a leap year
Nested if-else
An entire if-else construct can be written within either the body of the if statement or the
body of an else statement. This is called ‘nesting’ of ifs. This is shown in the following
structure.
if (n > 0)
{
if (a > b)
z = a;
}
else
z = b;
The second if construct is nested in the first if statement. If the condition in the first if
statement is true, then the condition in the second if statement is checked. If it is false,
then the else statement is executed.
Program:
40 is greater than 20
else-if Statement:
This sequence of if statements is the most general way of writing a multi−way decision.
The expressions are evaluated in order; if an expression is true, the statement associated
with it is executed, and this terminates the whole chain. As always, the code for each
statement is either a single statement, or a group of them in braces.
If (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
The last else part handles the ``none of the above'' or default case where none of the other
conditions is satisfied. Sometimes there is no explicit action for the default; in that case
the trailing can be omitted, or it may be used for error checking to catch an “impossible”
condition.
Program:
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n)
{
printf("m is greater than n");
}
else if(m<n)
{
printf("m is less than n");
}
else
{
printf("m is equal to n");
}
}
Output:
m is greater than n
switch case:
This structure helps to make a decision from the number of choices. The switch statement
is a multi−way decision that tests whether an expression matches one of a number of
constant integer values, and branches accordingly [3].
main( )
{ int i = 2; switch
(i)
{
case 1:
printf ( "I am in case 1 \n" ) ;
case 2:
printf ( "I am in case 2 \n" ) ;
case 3:
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ; }
}
I am in case 2
I am in case 3
I am in default
Here the program prints case 2 and 3 and the default case. If you want that only case 2
should get executed, it is up to you to get out of the switch then and there by using a break
statement.
main( )
{
int i = 2 ;
switch ( i )
{
case 1:
printf ( "I am in case 1 \n" ) ;
break ;
case 2:
printf ( "I am in case 2 \n" ) ;
break ;
case 3:
printf ( "I am in case 3 \n" ) ;
break ;
default:
printf ( "I am in default \n" ) ;
}
}
Program
#include <stdio.h>
int main ()
{
char grade;
printf(“Enter the grade”);
scanf(“%c”, &grade);
switch(grade)
{
case 'A' :printf("Outstanding!\n" );
break;
case 'B' : printf("Excellent!\n" );
break;
case 'C' :printf("Well done\n" );
break;
case 'D' : printf("You passed\n" );
break;
case 'F' : printf("Better try again\n" );
break;
default : printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
Output
ITERATIVE STATEMENTS
while statement
The while statement is used when the program needs to perform repetitive tasks. The
general form of a while statement is:
while ( condition)
statement ;
The program will repeatedly execute the statement inside the while until the condition
becomes false(0). (If the condition is initially false, the statement will not be executed.)
Consider the following program:
main( )
{ int p, n, count;
float r, si;
count = 1;
while ( count <= 3 )
{
printf ( "\nEnter values of p, n and r " ) ;
scanf(“%d %d %f", &p, &n, &r ) ;
si=p * n * r / 100 ;
printf ( "Simple interest = Rs. %f", si ) ;
count = count+1;
}
}
#include <stdio.h>
int main()
{
int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or not\n");
scanf("%d",&n);
temp = n;
while( temp != 0 )
{
reverse = reverse * 10;
reverse = reverse +temp%10;
temp = temp/10;
}
if ( n == reverse )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
return 0;
}
Output:
do
{ block of one or more C statements; }
while (test expression)
The test expression must be enclosed within parentheses, just as it does with a while
statement.
// C program to add all the numbers entered by a user until user enters 0.
#include <stdio.h>
int main()
{ int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}
Output:
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
#include <stdio.h>
main()
{
int i = 10;
do
{
printf("Hello %d\n", i );
i = i -1;
}while ( i > 0 );
}
Output
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
Program
#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
do
{
n/=10; /* n=n/10 */
count++;
} while(n!=0);
Output
Enter an integer: 34523
Number of digits: 5
for Loop
The for is the most popular looping instruction. The general form of for statement is as
under:
The for allows us to specify three things about a loop in a single line:
(a) Setting a loop counter to an initial value.
(b) Testing the loop counter to determine whether its value has reached the number of
repetitions desired.
(c) Updating the value of loop counter either increment or decrement.
int main(void)
{
int num;
printf(" n n cubed\n");
for (num = 1; num <= 6; num++)
printf("%5d %5d\n", num, num*num*num);
return 0;
}
The program prints the integers 1 through 6 and their cubes.
n n cubed
1 1
2 8
3 27
4 64
5 125
6 216
The first line of the for loop tells us immediately all the information about the loop
parameters: the starting value of num, the final value of num, and the amount that num
increases on each looping [5].
Grammatically, the three components of a for loop are expressions. Any of the three parts
can be omitted, although the semicolons must remain.
main( )
{
int i ;
for ( i = 1 ; i <= 10 ; )
{
printf ( "%d\n", i ) ;
i=i+1;
}
}
Here, the increment is done within the body of the for loop and not in the for statement.
Note that in spite of this the semicolon after the condition is necessary.
Programs:
9. Program to print the sum of 1st N natural numbers.
#include <stdio.h>
int main()
{
int n,i,sum=0;
printf("Enter the limit: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
sum = sum +i;
}
printf("Sum of N natural numbers is: %d",sum);
}
Output
Enter the limit: 5
Sum of N natural numbers is 15.
#include<stdio.h>
int main()
{
int num,r,reverse=0;
printf("Enter any number: ");
scanf("%d",&num);
for(;num!=0;num=num/10)
{
r=num%10;
reverse=reverse*10+r;
}
printf("Reversed of number: %d",reverse);
return 0;
}
Output:
C programming language allows using one loop inside another loop. Following section shows few
examples to illustrate the concept.
Syntax:
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type of loop.
For example, a for loop can be inside a while loop or vice versa.
Programs:
11. program using a nested for loop to find the prime numbers from 2 to 20:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<20; i++)
{
for(j=2; j <= (i/j); j++)
if(!(i%j))
break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}
Output
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
12. *
***
*****
*******
*********
#include <stdio.h>
int main()
{
int row, c, n,I, temp;
printf("Enter the number of rows in pyramid of stars you wish to see ");
scanf("%d",&n);
temp = n;
for ( row = 1 ; row <= n ; row++ )
{
for ( i= 1 ; i < temp ; i++ )
{
printf(" ");
temp--;
for ( c = 1 ; c <= 2*row - 1 ; c++ )
{
printf("*");
printf("\n");
}
}
}
return 0;
}
#include<stdio.h>
void main ()
{
int a;
a=10;
for (k=1;k=10;k++)
{
while (a>=1)
{
printf ("%d",a);
a--;
}
printf("\n");
a= 10;
}
}
Output:
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
LECTURE NOTE-12
JUMP STATEMENTS
main( )
{
int i = 1 , j = 1 ;
while ( i++ <= 100 )
{
while ( j++ <= 200 )
{
if ( j == 150 )
break ;
else
printf ( "%d %d\n", i, j );
}
}
}
In this program when j equals 150, break takes the control outside the inner while only,
since it is placed inside the inner while.
main( )
{
int i, j ;
for ( i = 1 ; i <= 2 ; i++ )
{
for ( j = 1 ; j <= 2 ; j++ )
{ if ( i == j)
continue ;
printf ( "\n%d %d\n", i, j ) ;
}
}
}
12
21
Note that when the value of I equals that of j, the continue statement takes the control to
the for loop (inner) by passing rest of the statements pending execution in the for loop
(inner).
Kernighan and Ritchie refer to the goto statement as "infinitely abusable" and suggest that
it "be used sparingly, if at all.
The goto statement causes your program to jump to a different location, rather than
execute the next statement in sequence. The format of the goto statement is;
Here, if the if conditions satisfies the program jumps to block labelled as a: if not then it
jumps to block labelled as b:.
Exercise questions:
1. WAP to input the 3 sides of a triangle & print its corresponding type.
2. WAP to input the name of salesman & total sales made by him. Calculate & print the
commission earned.
1-1000 3%
1001-4000 8%
6001-6000 12 %
6001 and above 15 %
3. WAP to calculate the wages of a labor.
TIME WAGE
First 10 hrs. Rs 60
Next 6 hrs. Rs 15
Next 4 hrs. Rs 18
Above 10 hrs. Rs 25
4. WAP to calculate the area of a triangle, circle, square or rectangle based on the user’s
choice.
5. WAP that will print various formulae & do calculations:
i. Vol of a cube
ii. Vol of a cuboid
iii. Vol of a cyclinder
iv. Vol of sphere
6. WAP to print the following series
i. S = 1 + 1/2 + 1/3 ……..1/10
ii. P= (1*2) + (2 *3) + (3* 4)+…….(8 *9) +(9 *10)
iii. Q= ½ + ¾ +5/6 +….13/14
iv. S = 2/5 + 5/9 + 8/13….n
v. S = x + x2 + x3 + x4......+ x9 + x10
vi. P= x + x3/3 + x5/5 + x7/7……………n terms
vii. S= (13 *1) + (12 * 2)……(1 *13)
viii. S = 1 + 1/(2 2) + 1/ (3 3) + 1/(44) + 1/(55)
ix. S = 1/1! + 1/2! + 1/3! ……………+1/n!
x. S = 1 + 1/3! + 1/5!+……..n terms
xi. S = 1 + (1+2) +(1+2+3) + (1+2+3+4)……………+(1+2+3…….20)
xii. S= x + x2/2! + x3/3! + x4/4!.....+x10/10!
xiii. P = x/2! + x2/3! +…….x9/10!
xiv. S = 1 – 2 + 3 - 4………. + 9 – 10
xv. S = 1 -22 + 32 - 42………. +92 - 102
xvi. S = 1/(1 + 2) + 3/(3 + 5)……15/(15 + 16)
xvii. S = 1 +x2/2! – x4/4! + x6/6!....n
xviii. S = 1 + ( 1 + 2) + (1+2+3)……..(1+2+3+4…..20)
xix. S = 1 + x + x2/2 + x3/3…….+xn/n
xx. S = 1 * 3/ 2 * 4 * 5 + 2 * 4 / 3 * 5 * 6 + 3 * 5/ 4 * 6 * 7……..n * (n+2)/ (n+1) *
(n+3) * (n+4)
7. WAP to input a no & print its corresponding table.
8. WAP to print the table from 1 to 10 till 10 terms.
9. WAP to input a no & print its factorial.
10. WAP to input a no & check whether it is prime or not.
11. WAP to input a no & print all the prime nos upto it.
12. WAP to input a no & print if the no is perfect or not.
13. WAP to find the HCF of 2 nos.
14. WAP to print the Pythagoras triplets within 100. (A Pythagorean triplet consists of three
positive integers a, b, and c, such that a2 + b2 = c2).
15. WAP to input a no & check whether its automorphic or not. (An automorphic number is a
number whose square "ends" in the same digits as the number itself. For example, 52 =
25, 62 = 36, 762 = 5776, and 8906252 = 793212890625, so 5, 6, 76 and 890625 are all
automorphic numbers).
16. WAP to convert a given no of days into years, weeks & days.
17. WAP to input a no & check whether it’s an Armstrong no or not. (An Armstrong no is an
integer such that the sum of the cubes of its digits is equal to the number itself. For
example, 371 is an Armstrong number since 33 + 73 + 13 = 371).
18. A cricket kit supplier in Jalandhar sells bats, wickets & balls. WAP to generate sales bill.
Input form the console the date of purchase, name of the buyer, price of each item &
quantity of each item. Calculate the total sale amount & add 17.5 % sales tax if the total
sales amount >300000 & add 12.5 % if the total sales amount is >150000 & 7 %
otherwise. Display the total sales amount, the sales tax & the grand total.
19. WAP to check whether a given number is magic number or not.
20. Write a C program to calculate generic root of the given number. (To find the generic root
of a no we first find the sum of digits of the no until we get a single digit output. That resultant no
is called the generic no. Eg: 456791: 4+5+6+7+9+1=32. 3 +2 =5. So, 5 becomes the generic root
of the given no)