Sunday, June 26, 2011

How Use Loops in C-'FOR' Loops

0 comments

Loops are used to repeat a block of code.Loops are one of the most basic but useful task in programming.We can simply produce extremely complex out put using loops.A loops let you write a very simple statement to produce a significantly greater result  simply by repetition.


FOR LOOPS:


FOR loops are the most useful one.The syntax of FOR loops:
for(variable initialization; condition; variable update)
{
code to execute while the condition is true
}
Example:


To print numbers upto 10:
#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();
}


The variable initialization allows you to either declare a variable and give it a value or give it a value to already existing variable.The condition tells the program that while the conditional expression is true the loop should continue to repeat it self.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(3).Notice that a semicolon separates each of these sections. Also note that every single one of the sections may be empty,though the semicolon still have to be there


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 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


<<Prev Home Next>>



Leave a Reply