C++ for loop


Introduction

The for loop in C++ is one of the most commonly used control flow statements, used to repeat a block of code a specific number of times. It is particularly useful when you know in advance how many times you want to execute a statement or a block of statements.

A for loop is often used to iterate over arrays, vectors, and ranges, or to perform repetitive tasks that require a specific number of iterations.

In this blog post, we'll cover:

  • The basic syntax of the C++ for loop.
  • A detailed explanation of the components of the loop.
  • Practical examples showing how to use the for loop.

1. Basic Syntax of the C++ for Loop

The for loop is made up of three parts:

  1. Initialization: Set up a variable for the loop.
  2. Condition: Define the condition to continue the loop.
  3. Increment/Decrement: Update the loop variable after each iteration.

Syntax:

for (initialization; condition; increment/decrement) {
    // Code to execute
}
  • Initialization: This part is executed once before the loop starts. It's usually where you declare and initialize the loop control variable.
  • Condition: This part is checked before each iteration. If it's true, the loop continues; if it's false, the loop stops.
  • Increment/Decrement: This part is executed after each iteration. It updates the loop control variable (typically increments or decrements it).

2. Example 1: Basic for Loop

Let's start with a simple example where we print the numbers from 1 to 5 using a for loop.

#include <iostream>
using namespace std;

int main() {
    // Print numbers from 1 to 5
    for (int i = 1; i <= 5; i++) {
        cout << "Number: " << i << endl;
    }

    return 0;
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Explanation:

  • Initialization: int i = 1 initializes the loop control variable i to 1.
  • Condition: i <= 5 means the loop will continue as long as i is less than or equal to 5.
  • Increment: i++ increments the value of i by 1 after each iteration.

3. Example 2: for Loop with Decrement

You can also use the for loop to count backward. Here's an example that prints numbers from 10 down to 1.

#include <iostream>
using namespace std;

int main() {
    // Print numbers from 10 to 1
    for (int i = 10; i >= 1; i--) {
        cout << "Number: " << i << endl;
    }

    return 0;
}

Output:

Number: 10
Number: 9
Number: 8
Number: 7
Number: 6
Number: 5
Number: 4
Number: 3
Number: 2
Number: 1

Explanation:

  • Initialization: int i = 10 sets the loop control variable i to 10.
  • Condition: i >= 1 keeps the loop running until i is greater than or equal to 1.
  • Decrement: i-- decreases the value of i by 1 after each iteration.

4. Example 3: for Loop with Multiple Statements

You can also execute multiple statements in the loop by placing them inside curly braces {}. Here's an example that prints the squares of numbers from 1 to 5.

#include <iostream>
using namespace std;

int main() {
    // Print squares of numbers from 1 to 5
    for (int i = 1; i <= 5; i++) {
        int square = i * i;  // Calculate square
        cout << "Number: " << i << ", Square: " << square << endl;
    }

    return 0;
}

Output:

Number: 1, Square: 1
Number: 2, Square: 4
Number: 3, Square: 9
Number: 4, Square: 16
Number: 5, Square: 25

Explanation:

  • The loop initializes i to 1 and runs until i is 5.
  • For each iteration, it calculates the square of i and prints it.

5. Example 4: Nested for Loop

A nested for loop is a loop inside another loop. Nested loops are commonly used for working with multi-dimensional arrays or performing operations with more than one variable.

Syntax:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        // Inner loop code
    }
}

Example: Printing a Multiplication Table

#include <iostream>
using namespace std;

int main() {
    // Print multiplication table from 1 to 5
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            cout << i * j << "\t";  // Print product
        }
        cout << endl;  // Move to the next line after each row
    }

    return 0;
}

Output:

1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25	

Explanation:

  • The outer loop runs 5 times, with i ranging from 1 to 5.
  • For each iteration of the outer loop, the inner loop runs 5 times, with j ranging from 1 to 5.
  • The product of i and j is printed for each combination.

6. Example 5: for Loop with a Break Statement

The break statement can be used inside a loop to terminate the loop early when a certain condition is met.

Example: Finding the First Even Number Greater Than 10
#include <iostream>
using namespace std;

int main() {
    // Find the first even number greater than 10
    for (int i = 1; i <= 20; i++) {
        if (i > 10 && i % 2 == 0) {
            cout << "The first even number greater than 10 is: " << i << endl;
            break;  // Exit the loop
        }
    }

    return 0;
}

Output:

The first even number greater than 10 is: 12

Explanation:

  • The loop runs from 1 to 20, and when it encounters an even number greater than 10, it prints it and exits the loop using the break statement.

7. Example 6: for Loop with a Continue Statement

The continue statement can be used to skip the current iteration of a loop and move to the next iteration.

Example: Skipping Odd Numbers
#include <iostream>
using namespace std;

int main() {
    // Print only even numbers between 1 and 10
    for (int i = 1; i <= 10; i++) {
        if (i % 2 != 0) {
            continue;  // Skip the odd numbers
        }
        cout << "Even number: " << i << endl;
    }

    return 0;
}

Output:

Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10

Explanation:

  • The continue statement skips the odd numbers, so only even numbers are printed.