CONTROL
STATEMENT
As the name
suggests, 'control statements' specify the order in which the various
instructions in a program are to be executed by the computer. In other words,
the control statements determine the 'flow of control' in a program. There are
four types of control statements in C. They are:
-
Sequence control statement
-
Selection or Decision control statement
-
Case control statement
-
Repetition or Loop control statement
The sequence control statement ensures that the
instructions in the program are executed in the same order in which they appear
in the program. Decision and Case control statements allow the computer to take
a decision as to which statement is to be executed next. The Loop control
statement helps computer to execute a group of statements repeatedly till a
condition is satisfied.
Blocks and Statement:
An expression such as x = 0 or i++ or
printf(...) becomes a statement when it is followed
by a semicolon, as in :
x = 0;
i++;
printf(...);
In C, the semicolon is a statement terminator.
Braces {} are used to group declarations and statements together into a
compound statement, or block, so that they are syntactically equivalent to a
single statement. C has three major decision making instructions:
the if statement, the if-else statement, and the
switch statement. A fourth, somewhat less important structure is the conditional
operator.
The if Statement:
Many a times, we want one set of instructions to be
executed in one situation, and an entirely different set of instructions to be
executed in another situation. This kind of situation is dealt in C programs
using decision control statements.
The general form of if statement
looks like this:
if
( this condition is true )
execute this statement ;
The keyword if tells the compiler that what
follows, is a decision control instruction. The condition following the keyword
if is always enclosed within a pair of parentheses. If the condition is
true, then the statement is executed. If the condition is not true then the
statement is not executed, and the program skips past it.
Multiple Statements within if:
It may so happen that in a program we want more than
one statement to be executed if the condition following the
if keyword is satisfied. If such multiple statements are to be executed
then they must be placed within a pair of braces.
The if-else Statement:
The if statement by itself
will execute a single statement, or a group of statements, when the condition
following if keyword is true. It does nothing when it is false. We execute one
group of statements if the condition is true and another group of statements if
the condition is false. This is what is the purpose of the else statement.
For example :
/* Calculation of Gross salary */
#include<stdio.h>
main( )
{
float bs, gs, da, hra ;
printf( "Enter basic salary" ) ;
scanf ( "%f", &bs) ;
if ( bs >= 1500 )
{
hra
= 500 ; da = bs * 50 / 100 ;
}
else
{
hra=
bs * 10 /100 ; da = bs * 25 / 100 ;
}
gs = bs + hra + da ;
printf("gross salary = Rs.%f",gs);
}
Here if the condition (bs >=
1500) is satisfied then the if block statements are executed, otherwise
the else block statements are executed.
Nested if's:
It is perfectly possible to write an entire if-else
construct within either the body of the if
statement or the body of an else statement. This is called 'nesting' of
if's. The program given below illustrates
this.
For example :
/* A quick demo of nested if else's */
main()
{
int
i;
printf("Enter either 1 or 2");
scanf("%d", &i);
if(i ==1)
printf("You
will go to heaven, for the good deeds ");
else
{
if( i ==2)
printf("Hell
was created with the bad deeds done by you in mind");
else
printf("How
about mother earth !");
}
}
Note that the second if-else construction is
nested in the first else statement. If the condition in the
first if statement is false, then the condition in the second if
statement is checked. If it is false as well, the final else statement is
executed.
If-else-if ladder:
The construction :
if
( expression )
statement
else
if ( expression )
statement
else
if ( expression )
statement
else
if ( expression )
statement
else
if ( expression )
statement
else
statement
This sequence of if
statements is the most general way of writing a multi-way decision. The
expressions are evaluated in order. If any 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 in braces.
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 else statement can
be omitted, or it may be used for error checking to catch an "impossible"
condition.
Switch:
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.
switch
(expression) {
case
const-expr: statements
case const-expr: statements
default : statements
}
Each case is labelled by one or more
integer-valued constants or constant expressions. If a case matches the
expression value, execution starts at that case. All case expressions must be
different. The case labelled default is executed if none of the other cases are
satisfied. A default is optional: if it isn't there and if none of the cases
match, no action at all takes place.
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");
}
}
The output of this program would be:
I am in case 2
The break statement causes an immediate exit from the
switch. Because cases serve just as labels, after the code for one case is done,
execution falls through to the next unless you take explicit action to escape.
Break and return are the most common ways to leave a switch.
Loops in C:
The versatility of the computer lies in its ability to
perform a set of instructions repeatedly. This involves repeating some portion
of the program either a specified number of times or until a particular
condition is being satisfied. This repetitive operation is done through a loop
control statement.
There are three methods by way of which we can repeat a part of a program. They
are:
a) Using a
while statement.
b) Using a for statement.
c) Using a do-while statement.
While Loop:
It is often the case in programming that you want to do
something a fixed number of times. Perhaps you want to calculate gross salaries
of ten different persons, or you want to convert temperatures from centigrade to
fahrenheit for 15 different cities.
The while loop is ideally suitable for such cases.
Let us look at a simple example, which uses a while loop.
/* Calculation of simple interest for 3 sets of p, n and r */
#include<stdio.h>
main()
{
int p, n, count ;
float r, si ;
count = 1 ;
while ( count <= 3 )
{
printf ( "\n Enter values of p, n and r " ) ;
scanf ( "%d %d %f", &p, &n, &r) ;
si = p * n * r / 100 ;
printf ( "Simple interest = Rs. %f \n", si) ;
count = count + 1
}
}
For
loop:
The for loop 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) Increasing the value of loop counter each time the program segment within
the loop has been executed.
The general form of for statement is as under:
for
( initialise counter; test counter; increment counter )
{
do
this;
and this;
}
Let us write an example program to
illustrate the for loop.
/* Calculation of simple interest for 3 sets of p, n, r */
#include<stdio.h>
main ( )
{
int p, n, count ;
float r, si :
for ( count = 1 ; count <= 3 ; count = count + 1 )
{
printf ( "Enter values of p, n and r " ) ;
scanf ( "%d %d %f'", &p, &n, &r) ;
si=p*n*r/100;
printf ( "Simple Interest = Rs. %f \n", si) ;
}
}
Do-while loop:
The do-while, tests at the bottom after making each pass through the loop body,
that is, the body is always executed at least once. The syntax of the do-while
loop is :
do{
Statement
}while (expression);
Nesting of loops:
Control statements (if, switch, etc) can be nested just like iteration
statements (for, while). For example, for within
a for loop, while within a while
loop, etc. Also, you can nest a for loop in a
while loop, or while within a do-while or for loop.
Break and Continue:
It is sometimes convenient to be able to exit from a loop other than by testing
a condition at the top or bottom of the loop. The break
statement provides an early exit from for, while, and do loops, just as
from switch. A break causes the innermost enclosing loop or switch to be exited
immediately.
The continue statement is related to break, but less often used. It causes the
next iteration of the enclosing for, while or do loop to begin. In the while and
do, this means that the test part is executed immediately. In
the for, control passes to the increment step.
The continue inside a switch can cause
the next loop iteration.
Go to:
A goto statement is used to cause program control to end up almost anywhere in
the program.
Exit( ) function:
exit( ) is a standard library function that comes ready made with the C
compiler. Its purpose is to terminate the execution of the program. Its work is
quite different from break. Break just terminates the execution of a
block (like loop or switch case), whereas exit(
) terminates the execution of the program itself.
An example for goto and exit ( ) :
#include<stdio.h>
main( )
{
int goals;
printf ( "Enter the number of goals scored against India" ) ;
scanf ( "%d", &goals) ;
if ( goals <= 5 )
goto sos ;
else
{
printf
( "About time soccer players learnt C \n" ) ;
printf ( "and said goodbye! adieu!
to soccer") ;
exit( ) ; /* terminates program execution */
}
sos:
printf ( "To err is human!" ) ;
}
HOME
<<PREVIOUS
NEXT>> |