Loops

Loops are used in programming to repeat a specific block of code.

while loop

while loop will loop continuously, and infinitely, until the expression inside the
parenthesis, () becomes false. Something must change the tested variable, or the while
loop will never exit.

Syntax:

while (test)
{
statement;
}

where, test checks the condition is true or false before each loop.

If the test expression is true (nonzero), codes inside the body of while loop are executed. The test expression is evaluated again. The process goes on until the test expression is false.

When the test expression is false, the while loop is terminated.

 do…while loop

Syntax:

do{
statement;
}
while(test);

The code block (loop body) inside the curly braces is executed once.

Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false).

When the test expression is false (nonzero), the do…while loop is terminated.

for loop

A for loop executes statements a predetermined number of times. The control expression for the loop is initialized, tested and manipulated entirely within the for loop parentheses.
Each for loop has up to three expressions, which determine its operation.

Syntax:

for (initialize; control; increment or decrement)
{
statement;
}

Note that the three expressions in the for loop argument parentheses are separated with semicolons.

Nested Loop

Nested loop is nothing but one loop inside another loop.

Syntax:

for ( initialize1 ;control1; increment1 or decrement1)
{
statement1;
for ( initialize2 ;control2; increment2 or decrement2)
{
statement2;
}
}
Infinite loop

It is the loop having no terminating condition, so the loop becomes infinite.

Syntax:

1. Using for loop

for (;;)
{
statement;
}

2. Using while loop

while(1)
{
statement;
}

3. Using do…while loop

do{
statement;
} while(1);

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s