Loops in C
Loops in C
PRESENTATION
LOOPS :
WHY DO WE NEED LOOPS ???
WHILE LOOP
FOR LOOP
DO-WHILE LOOP
NESTED LOOP
while(condition)
{
statement(s);
}
LOOPS => WHILE LOOP
Here, statement(s) may be a single statement or a
block of statements. The condition may be any
expression, and true is any non-zero value. The
loop iterates while the condition is true.
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
LOOPS :
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:
The syntax of a for loop in C is:
for ( init; condition; increment )
{
statement(s);
}
LOOPS => FOR LOOP
The init 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.
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
LOOPS :
DO-WHILE LOOP:
#include<stdlib.h>
int main ()
{ // Local variable declaration:
int a = 10;
// do loop execution
do
{
printf( "value of a: %d\n “ ,a);
a = a + 1;
} while( a < 20 );
getch();
}
LOOPS => DO-WHILE LOOP
When the above code is compiled and executed, it
produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
LOOPS :
NESTED LOOPS :
Syntax:
The syntax for a nested for loop statement in C is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
// you can put more statements.
}
LOOPS => NESTED LOOP
EXAMPLE :
#include<stdlib.h>
int main ()
{
int a=1,b;
while(a<=3)
{
for(b=1;b<=3;b++)
{
printf("a = %d , b = %d\n",a,b);
}
printf("\n");
a++;
}
system("pause");
}
LOOPS => NESTED LOOP
When the above code is compiled and executed, it
produces the following result:
a=1,b=1
a=1,b=2
a=1,b=3
a=2,b=1
a=2,b=2
a=2,b=3
a=3,b=1
a=3,b=2
a=3,b=3