Lecture 8(Control Statements)
Lecture 8(Control Statements)
Control statements enable us to specify the flow of program control; ie, the order
in which the instructions in a program must be executed. They make it possible to
make decisions, to perform tasks repeatedly or to jump from one section of code
to another.
Control statements are used in two ways as branching (conditional operators-if,
else if, nested –if-else etc.) and looping
There are 3 types of loops as follows:
FOR, WHILE and Do-While
What is Loop?
Loops provide a way to repeat commands and control how many times they are
repeated. C provides a number of looping way
while loop
The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an
If statement, if the test condition is true: the statments get executed. The difference is that after the
statements have been executed, the test condition is checked again. If it is still true the statements
get executed again.This cycle repeats until the test condition evaluates to false.
Basic syntax of while loop is as follows:
while ( expression )
{
Single statement
or
Block of statements;
}
Example: print 10 natural numbers from 1 to 10
#include <stdio.h>
main()
{
int i = 1;
while ( i <=1 0 )
{
printf("Hello %d\n", i );
i = i +1;
}
}
Output:
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10
for loop
for loop is similar to while, it's just written differently. for statements are often used to proccess lists
such a range of numbers:
Basic syntax of for loop is as follows:
for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}
#include <stdio.h>
main()
{
int i;
int j = 10;
for( i = 0; i <= j; i ++ )
{
printf("Hello %d\n", i );
}
}
Output:
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10
do...while loop
do ... while is just like a while loop except that the test condition is checked at the
end of the loop rather than the start. This has the effect that the content of the loop
are always executed at least once.
Basic syntax of do...while loop is as follows:
do
{
Single statement
or
Block of statements;
}while(expression);
Example: Example: print 10 natural numbers from 1 to 10
#include <stdio.h>
main()
{
int i = 10;
do{
printf("Hello %d\n", i );
i = i -1;
}
while ( i > 0 );
}
Output:
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10