for Loop of C++

03-11-17 Course- CPP

In computer programming, loop cause a certain piece of program to be executed a certain number of times. read here:

  • You want to execute some code/s certain number of time.
  • You want to execute some code/s certain number of times depending upon input from user.

These types of task can be solved in programming using loops.

There are 3 types of loops in C++ Programming:

  • for Loop
  • while Loop
  • do...while Loop

C++ for Loop Syntax


for(initialization statement; test expression; update statement) {
       code/s to be executed; 
}

How for loop works in C++ Programming?

The initialization statement is executed only once at the beginning of the for loop. Then the test expression is checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.

Flowchart of for Loop in C++

Flowchart of for loop in C++ Programming

Example 1: C++ for Loop

C++ Program to find factorial of a number (Note: Factorial of positive integer n = 1*2*3*...*n)


#include <iostream>
using namespace std;

int main() {
    int i, n, factorial = 1;

    cout<<"Enter a positive integer: ";
    cin>>n;

    for (i = 1; i <= n; ++i) {
        factorial *= i;   // factorial = factorial * i;
    }

    cout<< "Factorial of "<<n<<" = "<<factorial;
    return 0;
}

Output


Enter a positive integer: 5
Factorial of 5 = 120

In this program, user is asked to enter a positive integer which is stored in variable n (supposed user entered 5). Here is the working of for loop in this program:

Initially, i = 1, test expression is true, factorial becomes 1. Variable i is updated to 2, test expression is true, factorial becomes 2. Variable i is updated to 3, test expression is true, factorial becomes 6. Variable i is updated to 4, test expression is true, factorial becomes 24. Variable i is updated to 5, test expression is true, factorial becomes 120. Variable i is updated to 6, test expression is false, for loop is terminated.

In the above program you can see that, variable i is not used outside for loop. In such case, it is better to define variable at the time of initialization statement.


for (int i = 0; i <= n; ++i){
  ... .. ...
}

In the above C++ code, i is local to for loop, that is, you cannot use it outside for loop but makes program more readable.