Lesson 28 of 60 – for Loop in C++
47%

for Loop in C++

The for loop is used to repeat a block of code multiple times. It is especially useful when we know how many times we want to execute a block of statements.

Note: A for loop usually contains three parts: initialization, condition, and update.

1. What is a for Loop?

A for loop repeatedly executes a block of code while a specified condition remains true.

for (initialization; condition; update) {
    // statements
}

The loop continues until the condition becomes false.

2. Syntax of for Loop

for (initialization; condition; update) {

    // code to repeat

}

The three parts are separated by semicolons.

  • Initialization: Sets the starting value.
  • Condition: Determines whether the loop continues.
  • Update: Changes the loop variable after each iteration.

3. Simple for Loop

for (int i = 1; i <= 5; i++) {
    std::cout << i << std::endl;
}

Output:

1
2
3
4
5

4. Initialization Part

The initialization part runs once before the loop starts.

for (int i = 1; i <= 5; i++) {
    std::cout << i;
}

Here, int i = 1 initializes the loop variable with 1.

5. Condition Part

The condition is checked before each iteration.

for (int i = 1; i <= 5; i++) {
    std::cout << i;
}

The loop continues while i <= 5 is true.

6. Update Part

The update part changes the loop variable after each iteration.

for (int i = 1; i <= 5; i++) {
    std::cout << i;
}

Here, i++ increases i by 1 after every iteration.

7. How a for Loop Executes

For this loop:

for (int i = 1; i <= 3; i++) {
    std::cout << i;
}

The execution is:

  1. i is initialized to 1.
  2. The condition i <= 3 is checked.
  3. The loop body executes.
  4. i++ increases the value.
  5. The condition is checked again.
  6. The process continues until the condition becomes false.

8. Printing Numbers from 1 to 10

#include <iostream>

int main() {

    for (int i = 1; i <= 10; i++) {
        std::cout << i << std::endl;
    }

    return 0;
}

9. Printing Numbers from 10 to 1

The decrement operator can be used to count backward.

for (int i = 10; i >= 1; i--) {
    std::cout << i << std::endl;
}

The output starts from 10 and ends at 1.

10. Printing Even Numbers

for (int i = 2; i <= 20; i += 2) {
    std::cout << i << std::endl;
}

The update expression i += 2 increases the value by 2, so only even numbers are printed.

11. Printing Odd Numbers

for (int i = 1; i <= 19; i += 2) {
    std::cout << i << std::endl;
}

The loop starts from 1 and increases by 2.

12. Using i++

The i++ operator increases the loop variable by 1.

for (int i = 1; i <= 5; i++) {
    std::cout << i;
}

This is one of the most common forms of a for loop.

13. Using i--

The i-- operator decreases the loop variable by 1.

for (int i = 5; i >= 1; i--) {
    std::cout << i << std::endl;
}

14. Using i += 2

for (int i = 0; i <= 10; i += 2) {
    std::cout << i << std::endl;
}

This loop prints values with a difference of 2.

15. Sum of Numbers

int sum = 0;

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

std::cout << "Sum = " << sum;

The loop adds the numbers from 1 to 10 to the sum variable.

16. Multiplication Table

int number = 5;

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

This program prints the multiplication table of 5.

17. Taking Input for a Loop

#include <iostream>

int main() {

    int n;

    std::cout << "Enter a number: ";
    std::cin >> n;

    for (int i = 1; i <= n; i++) {
        std::cout << i << std::endl;
    }

    return 0;
}

The number of iterations depends on the value entered by the user.

18. Factorial Using for Loop

int number = 5;
int factorial = 1;

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

std::cout << "Factorial = " << factorial;

The factorial of 5 is 120.

19. Counting Characters in a String

#include <iostream>
#include <string>

int main() {

    std::string name = "SOOPRO";

    for (int i = 0; i < name.length(); i++) {
        std::cout << name[i] << std::endl;
    }

    return 0;
}

The loop accesses each character using its index.

20. for Loop with Array

int numbers[] = {10, 20, 30, 40, 50};

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

The loop uses the index to access each element of the array.

21. for Loop with if Statement

A for loop can contain an if statement.

for (int i = 1; i <= 20; i++) {

    if (i % 2 == 0) {
        std::cout << i << std::endl;
    }

}

This prints only even numbers between 1 and 20.

22. Using break in a for Loop

The break statement immediately terminates the loop.

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

    if (i == 5) {
        break;
    }

    std::cout << i << std::endl;
}

The loop stops when i becomes 5.

23. Using continue in a for Loop

The continue statement skips the current iteration and moves to the next iteration.

for (int i = 1; i <= 5; i++) {

    if (i == 3) {
        continue;
    }

    std::cout << i << std::endl;
}

The number 3 is skipped.

24. Nested for Loops

A for loop can be placed inside another for loop. This is called a nested loop.

for (int i = 1; i <= 3; i++) {

    for (int j = 1; j <= 3; j++) {
        std::cout << i << "," << j << std::endl;
    }

}

25. Printing a Pattern

for (int i = 1; i <= 5; i++) {

    for (int j = 1; j <= i; j++) {
        std::cout << "* ";
    }

    std::cout << std::endl;
}

Output:

*
* *
* * *
* * * *
* * * * *

26. Common for Loop Mistakes

  • Forgetting the semicolons between initialization, condition, and update.
  • Using the wrong loop condition.
  • Forgetting to update the loop variable.
  • Creating an infinite loop accidentally.
  • Using an incorrect starting value.
  • Using <= when < is required, or vice versa.
  • Accessing an array outside its valid index range.

Correct structure:

for (int i = 0; i < 10; i++) {
    std::cout << i;
}

27. Complete Number Analysis Program

#include <iostream>

int main() {

    int n;

    std::cout << "Enter a number: ";
    std::cin >> n;

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

        if (i % 2 == 0) {
            std::cout << i
                      << " is even"
                      << std::endl;
        }
        else {
            std::cout << i
                      << " is odd"
                      << std::endl;
        }

    }

    return 0;
}

28. Scope of Loop Variable

When a variable is declared inside the initialization part of a for loop, its scope is normally limited to the loop.

for (int i = 1; i <= 5; i++) {
    std::cout << i;
}

// i is not available here

The variable i can be used inside the loop but not after the loop.

29. Best Practices for for Loops

  • Use meaningful loop variables when appropriate.
  • Keep the loop condition simple.
  • Make sure the loop variable changes correctly.
  • Use braces to keep the loop body clear.
  • Avoid unnecessary changes to the loop variable inside the body.
  • Check array boundaries carefully.
  • Use break and continue only when they make the logic clearer.
  • Choose the correct starting and ending values.
for (int i = 1; i <= 10; i++) {
    std::cout << i << std::endl;
}

30. for Loop – Final Summary

Part Purpose
Initialization Sets the starting value of the loop variable.
Condition Determines whether another iteration should execute.
Update Changes the loop variable after each iteration.
Body Contains the statements repeated by the loop.
break Terminates the loop immediately.
continue Skips the current iteration.
for (int i = 1; i <= 10; i++) {
    std::cout << i;
}

📌 Key Points

  • The for loop repeats a block of code.
  • It is useful when the number of iterations is known or controlled by a counter.
  • A for loop contains initialization, condition, and update.
  • The condition is checked before each iteration.
  • The update runs after the loop body.
  • i++ increases the counter by one.
  • i-- decreases the counter by one.
  • break terminates the loop.
  • continue skips the current iteration.
  • For loops can be nested inside other loops.
  • For loops can be combined with if statements and arrays.

🧠 Quick Quiz

Question: Which part of a for loop changes the loop variable after each iteration?