C++ For Loop


What Is a For Loop in C++?

In C++, a for loop is one of the most commonly used looping structures. It is perfect when you know in advance how many times a block of code should repeat.

The for loop simplifies repetition by grouping initialization, condition, and update in a single line, making your code neat and easy to understand.

Syntax of the For Loop

The general syntax looks like this:

for (initialization; condition; update) {
    // code to be executed
}

Explanation:

  1. Initialization: Runs once at the start. It sets up the loop control variable.

  2. Condition: Checked before each iteration. The loop continues if this is true.

  3. Update: Executes after every iteration, usually modifying the loop variable.

Example: Basic For Loop in C++

#include <iostream>
using namespace std;

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

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Here, i starts at 1, increases by 1 each time, and stops after reaching 5.

Step-by-Step Working of a For Loop

Let’s break it down:

  1. Initializationint i = 1 runs once before the loop starts.

  2. Condition checki <= 5 is evaluated; if true, the loop body runs.

  3. Execution – The statements inside the loop are executed.

  4. Updatei++ increases i by 1.

  5. Repeat – Steps 2–4 continue until the condition becomes false.

Example: Printing Even Numbers

#include <iostream>
using namespace std;

int main() {
    for (int num = 2; num <= 20; num += 2) {
        cout << num << " ";
    }
    return 0;
}

Output:

2 4 6 8 10 12 14 16 18 20

This loop prints even numbers by increasing the variable by 2 each time.

Using For Loop to Calculate Sum

#include <iostream>
using namespace std;

int main() {
    int sum = 0;

    for (int i = 1; i <= 10; i++) {
        sum += i;
    }

    cout << "Sum of first 10 numbers: " << sum;
    return 0;
}

Output:

Sum of first 10 numbers: 55

For loops are ideal for cumulative calculations like totals, averages, and sums.

Example: Factorial Using For Loop

#include <iostream>
using namespace std;

int main() {
    int n = 5, fact = 1;

    for (int i = 1; i <= n; i++) {
        fact *= i;
    }

    cout << "Factorial of " << n << " is " << fact;
    return 0;
}

Output:

Factorial of 5 is 120

The For Loop with Multiple Variables

You can use more than one variable in a for loop by separating them with commas.

Example:

#include <iostream>
using namespace std;

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

Output:

i = 1, j = 5
i = 2, j = 4
i = 3, j = 3
i = 4, j = 2
i = 5, j = 1

Both variables change during each iteration independently.

Using For Loop with Conditional Logic

You can combine conditions or use if statements inside a loop for more control.

Example: Print Odd Numbers

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i % 2 != 0)
            cout << i << " ";
    }
    return 0;
}

Output:

1 3 5 7 9

Nested For Loops in C++

A nested for loop means one for loop inside another.
It’s commonly used for working with tables, matrices, and patterns.

Example: Multiplication Table

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            cout << i * j << " ";
        }
        cout << endl;
    }
    return 0;
}

Output:

1 2 3
2 4 6
3 6 9

Nested loops are very useful but should be used carefully since they increase program complexity.

Infinite For Loop

A for loop can become infinite if the condition is always true or missing.

Example:

for (;;) {
    cout << "This will run forever!";
}

Here, there is no initialization, condition, or update.
To stop such a loop, you’ll need to manually terminate the program or include a break statement.

For Loop with Break and Continue

  • break: Immediately exits the loop.

  • continue: Skips the current iteration and moves to the next one.

Example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5)
            continue;
        if (i == 9)
            break;
        cout << i << " ";
    }
    return 0;
}

Output:

1 2 3 4 6 7 8

Here, i = 5 is skipped, and the loop stops when i = 9.

Using For Loop for Arrays

For loops are the most common way to process array elements.

Example:

#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    for (int i = 0; i < 5; i++) {
        cout << "Element " << i << ": " << numbers[i] << endl;
    }
    return 0;
}

Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

Summary of C++ For Loop

The for loop in C++ is used for executing a block of code multiple times with controlled initialization, condition, and update.
It’s best suited for tasks with a fixed number of iterations, such as counting, generating sequences, or iterating through arrays.

Key points to remember:

  • For loops combine all control elements in one line.

  • Use nested loops for multidimensional data.

  • Avoid infinite loops by ensuring the condition becomes false eventually.


Practice Questions

  1. Write a C++ program to print all numbers from 1 to 100 using a for loop.

  2. Write a program that prints the square of each number from 1 to 10 using a for loop.

  3. Write a C++ program to display all even numbers between 1 and 50 using a for loop.

  4. Create a program to find the sum of all odd numbers between 1 and 100 using a for loop.

  5. Write a C++ program to display the multiplication table of a number entered by the user using a for loop.

  6. Write a C++ program that counts how many numbers between 1 and 200 are divisible by 9 using a for loop.

  7. Write a program that prints the factorial of a number entered by the user using a for loop.

  8. Write a C++ program that prints a right triangle pattern of stars using nested for loops.

    *
    **
    ***
    ****
    *****
    
  9. Write a program to calculate and print the average of 10 numbers entered by the user using a for loop.

  10. Write a C++ program that reverses the digits of a given number using a for loop.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top