Monday, January 21, 2019

for loop in c++ programming

in this tutorial post, you will learn how to use for loop in c++ programming and what is the for loop in programming.

For loop

for loop in c++ programming, learn c++ programming
learn c++ programming

In  c++ programming for loop specifies the counter-controlled repetition details in a single line of code. 

syntax:
            for(initialization; condition; counter)
             {

                  code for execution;
             }
    
Note: for loop is the addition of while loop, both are working same. but the difference is all about the syntax. 
in for loop, we used three conditions, first we initialize the variable, second, we make the condition for the continuation of the loop, and then, at last, we increment(a++) and decrement(a--) the variable as per need and condition of the program.

Example:
            for(i=0;i<10;i++)
            {
               std::cout<<"*";
               std::cout<<endl;

            }

Program using for loop in c++:

        #include <iostream>

        int main()
        {
              int a;

              for(a=0;a<=5;a++)
              {

              std::cout<<"\nyou are learning c++";
              }
          
            return 0;
          }

Note: always place the [;] in between the condition of for loop. like for(i=0;i<5;i++).

More on for loop in c++

we can also write the for loop like this:

first:
            for( ; a<=5; a++)
            {
                  std::cout<<"\n learn c++";
            }
    
second:
             for(a=0;a<=5;)
            {
             std::cout<<"\n we are learning c++";
             }

If we use for loop like this:
     
            for(a=0; 0; a++)  
             {

               std::cout<<"\n for loop is not executed:";
             }

Note: if we place the 0 at the condition part of the for loop then the for loop is not going to execute. and if we place the non zero value like 1 or any other number. then the for loop is executed at the infinite time. 

Note: if in the body of for loop there is only one statement. then we need not use curly brackets [{ }] after the for loop. 

Example:
              for(i=0;i<5;i++)
              std::cout<<"\n there is no any curley brackets in for loop";

we can also place the two conditions in the for loop:

Example:
              for(i=0,j=0;i<=5,j<=6; i++,j++)
              {

                std::cout<<"\n there is two conditions in for loop";
              }


Note: in for loop we at the time of two conditions we separate both conditions via [,] comma sign. as you see in the above example. and the execution of for loop always depends on the second condition. likewise in the above example, the execution of for loop is depended on the [j<=6] condition.

"Please share this knowledge as much possible as you can and also comment me your queries and questions related to this topic. I will really grateful to help you."

0 comments: