Loops in C-Programming



Loops In C Language

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:
Loop Architecture
C programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.
Loop TypeDescription
while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
do...while loopLike a while statement, except that it tests the condition at the end of the loop body
nested loopsYou can use one or more loop inside any another while, for or do..while loop.


FOR - 

for loops are the most useful type. The syntax for a for loop is 


for ( variable initialization; condition; variable update )

 {

  Code to execute while the condition is true;

}

The variable initialization allows you to either declare a variable and give it a value or give a value to an already existing variable. Second, the condition tells the program that while the conditional expression is true the loop should continue to repeat itself. The variable update section is the easiest way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10, or even x = random ( 5 ), and if you really wanted to, you could call other functions that do nothing to the variable but still have a useful effect on the code. Notice that a semicolon separates each of these sections, that is important. Also note that every single one of the sections may be empty, though the semicolons still have to be there. If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it. 


Example:

#include <stdio.h>


int main()

{

    int x;

    /* The loop goes while x < 10, and x increases by one every loop*/

    for ( x = 0; x < 10; x++ ) {

        /* Keep in mind that the loop condition checks 

           the conditional statement before it loops again.

           consequently, when x equals 10 the loop breaks.

           x is updated before the condition is checked. */   

        printf( "%d\n", x );

    }

    getchar();

}

This program is a very simple example of a for loop. x is set to zero, while x is less than 10 it calls printf to display the value of the variable x, and it adds 1 to x until the condition is met. Keep in mind also that the variable is incremented after the code in the loop is run for the first time. 


WHILE - 

WHILE loops are very simple. The basic structure is 


while ( condition ) 

Code to execute while the condition is true ;p

The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is like a stripped-down version of a for loop-- it has no initialization or update section. However, an empty condition is not legal for a while loop as it is with a for loop. 


Example:

#include <stdio.h>


int main()

  int x = 0;  /* Don't forget to declare variables */

  

  while ( x < 10 ) { /* While x is less than 10 */

      printf( "%d\n", x );

      x++;             /* Update x so the condition can be met eventually */

  }

  getchar();

}

This was another simple example, but it is longer than the above FOR loop. The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block. 


DO..WHILE - 

DO..WHILE loops are useful for things that want to loop at least once. The structure is

do

 {

Code to execute while the condition is true;

} while ( condition );

Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is almost the same as a while loop except that the loop body is guaranteed to execute at least once. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and then continue to loop while the condition is true". 


Example:

#include <stdio.h>


int main()

{

  int x;


  x = 0;

  do {

    /* "Hello, world!" is printed at least one time

      even though the condition is false */

      printf( "Hello, world!\n" );

  } while ( x != 0 );

  getchar();

}

Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition.



Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements. Click the following links to check their detail.
Control StatementDescription
break statementTerminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
goto statementTransfers control to the labeled statement. Though it is not advised to use goto statement in your program.

The 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