UNIT-II
Objective:
Familiarize about control statements in C language.
Syllabus:
Simple sequential programs Conditional Statements: simple if , if-else, else-
if ladder, switch
Loops: for, while, do-while
Unconditional branching: break and continue
Learning Outcomes:
At the end of the unit student will be able to:
Understand the control statements in C.
solve moderate problems on computer using control statements in C.
Learning Material
CONTROL STATEMENTS:
Controlling the flow of program is very important aspect of programming.
Control flow relates to the order in which the operations of a program
executed.
Two types of control structures:
Selection/Branching Statements
Iteration/loop Statements
SELECTION STATEMENTS:
A selection statement selects among a set of statements depending on
the value of a controlling expression.
The selection statements are:
if statement
switch statement
C has four kinds of if statements that permit the execution of a single
statement or a block of statements based on the evaluation of a test
expression. The statements are
1. if
2. if-else
3. if-else-if
4. nested if
1. if Statement:
An if statement consists of a Test expression followed by one or more
statements. It is a one-way decision statement.
Syntax:
if(Text Expr)
{
/*statement(s) will execute if the Test expression is true*/
}
If the Test expression evaluates to true, then the block of code
inside the 'if' statement will be executed.
If the Test expression evaluates to false, then the first set of code
after the end of the 'if' statement (after the closing curly brace) will
be executed.
Flow Diagram
Example
#include<stdio.h>
void main()
{
int a=10; /*local variable declaration*/
if(a<20)
{
printf(“a is less than 20\n”);
}
printf(“The value of a :%d”,a);
}
When the above code is compiled and executed, it produces the following
result −
a is less than 20
The value of a: 10
C programming language assumes any non-zero and non-null values
as true, and if it is either zero or null, then it is assumed as false value.
2. if-else statement:
It is a two-way decision statement. Similar to one-way decision, the
decision here is based on the test expression.
Syntax
if(Text Expr)
{
/*statement(s) will execute if the Test expression is true*/
}
else
{
/*statement(s) will execute if the Test expression is false*/
}
If the Test expression evaluates to true, then if block will be
executed.
Otherwise, else block will be executed.
Flow Diagram
Example
#include<stdio.h>
void main()
{
int a=10; /*local variable declaration*/
if(a<20)
{
printf(“a is less than 20\n”);
}
else
{
printf(“a is not less than 20\n”);
}
}
When the above code is compiled and executed, it produces the following
result
a is less than 20
3. if-else-if Statement: (else-if ladder)
It is a multi-way decision statement. These are used to test various
conditions.
When using if-else-if statements, there are few points to keep in mind −
An if can have zero or one else's and it must come after any else
if's.
An if can have zero to many else if's and they must come before
the else.
Once an else if succeeds, none of the remaining else if's or else's
will be tested.
Syntax
if(Test Expr1)
{
/*statement(s) will execute if the Test expression1 is true*/
}
else if(Test Expr2)
{
/*statement(s) will execute if the Test expression2 is true*/
}
.
.
else if(Test ExprN)
{
/*statement(s) will execute if the Test expressionN is true*/
}
else
{
/*executes when the none of the above condition is true*/
}
Flow Diagram
Test
Expr1
Test
Expr2
Statement(s) 1
Test
ExprN
Statement(s) 2
else block
Statement(s) N
Example
#include<stdio.h>
void main()
{
int a=100; /*local variable declaration*/
if(a= =20)
{
printf(“Value of a is 20\n”);
}
else if(a==30)
{
printf(“Value of a is 30\n”);
}
else if(a==40)
{
printf(“Value of a is 40\n”);
}
else
{
printf(“None of the values is matching”);
}
}
When the above code is compiled and executed, it produces the following
result
None of the values is matching
4. Nested if statement
When any if statement is written under another if statement,
this cluster is called nested if.
It is always legal in C programming to nest if-else
statements, which means you can use one if or else if
statement inside another if or else if statement(s).
Syntax
if(Test Expr1)
/*Statements will execute if the test expr 1 is true*/
if(Test Expr2)
/*Statements will execute if both test expr1 and test
expr2 is true*/
Example
#include<stdio.h>
void main ( )
{
int a, b, c;
printf (“\n enter three numbers :”);
scanf (“%d%d%d ”, &a,&b,&c);
if(a > b)
{
if(a>c)
{
printf(“\n a is big”);
}
else
{
printf(“\n c is big”);
}
}
else
{
if (b > c)
{
printf(“\n b is big”);
}
else
{
printf(“\n c is big”);
}
}
When the above code is compiled and executed, it produces the
following result :
Enter three numbers:
264
b is big
Dangling else problem:
In nested if statements, when a single “else clause” occurs, the situation
happens to be dangling else. For example:
if(condition)
if(condition)
if(condition)
else
printf(“dangling else!”);
1. In such situations, else clause belongs to the closest if statement
which is incomplete that is the innermost if statement.
2. However, we can make else clause belong to desired if statement
by enclosing all if statements in block outer to which if statement
to associate the else clause.
For example:
if(condition)
if(condition)
if(condition)
}
else
printf(“\n else associates with the outermost if statement”);
switch statement:
A switch case statement is a multi-way decision statement that is
simplified version of if-else block that evaluates only one variable.
Syntax:
switch (expr)
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
-------------
-------------
default: stmtListN;
The following rules apply to a switch statement −
The expression used in a switch statement must have an integral or
enumerated type, or be of a class type in which the class has a single
conversion function to an integral or enumerated type.
You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear
at the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.
Flow Diagram
Example
#include<stdio.h>
#include<conio.h>
void main()
int a,b,ch,c;
clrscr();
printf(“\nenter a and b values”);
scanf(“%d%d”,&a,&b);
printf(“\n1.Addition\t2.Subtraction\t3.Multiplication\t4.Division”)
;
scanf(“%d”,&ch);
switch(ch)
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
default: printf(“\nenter valid choice”);
printf(“\nresult=%d”,c);
getch();
When the above code is compiled and executed, it produces the following result
enter a and b values
56
1. Addition 2 .Subtraction
3.Multiplication 4.Division 1
result=11
ITERATION STATEMENTS:
Iterative statements are used to repeat the execution of a list of
statements, depending on the value of an integer expression.
C language supports three types of iterative statements also known as
looping statements. They are:
while loop
do-while loop
for loop
1. while loop
The while loop provides a mechanism to repeat one or more
statements while a particular condition is true.
Syntax:
statement x;
while(condition)
{
statement block;
}
statement y;
In the while loop, the condition is tested before any of the
statements in the statement block is executed.
If the condition is true only the statement block will be
executed otherwise (if the condition is false), the control will
jump to statement y, which is the immediate statement
outside the while loop block.
Flow Diagram:
Statement x
update the condition
expression
Condition
T F
Statement block
Statement y
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=1;
clrscr();
while(a<=5)
{
printf(“%d\t”,a);
a++;
}
}
When the above code is compiled and executed, it produces the
following result
1 2 3 4 5
2. do-while loop
The do-while loop is similar to the while loop. The only difference is
that in a do-while loop, the test condition is tested at the end of
the loop. Now the test condition is tested at the end, this clearly
means that the body of the loop gets executed at least one time
even if the condition is false.
Syntax:
statement x;
do
{
statement block;
}while(condition);
statement y;
Disadvantage: The major disadvantage of using a do-while loop is
that it always executes at least once, even if the user enters some
invalid data.
Flow Diagram
Statement x
Statement block
Update the condition
expression
Condition
T
F
Statement y
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr( );
do
{
printf(“%d\t”,i);
i++;
}while(i<=5);
}
When the above code is compiled and executed, it produces the
following result
1 2 3 4 5
3. for loop
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of
times.
Syntax:
for( initialization; condition; increment/decrement/update)
{
statement block;
}
statement y;
Flow Diagram:
Initialization of loop
variable
Controlling F
condition for
loop variable
Statement block
Update the loop
variable
Statement y
Here is the flow of control in a 'for' loop −
The initialization step is executed first, and only once. This step
allows you to declare and initialize any loop control variables. You
are not required to put a statement here, as long as a semicolon
appears.
Next, the condition is evaluated. If it is true, the body of the loop
is executed. If it is false, the body of the loop does not execute and
the flow of control jumps to the next statement just after the 'for'
loop.
After the body of the 'for' loop executes, the flow of control jumps
back up to the increment statement. This statement allows you
to update any loop control variables. This statement can be left
blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop
executes and the process repeats itself (body of loop, then
increment step, and then again condition). After the condition
becomes false, the 'for' loop terminates.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for( i=1; i<=5; i++)
{
printf(“%d\t”,i);
}
}
When the above code is compiled and executed, it produces the
following result
1 2 3 4 5
Nested loops
C programming allows us to use one loop inside another loop. The
following section shows few examples to illustrate the concept.
Syntax for nested for loop
for ( initialization; condition; increment/decrement/update)
{
for ( initialization; condition; increment/decrement/update)
{
statement(s);
}
statement(s);
}
Syntax for nested while loop
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
Syntax for nested do-while loop
do
{
statement(s);
do
{
statement(s);
}while(condition);
}while(condition);
Note: you can put any type of loop inside any other type of loop. For
example, a 'for' loop can be inside a 'while' loop or vice versa.
JUMP STATEMENTS:
Jump statements cause an unconditional jump to another statement
elsewhere in the code. They are used primarily to
interrupt switch statements and loops. The jump statements are:
1. break statement
2. continue statement
1. break statement :
The break statement in C programming has the following two usages −
When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the
next statement following the loop.
It can be used to terminate a case in the switch statement.
If you are using nested loops, the break statement will stop the execution
of the innermost loop and start executing the next line of code after the
block.
Syntax
break;
Flow Diagram
Example
#include<stdio.h>
void main()
{
int i=0;
while(i<=10)
{
if(i= = 5)
{
break;
}
printf(“\t%d”,i);
i=i+1;
}
}
When the above code is compiled and executed, it produces the
following result
0 1 2 3 4
2. continue statement :
The continue statement in C programming works somewhat like
the break statement. Instead of forcing termination, it forces the next
iteration of the loop to take place, skipping any code in between.
Syntax :
continue;
Flow Diagram
Example
#include<stdio.h>
void main()
{
int i=0;
while(i<10)
{
i=i+1;
if(i= = 5)
continue;
printf(“\t%d”,i);
}
}
When the above code is compiled and executed, it produces the
following result
1 2 3 4 6 7 8 9 10
Problem Solving:
1. Write a C program to generate electricity bill.
#include <stdio.h>
main()
float a=0,u;
system("cls");
printf("Enter the number of units");
scanf("%f", &u);
if(u<=50)
a= u* 0.75;
else if(u >50 && u <=100)
a=0.75 * 50 + 0.85*(u-50);
else if(u >100 && u <200)
a=(0.75*50) + (0.85*50 )+ (1.5 *(u-100));
else if(u >200 && u <300)
a=(0.75*50) + (0.85*50 )+ (1.5 *100) + (2.20 *(u-200));
else
a=(0.75*50) + (0.85*50 )+ (1.5 *100) + (2.20 * 100) +(3.0*(u-300));
a=a+(0.2*a);
printf("The total electricity bill is %f", a);
getch();
Output:
Enter the number of units100
The total electricity bill is 96.000000
2. Write a C program to simulate a calculator using switch case.
#include"stdio.h"
main()
int a,b;
char ch;
clrscr();
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
printf("\n Enter Ur choice:");
printf("\n Enter + for Addition:");
printf("\n Enter - for Subtraction:");
printf("\n Enter * for Multiplication:");
printf("\n Enter / for Division:");
printf("\n Enter %% for Mod:\n");
ch=getche();
switch(ch)
case '+':printf("\n Addition is:%d",a+b);
break;
case '-': printf("\n Subtraction is:%d",a-b);
break;
case '*':printf("\n Multiplication is:%d",a*b);
break;
case '/':printf("\n Division is:%f",(float)a/b);
break;
case '%':printf("\n Mod value is:%d",a%b);
break;
default: printf("\n Enter Correct choice, The choice must be +,-,*,/
and %");
getch();
Output:
Enter two values: 6 7
Enter Ur choice:
Enter + for Addition:
Enter - for Subtraction:
Enter * for Multiplication:
Enter / for Division:
Enter % for Mod:
Division is: 0.857143
3. Implement C code to find out the roots of the quadratic
equation.
#include"stdio.h"
#include"math.h"
main()
float a,b,c,d,r1,r2;
clrscr();
printf("\n Enter three values");
scanf("%f%f%f",&a,&b,&c);
d=b*b-4*a*c;
if(d==0)
r1=r2=-b/(2*a);
printf("\n Roots are equal");
printf("\n r1=%f and r2=%f",r1,r2);
else if(d<0)
printf("\n Roots are imaginary:");
r1=-b/(2*a);
r2=sqrt(-d)/(2*a);
printf("\n r1=%f+i%f",r1,r2);
printf("\n r2=%f-i%f",r1,r2);
else
printf("\n Roots are real:");
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf("\n r1=%f",r1);
printf("\n r2=%f",r2);
getch();
Output:
Enter three values 1 2 3
Roots are imaginary:
r1=-1.000000+i1.414214
r2=-1.000000-i1.414214
4. Develop C program to Check a number is palindrome or not.
#include<stdio.h>
void main()
int n,s=0,k;
system("cls");
printf("Enter an integer:");
scanf("%d",&n);
k=n;
while(n>0)
s=s*10+n%10;
n/=10;
if(k==s)
printf("\n%d is Palindrome",k);
else
printf("\n%d is Not a Palindrome",k);
getch();
Output:
Enter an integer: 121
121 is Palindrome
5. Write a C program to find out given number is prime or not.
#include<stdio.h>
void main()
int n,c=0,i;
clrscr();
printf("\nEnter an Integer:");
scanf("%d",&n);
for(i=1;i<=n;i++)
if(n%i==0)
c++;
if(c==2) //use c!=2 for Non-Prime number checking
printf("%d is Prime Number",n);
else
printf("%d is Not a Prime Number",n);
getch();
Output:
Enter an Integer: 7
7 is Prime Number