Showing posts with label for loop in c. Show all posts
Showing posts with label for loop in c. Show all posts

Thursday 17 October 2013

For Loop In C++

For Loop In C++:


The while loop discussed in our previous tutorial is a general form which can be implemented in a different form of repetitions. In this C tutorial for beginners, we are going to study second repetition structure known as for loop c. In C++, for loop is a specialized form of while loop. Its primary purpose is to simplify the writing of counter-controlled loops.
In while loop, you had to declare a counter variable and write an extra code to increment the counter in a while loop and the length continues as you increase the number of counters. But in for loop, you can do this all in just one line and that’s the reason why for loop is called a counted or indexed for loop.

Syntax:

for ( initial statement; loop condition; update statement)
      statement;



For loop in C++


in C++, for is a reserved keyword. The initial statement, loop condition and update statement enclosed in parenthesis control the body of the for loop statement.

The following are some common points regarding for loop:

  1. If the loop condition is initially false then the loop body doesn’t execute.
  2. The update statement alter the value of loop control variable which ultimately sets the loop condition to false until or unless the update statement is converging towards loop condition.
  3. C++ allows you to fractional values for loop control variables of the double type.
  4. A semicolon at the end of the for statement would make it an infinite loop
                     e.g: for ( int i=0; i<10; i++);
  5. In the for loop, if the loop condition is omitted then it is assumed to be true.
  6. If we omit all three statements in for loop then it would be legal but it would be an infinite for loop.
                    e.g: for( ; ; )
                                cout << “Hello World\n”;

Example:

for(int i=0;i<10;i++)
      cout<<i<<"  ";

this program will print numbers from 0 to 9 on console.It is a common example of c for loop.

Final words:

For loop is the most frequently used loop in programming languages.
It has been explained with detail  in this c tutorial for beginners.