Friday, November 8, 2013

Looping Statements in C

C programming language allows users to use one loop inside another loop.
Following section shows few examples to illustrate the concept.

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);
}

Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#include <stdio.h>
int main ()
{
int i, j;
for(i=2; i<100; i++) {
for(j=2; j <= (i/j); j++)
if(!(i%j)) break;
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}

Example
#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
return 0;
}

Syntax of continue:
The syntax for a continue statement in C is as follows:
Continue;

Example:
#include <stdio.h>
int main ()
{
int a = 10;
do
{
if( a == 15)
{
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}

Syntax of goto:
The syntax for a goto statement in C is as follows:
goto label;
label: statement;

Example:
#include <stdio.h>
int main ()
{
int a = 10;
LOOP:do
{
if( a == 15)
{
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}

Infinite Loop
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
#include <stdio.h>
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.

NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

No comments:

Post a Comment