How to Use for Loop in C++

A program in any programming language sometime requires execution of a set of statements several times depending on the needs of the program e.g. printing a message on the screen several times. All of the programming languages use a concept of loops to deal with this thing. Some of the loop types are for loop, while loop and do while loop. Each of them are used for different uses, for loop is the most simplest among all. I will describe the use of for loop in next few steps.

Instructions

  • 1


    Syntax:


    The syntax of for loop is shown below:


    for (initialize_a_variable_value; condition_to check_everytime; increment_or_decrement){


    //set of statements here to execute.


    }


    To further simplify the above syntax, let us have a look at a simple for loop example:


    for (int i=0 ; i<10 ; i++){


    Cout<


    }


    You can either initialize the variable inside for loop or you can also declare and initialize it.



  • 2


    First of all the loop will initialize the value of variable i=0 and then will check the condition, if it is true than it will execute the set of code inside braces. After that it will apply increment or decrement the variable as mentioned in the for loop. And then will again check the given condition, if it is true again same set of statements will execute. This will continue until the condition becomes false.


    In the example I have shown above, the loop will execute the code inside braces for 10 times.



  • 3


    Example:


    #include


    Using namespace std;


    int main ( ){


    int i;


    for(i=0; i<=20; i++){


    cout<<”The recent value of I is ”<


    cout<<”incrementing i now”<


    }


    return 0;


    }



Leave a Reply

Your email address will not be published. Required fields are marked *


− five = 2