Introduction to For Loops in C

Discussion in 'C' started by lionaneesh, Jul 13, 2011.

  1. lionaneesh

    lionaneesh Active Member

    Joined:
    Mar 21, 2010
    Messages:
    848
    Likes Received:
    224
    Trophy Points:
    43
    Occupation:
    Student
    Location:
    India

    For Loops



    ‘For loops’ are more concise and special kind of loops that are used to execute statements repeatedly in some programming languages including C. The For loop structure is quite different from while loops as well as do while loop structures which we had a look in previous articles.

    ‘For loops’ are usually used when we need to execute specific number of iterations i.e when number of iterations is known before entering the loop.

    It follows the following format:-

    Code:
    for(initialization ; condition ; afterEachExecution )
        {
            CodeHere;
        }
    
    The Working
    1. First the program runs the code or an assignment specified in the ‘initialization’ section.
    2. Then it checks whether the condition specified evaluates to true
    3. If ‘yes’ then the loop body is executed.
    4. Then after executing the program runs the code or an assignment specified in the ‘afterEachExecution’ section
    5. Then after executing the program again checks if the condition evaluates to true
    6. If it is true the loop body is executed
    7. This process of repeatedly execution continues until the condition evaluates to false.
    That’s much of a theory there now let the coding begin.

    Using for loops



    Now let’s create a simple C program which would basically print all the even numbers between 1 and 100.

    Code:
    #include<stdio.h>
    
    int main()
    {
        int i=1;
        for(i = 2 ; i < 100 ; i = i+2 )
        {
            printf("%d\n",i);
        }
        return(0);
    }
    
    Explanation:-
    1. First we declare a ‘int’ variable named ‘i’ . ‘i’ is used to as a loop counter and to display even numbers on the screen.
    2. In the loop initialization, we set ‘i’ to 2 (first even number).
    3. Then the program checks if the condition specified in the condition section evaluates to true.
    4. Then the program moves to loop body where we output ‘i’ (our even number) on to the screen.
    5. Then the program jumps to the ‘afterEachExecution’ where it increments ‘i’ by 2.
    6. This procedure (from step 3) continues until the condition specified in the condition section evaluates to false.
    Output:-
    Code:
    2
    4
    6
    8
    10
    12
    14
    16
    18
    20
    22
    24
    26
    ------------------------- Snipped ------------------------------
    
    That’s all for this tutorial stay tuned for more.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice