For loop in c++/c/cpp

For loop in c++/c/cpp

1 min read

It is the iterative statement, through which we can execute a set of instructions repeatedly.

Syntax:-

 
 for(initialization expression(s); test-expression;update-expression)
 {
  //Body of loop;
 }    

Let’s understand all terms one by one:

  • Initialization expression(s): It initialize the loops control variable. It tells the compiler about the number of times the loop should work. It is executed once, at the beginning of loop.
  • Test expression(s): It is basically a condition whose truth value decides whether the loop body will execute in the next turn or not. If its value is true, the loop will continue, otherwise, it is terminated.
  • Update expression(s): It changes the value of the loops variable.
  • Body of the loop: the statements that you want to execute repeatedly are placed in this.If text-expression is evaluated to be true body-of-loop is executed, else the loop is terminated.

Example:

//program to print numbers from 1 to 10
int main()
{
 int I;
 for(i=0;i<=10;++i)         //no semicolon is needed here
 cout<<i<<"\n";
 return 0;
}

OUTPUT

1
2
3
4
5
6
7
8
9
10

EXPLANATION:

  1. Firstly initialization expression is evaluated(i=1) which gives initial value to the variable i.
  2. Then test expression is evaluated (i<=10) which results into true I.e, (1<10).
  3. Since test expression is true body is executed(cout<<i)which prints 1 to the screen.
  4. Then update takes place(++i) i is incremented, now the value of i becomes 2, which further goes to test expression and evaluate the condition(2<10) true, body will be executed.
  5. Loop continues in this way,till the(i<=10) is true. At (i=11), condition is false and loop terminates.
Tags:
Choose your Reaction!
Leave a Comment