Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Control Statements

The statement which alter flow of execution of a program are known as control statements. In the
absence of control statements, the instructions or statements are executed in same order in which
they appear in source program. Such type of construct is known as sequential construct.
Sometimes tasks are performed on the basis of certain logic test where output comes according
to true or false tests or conditions. Similarly , sometimes it is necessary to perform repeated
actions or skip some statements from execution. For these operations, control statements are
needed. They control flow of program so that it is not necessary to execute statements in the
same order in which they appear in the program.

Figure : Basic Control Structure

Classification of Control statements

1. Sequential
2. Selective (Branching)
a) Two way branching : if...else
b) Multiple branching : if...else if...else and switch
3. Repetitive (Looping)
a) Entry controlled : while and for
b) Exit controlled : do...while

1. Sequential Structure : Sequence simply means executing one instruction after another, in the
order in which they occur in the source file. This is usually built into languages as the default
action, as it is with C. If an instruction is not a control statement, then the next instruction to be
executed will simply be the next one in sequence.

2. Selective Structure (Branching / Decision making statements) : Selection means executing


different sections of code depending on a condition or the value of a variable. This is what allows
a program to take different courses of action depending on different circumstances. Selective
structure are used when we have a number of situations where we may need to change the order
of execution of statements based on certain condition. The decision making statements test a
condition and allow to execute some statements on the basis of result of the test (i.e. either true
or false).C provides the following statements for selective structures.

Compiled By : Deepak Kr. Singh, Pradip Khanal


a) Two way branching and b) Multiple branching

 if statement
 switch statement

if statements

The if statement is a powerful decision making statement and it is used to control the flow of
execution of statements. It is a two way statement and is used in conjunction with a test
expression. Syntax: if(test expression)

if statement allows the computer to evaluate the expression first and then depending on whether
the value of the expression (condition) is true or false, it transfer the control to a particular
statement. The if statement may be implemented in different forms depending on the complexity
of conditions to be tested. Which are :

 Simple if statement
 if...else statement test expression False
 Nested if...else statement
?
 else...if ladder statement

True

Figure : two-way branching

Simple if statement : The simple if statement is used to execute a block of code conditionally
based on whether the given condition is true or false. If the condition is true , the block of code
will be executed, otherwise it will be skipped.

The general form is:

if (test expression)
{
statement-block;
}
statement-x;
Figure : general form and flowchart of
simple if statement.

If the test expression is true the statement-block will be executed otherwise the statement-block
will be skipped and the execution will jump to statement-x. but when the condition is true both
the statement-block and the statement-x are executed sequence.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Example: Write a program that prompts a user to input average marks of a student and adds
10% bonus marks if his/her average marks is greater than or equal to 65%.
#include<stdio.h>
#include<conio.h>
void main()
{
float marks;
clrscr();
printf("Enter marks:");
scanf("%f",&marks);
if(marks>=65)
{
marks=marks+marks*0.1; Output:
} Enter marks:70.00
printf("New marks=%.2f",marks); New marks=77.00
getch();
}

The if...else selection structure : The if...else statement extends the idea of the if statement by
specifying another section of code that should be executed only if the condition is false i.e.,
conditional branching. The form is:
if(test expression)
{
true block statement(s)
}
else
{
false block statement(s)
}
Fig : Syntax and Flowchart
Here , test expression is an expression, that gives true or false values, true-block statement(s) are
to be executed only if the test expression is true and false-block statement(s) is to be executed
only if the condition is false.
Example: WAP to ask the user three sides of a triangle and display the area. Before computing
area check whether the triangle is formed by the given sides or not.
void main()
{
float a, b, c, s, area;
printf("Enter the length of three sides of a triangle: ");

Compiled By : Deepak Kr. Singh, Pradip Khanal


scanf("%f%f%f", &a, &b, &c);
Enter the length of three sides of
if((a+b)>c && (b+c)>a && (c+a)>b)
triangle: 4,5,6
{
s = (a+b+c)/2; Area of triangle: 9.921567
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of the triangle: %f", area); Again
} Enter the length of three sides of
else triangle: 2,4,7
{
printf("The condition is not satisfied."); The condition is not satisfied.
}
}
Assignment
Q. WAP to check the given three points (x1,y1), (x2,y2) and (x3,y3) are collinear or not?
Q. In question number 1, test whether three points are vertex of a triangle or not. If yes, check
the type of triangle and display appropriate message whether it is acute, scalene, right angled,
isosceles and equilateral.
Q.WAP to read two numbers. Suppose a and b and divide a by b and display the appropriate
message whether the quotient is greater than 1 or not.
Q. WAP to compute the return amount (A) given by expression A=p(i(1+i)^n/((1+i)^n-1)) on
investment of p amount of money for n numbers of years and at interest rate i.

The nested if.......else statement : When a series of decision are involved, we may have to use
more one if...else statement in nested form. The ANSI standard specifies that 15 level of nesting
may be continued. In c, an else statement in the same block and not already associated with an if.
Syntax: if(test-expression1)
{
if(test-expression2)
{
statementblock-1;
}
else
{
statementblock-2;
}
}
else
{
statementblock-3;
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Example : WAP to find largest of three different integer number just entered by user.
void main()
{
int a, b, c;
printf("Enter three numbers: ");
scanf("%d%d%d", &a, &b, &c);
if(a>b)
{
if(a>c)
{printf("\nThe largest no. is %d", a);}
else
{printf("\nThe largest no. is %d", c);}
}
else
{
if(b>c)
{printf("\nThe largest no. is %d", b);}
else
{printf("\nThe largest no. is %d", c);}
}
Q. WAP to check whether the entered year is leap year or not.
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
printf("Enter a year:");
scanf("%d", &year);
if(year%4==0)
{
if(year%100==0)
{
if(year%400==0)
{
printf("\n%d is a leap year.",year);
}
else
{
printf("\n%d is not a leap year.",year);
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


}
else
{
printf("\n%d is a leap year.",year);
}
}
else
{
printf("\n%d is not a leap year.",year);
}
}
Using Conditional operator
largest = (a>b)?((a>c)?a:c):((b>c)?b:c);

Example : WAP to read integer and find its square if it is less than 50 else check whether it is
odd or even and display appropriate message.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n, r; //n for integer and r for result.
printf("Enter value of n: ");
scanf("%d", &n);
if(n>0)
{
if(n<50)
{r=pow(n,2); printf("Square of n is %d", r);}
else
{ if(a%2==0)
{printf("%d is even", n);}
else
{printf("%d is odd", n);}
}
}
else
{ print("invalid input");}
getch();
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


The else....if ladder statement : It is another way of putting ifs together when multipath
decisions are involved. A multipath decision is a chain of ifs in which the statement associated
with each else is an if.
Syntax & Flowchart :
if(condition-1)
statement-`1;
else if(condition-2)
statement-2;
else if(condition-3)
statement-3;
..........................
else if(condition-n)
statement-n;
else
default-statement;
statement-x;
Example : WAP that reads a co-ordinate point of rectangular co-ordinate system and display the
appropriate message after checking where the point lies on the co-ordinate system.
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
printf("Enter value of x and y: ");
scanf("%d\t%d\n", &x, &y);
if(x==0 && y==0)
{printf("The point (%d , %d) lies on origin.", x, y);}
else if(x==0 && y>0)
{printf("The point (%d , %d) lies on +ve y-axis.", x, y);}
else if(x==0 && y<0)
{printf("The point (%d , %d) lies on -ve y-axis.", x, y);}
else if(x>0 && y==0)
{printf("The point (%d , %d) lies on +ve x-axis.", x, y);}
else if(x<0 && y==0)
{printf("The point (%d , %d) lies on -ve x-axis.", x, y);}
else if(x>0 && y>0)
{printf("The point (%d , %d) lies on 1st quadrant.", x, y);}
else if(x<0 && y>0)
{printf("The point (%d , %d) lies on 2nd quadrant.", x, y);}
else if(x<0 && y<0)

Compiled By : Deepak Kr. Singh, Pradip Khanal


{printf("The point (%d , %d) lies on 3rd quadrant.", x, y);}
else
{printf("The point (%d , %d) lies on 4th quadrant.", x, y);}
getch();
}
Output :
Enter values of x and y: -3 5
The point (-3 , 5) lies on 4th quadrant.
Assignment:
Q. WAP that prompts the user to enter any integer from 1 to 7 and display the corresponding day
of user.
Q. WAP to read the marks secured by a student and display the appropriate message as follows:
 Marks greater or equal to 40 and less than 65 display PASS.
 Marks greater or equal to 65 and less than 80 then display 1st division.
 Marks greater or equal to 80 then display Distinction.
 Otherwise failed.
Q. WAP to calculate the commission of a salesman when sales and the region of the sales are
given as input. The commission is calculated with the rules as follows:
 Nil when sales < 10000 in region A when sales < 8000, in region B.
 15% of sales when sales < 20000 in region A when sales < 12000 in region B.
 20% of sales when sales >=14000 in region

Switch statement : C has built a multi way decision statements known as switched, that tests the
value of an expression against a list of case values (integer or character constants). When a
match is found, the statements associated with that case is executed.
Syntax:
switch (expression)
{
case constant1:
block of case constant1;
break;
case constant2:
block of case constant2;
break;
case constant3:
block of case constant3;
break;
.................................................
.................................................
default:

Compiled By : Deepak Kr. Singh, Pradip Khanal


default block;
}
next statement(s);

- The expression is an integer or character expression.


- Constant1, Constant2.......... are constant or constant expression( evaluable to an integral
constant) and are called as case labels.
- Case labels should be unique and end with :
- ANSI C requires at least 257 case labels allowed in a switch statement.
- The break statement at the end of each block indicates the end of a particular case and causes
as exit from the switch statement, transferring the control to statement following the switch. If
the break statement is omitted, execution continues on into the next case statement until either a
break or the end of the switch is reached.
- The default is an option case. When present, it will be executed if the value of expression does
not match with any of the case constants. If not present, no action takes place if all the matches
fails and control goes to statement-x.
- It is possible to nest the switch statement. A switch may be the part of case block. ANSI allows
15 levels of nesting.

Switch Statement Behavior


Condition Action
The value of switch expression is matched to Control will be transferred to the statements
a case label. following that label.
The value of switch expression is not Control will be transferred to the statements
matched to any case label and the default following default label.
label is present.
The value of switch expression is not Control will be transferred to the statement
matched to any case label and the default is after the switch statement.
not present.

Q. WAP that to determine all roots of a quadratic equation by using switch statement.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, r1, r2, discriminant, realpart, imaginarypart;
int switchexpression;
printf("Enter value of a, b, c: ");
scanf("%f %f %f", &a, &b, &c);
discriminant=pow(b,2)-4*a*c;

Compiled By : Deepak Kr. Singh, Pradip Khanal


if(discriminant==0)
{switchexpression=500;}
if(discriminant>0)
{switchexpression=600;}
if(discriminant<0)
{switchexpression=700;}
switch(switchexpression)
{
case 500:
r1=r2=-b/(2*a);
printf("Roots are real and equal which are %f, %f", r1, r2);
break;
case 600:
r1=(-b+sqrt(discriminant))/(2*a);
r2=(-b-sqrt(discriminant))/(2*a);
printf("Roots are real and unequal which are %f, %f", r1, r2);
case 700:
realpart=-b/(2*a);
imaginarypart=sqrt(4*a*c-pow(b,2));
printf("Root1=%f+i%f\n", realpart, imaginarypart);
printf("Root2=%f-i%f\n", realpart, imaginarypart);
default:
printf("Invalid input");
}
getch();
}
Q. WAP that asks an arithmetic operator and two operands and performs the corresponding
operation on the operands.
Q. Write a menu driven program to calculate having options: a) Factorial of a number. b) Odd or
Even. c) Area of circle. d) Exit.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Difference between else....if and switch case statements
else........if construct switch construct
An expression is evaluated and the code An expression is evaluated and the code block
block is selected based on the result of is selected based on the value of expression.
expression.
Each if has its own logical expression to be Each case is referring back to the expression in
evaluated as true or false. the switch statement.
The variables in the expression may evaluate The expression must evaluate to an integer or
to a value of any type such as int, float or character
character etc.
It does not require break statement becauseIt needs involvement of break statements to
only one block of code is executed at a time.
avoid execution of block just below the current
executing block.
It takes decision on the basis of non zero It takes decision on the basis of equality.
(true) or false (zero) basis.

The conditional Operator : It is used for two way decision.


General form:
conditional expression? expression1: expression2;
Q. WAP that finds the value of y based on the value of x in the following function.

y={2x+300 for x<50, 200 for x=50 and 50x-100 for x>50}
#incude<stdio.h>
#include<conio.h>
void main()
{
float x, y;
printf("Enter value of x: ");
scanf("%f", &x);
y=(x!=50)?((x<50)?(2x+300):(50x-100)): 200;
printf("y = %f", y);
getch();
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


3. Repetitive Structure (Looping) : Repetition means executing the same section of code more
than once. A section of code may either be executed a fixed number of times, or while some
condition is true. In repetitive structure, a sequence of steps which is specified once, may be
executed for a specified number of times or until some condition is met.
The structure, which execute the statements for a specified number of times is called count-
controlled loop.
The structure which executes the statements until some condition is met are called
condition(sentinel) controlled loops.
A looping process, in general, would include the following 4 steps.
1) Setting and initialization of a counter.
2) Execution of statements in the loop.
3) Test for a specified condition for execution for the loop.
4) Updating the counter.

C provides 3 loop constructs for performing loop generations.

a) while
b) do...while
c) for

a) while statement : It specifies that a section of code should executed while a certain condition
holds true.
Syntax & flowchart :
while(test_expression)
{
body of loop
}

Here, test condition is evaluated first and if it is true (non-zero), then the body of loop will be
executed. After execution of body, the test condition is once again evaluated and if it is true, the

Compiled By : Deepak Kr. Singh, Pradip Khanal


body will be executed once again. This process of repeated execution of body continues until the
test condition finally becomes false and the control will be transferred out of loop.
The while loop can also be forcefully terminated when a break, goto or return within loop is
executed.
Continue statement is used to terminate the current iteration without exiting the while loop.
Continue passes control to the next iteration of the while loop.
Example: WAP to read a positive integer and display the sequence :
1 2 3 .......... n-1 n n-1 .......... 3 2 1
#include<stdio.h>
void main()
{
int n ,i, a=1;
printf("Enter a positive integer:");
scanf("%d",&n);
i=1;
while(i>=1)
{
printf("%d",i);
if(i==n)
{
a=-a;
}
i=i+a;
}
}
Output:
Enter a positive integer:10
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
Q. WAP to find binary equivalent of a decimal integer number.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i,base=1,sum=0,rem;
printf("Enter a number:");
scanf("%d",&num);
i=num;
while(num!=0)
{
rem=num%2;

Compiled By : Deepak Kr. Singh, Pradip Khanal


sum=sum+rem*base;
base=base*10;
num=num/2;
}
printf("Binary equivalent = %d",i,sum);
}
Q. WAP to convert binary number to decimal number.
#include<stdio.h>
#include<conio.h>
void main()
{
int num, binary_val, decimal_val=0,base=1,rem;
printf("Enter a binary number (1s & 0s) : ");
scanf("%d", &num);
binary_val=num;
while(num>0)
{
rem=num%10;
decimal_val=decimal_val+rem*base;
num=num/10;
base=base*2;
}
printf("\nBinary no=%d",binary_val);
printf("\nDecimal no=%d",decimal_val);
}
b) do...while statement : It is very much similar to while statement. It also specifies that a
section of code should be executed while a certain condition holds true.
Syntax & flowchart :
do
{
body of loop.
}while(test_expression);

Compiled By : Deepak Kr. Singh, Pradip Khanal


Difference between a do...while construct and while construct is that the while construct tests its
condition at the beginning of its structure but do...while structure tests its condition at the bottom
of its structure. If the test condition in while construct is false at the beginning, body of construct
will not be executed but in case of do...while construct will be executed at least once.
Example : WAP to find sum of digits after reading a +ve integer.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, sum=0, r;
printf("Enter a +ve integer:");
scanf("%d", &n);
do
{
r=n%10;
sum=sum+r;
n=n/10;
}while(n!=0);
printf("\nSum=%d", sum);
}
Q. Check palindrome number using do..while.

c) for statement : Both while and do...while statements provide repetition until some condition
becomes false.
for statement is used to execute a block of code for a fixed number of repetition.
Syntax & flowchart :
for(initialization;test_expression;update_expression)
{
body of loop.
}

Example : WAP to print number of stars specified by a user.

Compiled By : Deepak Kr. Singh, Pradip Khanal


#include<stdio.h>
void main()
{
int num, i;
printf("Enter the number of stars: ");
scanf("%d", &num);
for(i=0;i<num;i++)
{
printf("*");
}
}
Q. WAP to read a non-negative integer and display its factorial.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
long int fact=1;
printf("Enter a non-negative integer : ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf("The factorial of the number is %ld",n,fact);
}
Q. WAP that will generate every third integer beginning with i=2 and continuing for all integer
that are less than 100. Calculate the sum of these numbers that are exactly divisible by 7.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, sum=0;
for(i=2;i<100;i=i+2)
{
if(i%7==0)
{
sum=sum+i;
}
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


printf("The sum = %d",sum);
}

Nesting of loops
Putting one loop statement within another loop statement is called nesting of loop.
a) Nesting of for loops : Putting one for statement within another for statement is called nesting
of for loops.
general form : for(initialization;test_expression;update_expression)
{
for(initialization;test_expression;update_expression)
{
.......................
.......................
}
}
Nesting may be continued up to 15 levels in ANSI C. Many compilers allow more than 15 levels.
Q. WAP to display the multiplication table of m by n.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,rows,columns;
printf("Enter row and column size : ");
scanf("%d%d", &rows, &columns);
for(i=1;i<=rows;i++)
{
for(j=1;j<=columns;j++)
{
printf("%d\t",i*j);
}
printf("\n");
}
}
b) Nesting of while loops
general form : while(test_expression)
{
while(test_expression)
{
............................
............................

Compiled By : Deepak Kr. Singh, Pradip Khanal


}
}
Q. WAP to display the multiplication table of m by n.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,rows,columns;
printf("Enter row and column size : ");
scanf("%d%d", &rows, &columns);
i=0;
while(i<=rows)
{
j=0;
while(j<=columns)
{
printf("%d\t",i*j);
j++;
}
i++;
printf("\n");
}
}
c) Nesting of do...while loops
general form : do
{
do
{
........................
........................
}
}
Q. WAP to display the multiplication table of m by n.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,rows,columns;
printf("Enter row and column size : ");
scanf("%d%d", &rows, &columns);

Compiled By : Deepak Kr. Singh, Pradip Khanal


i=0;
do
{
j=0;
do
{
printf("%d\t",i*j);
j++;
}while(j<=columns);
i++;
printf("\n");
}while(i<=rows);
}
Assignment
Q. WAP to print Armstrong numbers in range between two positive integer given by user.

Entry Controlled Loop (pre-test loop) & Exit Controlled Loop (post-test loop)
Entry Controlled Loop Exit Controlled Loop
Test condition appears at the beginning of Test condition appears at the end of loop.
loop.
Control variable is counter variable. Control variable is counter and sentinel
variable.
Each execution occurs by testing condition. Each execution except first the first one occurs
by testing condition.
for and while loop belongs to entry do...while loop belongs to exit controlled loop.
controlled loop.
Example: ------------ Example: ------------------------
Sum=0; do
N=1; {
while(n<=10)
{ printf("Input a number: ");
sum= sum + pow(n,2); scanf("%d",&num);
n=n+1; }while(num>0);
} --------------------------
----------------------

Compiled By : Deepak Kr. Singh, Pradip Khanal


Jumps in loops
Loop performs a set of operations repeatedly until the control variable fails to satisfy the test
condition. The number of times a loop is repeated is decided in advance and the test condition is
written to achieve this. Sometimes, while executing a loop it becomes desirable to skip a part of
loop or to leave the loop as soon as a certain condition occurs. C permits a jump from one
statement to another within loop as well as a jump out of a loop.
break, continue, goto and return statements are used for jumping purpose.

The break statements


 It is used to jump out of a loop.
 It terminates the execution of the nearest enclosing loop.
 It is used with conditional statements and with the while, do..while and for loop
statements.
Syntax:

Compiled By : Deepak Kr. Singh, Pradip Khanal


Q. WAP to enter an integer and display a message whether the number is prime or not.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
printf("Enter an integer greater than 1 : ");
scanf("%d", &n);
for(i=2;i<n/2;i++)
{
if(n%2==0)
{break;}
}
if(i==n/2)
{
printf("\n%d is prime.",n);
}
else
{
printf("\n%d is not prime.",n);
}
getch();
}

The continue statements


 It is used to bypass the remaining part of current pass of a loop.
 The loop will not be terminated when a continue statement is encountered.
 The remaining loop statements are skipped and the computation proceeds directly to next
pass through the loop.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Syntax :

In the while or do...while loop, the next iteration starts by re-evaluating the test condition.
Depending on the result, the loop either terminates or another iteration occurs.
In the for loop (using the syntax for(initialization; condition; update)), continue causes update
expression to be executed. Then test condition s re-evaluated and depending on the result, the
loop either comes to an end or begins next repetition.

Example : WAP to print the alphabetic characters and their ASCII values in range from 65 to
122. But there are non-alphabetic character from 91 to 96 which are skipped using continue
statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=65; i<=122; i++)
{
if(i>90 && i<96)
{
continue;
}
printf("%c=%d",i,i);

Compiled By : Deepak Kr. Singh, Pradip Khanal


}
getch();
}

The goto statements


 It is used to alter the normal sequence of program execution by transferring control to
some other part of the program.
 It is written as: goto label;
Where label is an identifier that is used to label the target statements to which the
control will be transferred.
The target statements must be labeled and the label must be followed by a colon. The
target statements will appear as :
label:
statement;

Each label statement within the program must have a unique label.
Label can be before or after the goto statements.
goto breaks the normal sequence of program.
Backward jump : If the label: is before the statement goto label; a loop will be formed
and some statement will be executed repeatedly. Such a jump is called as backward jump.
General form: label:
.......................
.......................
goto label;
statements;

Forward jump : If the label: is after the goto label; statements, some statements will be
skipped and the jump is called as a forward jump.
General form: goto label;
..................
..................
label:
statements;

Example : Use of goto statements


#include<stdio.h>
#include<conio.h>
void main()
{
int i, j;

Compiled By : Deepak Kr. Singh, Pradip Khanal


for(i=0; i<10; i++)
{
printf("Outer loop executiing.i=%d\n",i);
for(j=0; j<2; j++)
{
printf("Inner loop executing.j=%d\n",j);
if(i==3)
{goto stop;}
}
}
printf("Loop exited.i=%d\n",i);
stop:
printf("Jumped to stop.i=%d\n",i);
getch();
}

Compiled By : Deepak Kr. Singh, Pradip Khanal

You might also like