C++ For loop


Go to main Page

For Loop in C++

In this tutorial, we are going to learn about for loops with the help of examples.

For Loop

The syntax of While Loop is:

for (initialization; condition; update) {
    // body of-loop 
}

initialization initializes variables and is executed only once.

condition if true, the body of for loop is executed.

update updates the value of initialized variables and again checks the condition.

Diagram
Example 1: Print number 1 to 5

#include <iostream>
using namespace std;

int main() {
        for (int i = 1; i <= 5; ++i) {
        cout << i << " ";
    }
    return 0;
}

Output

1 2 3 4 5


Example 2:Sum of natural numbers

#include <iostream>
using namespace std;
int main() {
    int num, sum;
    sum = 0;

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

    for (int count = 1; count <= num; ++count) {
        sum += count;
    }

    cout << "Sum = " << sum << endl;

    return 0;
}

Output

Enter a positive integer: 10
Sum = 55

Example 2:Print text 5 times

#include <iostream>
using namespace std;
int main() {
    for (int i = 1; i <= 5; ++i) {
        cout <<  "Pakistan " << endl;
    }
    return 0;
}

Output

  Pakistan
  Pakistan
  Pakistan
  Pakistan
  Pakistan