C++ For Loop

Welcome to The Coding College! In this tutorial, we’ll dive into the for loop in C++—a structured, powerful tool for iterating through tasks efficiently.

What is a For Loop?

A for loop is a control structure that allows you to repeat a block of code a specific number of times. It is often used when the number of iterations is known beforehand.

Syntax

for (initialization; condition; increment/decrement) {
    // Code to execute
}

Key Components:

  1. Initialization: Sets the loop control variable.
  2. Condition: Checks if the loop should continue running.
  3. Increment/Decrement: Modifies the loop control variable at the end of each iteration.

Example 1: Simple For Loop

Print numbers from 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 First N Numbers

Calculate the sum of the first N natural numbers.

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0;

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

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

    cout << "The sum of the first " << n << " numbers is: " << sum << endl;

    return 0;
}

Output:

Enter a positive integer: 5  
The sum of the first 5 numbers is: 15

Example 3: Print Multiplication Table

Generate the multiplication table for a given number.

#include <iostream>
using namespace std;

int main() {
    int num;

    cout << "Enter a number: ";
    cin >> num;

    for (int i = 1; i <= 10; i++) {
        cout << num << " x " << i << " = " << num * i << endl;
    }

    return 0;
}

Output:

Enter a number: 3  
3 x 1 = 3  
3 x 2 = 6  
...  
3 x 10 = 30

Example 4: Factorial Using For Loop

Calculate the factorial of a number.

#include <iostream>
using namespace std;

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

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

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

    cout << "The factorial of " << n << " is: " << factorial << endl;

    return 0;
}

Output:

Enter a positive integer: 5  
The factorial of 5 is: 120

Example 5: Reverse Loop

Print numbers from 10 to 1 in reverse order.

#include <iostream>
using namespace std;

int main() {
    for (int i = 10; i >= 1; i--) {
        cout << i << " ";
    }
    return 0;
}

Output:

10 9 8 7 6 5 4 3 2 1

Example 6: Nested For Loop

Print a multiplication table from 1 to 5.

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 10; j++) {
            cout << i << " x " << j << " = " << i * j << endl;
        }
        cout << endl;  // Add a blank line between tables
    }
    return 0;
}

Output:

1 x 1 = 1  
1 x 2 = 2  
...  
1 x 10 = 10  

2 x 1 = 2  
2 x 2 = 4  
...  
2 x 10 = 20  
...

Example 7: Infinite For Loop

An infinite loop occurs when the condition always evaluates to true.

#include <iostream>
using namespace std;

int main() {
    for (;;) {  // No condition means infinite loop
        cout << "This is an infinite loop!" << endl;
    }
    return 0;
}

Note: Use break to exit infinite loops when needed.

Example 8: For Loop with Multiple Variables

Use two variables in a single for loop.

#include <iostream>
using namespace std;

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

Output:

i = 1, j = 10  
i = 2, j = 9  
...  
i = 10, j = 1

Best Practices for Using For Loops

  1. Clear Initialization: Ensure the loop control variable is initialized correctly.
  2. Termination Condition: Double-check that the loop condition allows for proper termination.
  3. Increment/Decrement: Use meaningful updates to avoid infinite loops.
  4. Avoid Hardcoding: Use variables instead of fixed numbers when possible, making your code reusable.

When to Use a For Loop

Use a for loop when:

  • The number of iterations is known beforehand.
  • You need a compact, structured way to iterate.

Explore More at The Coding College

Visit The Coding College for hands-on tutorials and coding resources. Master the fundamentals of C++ and beyond!

What’s Next?

  • Learn about the while loop for conditional iteration.
  • Discover the do/while loop, which guarantees at least one execution.
  • Explore how loops interact with arrays and functions for advanced programming tasks.

Leave a Comment