Learn C++ For Loop from Scratch: From Syntax to Examples

In programming, we often need to repeatedly execute a segment of code. For example, to print the numbers from 1 to 10, without using a loop, you would have to write 10 cout statements, which is obviously cumbersome. However, C++’s for loop can easily help us solve such repetitive tasks.

1. Why Use a for Loop?

A for loop is the most common tool when you need to execute a block of code a fixed number of times. Examples include:
- Printing all numbers from 1 to 100;
- Calculating the sum of numbers from 1 to 100;
- Iterating through each element of an array.

Manually repeating code is time-consuming and error-prone. A for loop allows you to complete a large amount of repetitive work with just a few lines of code.

2. Basic Syntax of a for Loop

The for loop has a straightforward format, consisting of three core parts separated by semicolons:

for(Initialization; Loop Condition; Update Loop Variable) {
    // Loop Body: Code to be executed repeatedly
}

Explanation of Each Part:

  • Initialization: Typically assigns an initial value to the loop variable (e.g., int i = 1), executed only once at the start of the loop.
  • Loop Condition: A boolean expression (evaluates to true or false). The loop body runs only if the condition is true.
  • Update Loop Variable: Adjusts the loop variable after each iteration (e.g., i++ increments i by 1).

3. Learning from Simple Examples

Example 1: Print Numbers from 1 to 10

#include <iostream>
using namespace std;

int main() {
    // Initialize i=1, condition i<=10, increment i each time
    for(int i = 1; i <= 10; i++) {
        cout << "Current number: " << i << endl; // Loop body: print i
    }
    return 0;
}

Execution Process:
- Initially, i=1, condition 1<=10 is true, so print 1;
- Execute i++ to make i=2;
- Repeat until i=11 (condition 11<=10 is false), then the loop ends.

Output:

Current number: 1
Current number: 2
...
Current number: 10

Example 2: Calculate the Sum from 1 to 10

Use a variable sum to accumulate the result, initialized to 0:

#include <iostream>
using namespace std;

int main() {
    int sum = 0; // Accumulator, initialized to 0
    for(int i = 1; i <= 10; i++) {
        sum = sum + i; // Add current i to sum each iteration
    }
    cout << "Sum from 1 to 10: " << sum << endl; // Output: 55
    return 0;
}

Execution Process:
- sum starts at 0, i starts at 1;
- The loop runs 10 times, with sum += i each time, resulting in sum = 0+1+2+...+10 = 55.

4. Common for Loop Styles

1. Omitting Some Conditions

  • Omit Initialization: If the loop variable is already defined, the initialization part can be omitted (not recommended for beginners):
  int i = 1;
  for(; i <= 10; i++) { // Omit initialization
      cout << i << endl;
  }
  • Omit Update: If the condition includes the update logic, the update part can be omitted (but manually update i to avoid infinite loops):
  for(int i = 1; i <= 10; ) { // Omit update part
      cout << i << endl;
      i++; // Manually update i
  }

2. Single-Line Loop Body

If the loop body has only one statement, braces {} can be omitted. However, always use braces to avoid logical errors:

for(int i = 1; i <= 3; i++) {
    cout << i; // Single line, braces optional but recommended
}
// Or (less readable):
for(int i = 1; i <= 3; i++) cout << i;

5. Advanced Example: Print the Multiplication Table

for loops support nesting (a loop inside another loop). A classic example is the 9×9 multiplication table:

#include <iostream>
using namespace std;

int main() {
    for(int i = 1; i <= 9; i++) { // Outer loop controls rows
        for(int j = 1; j <= i; j++) { // Inner loop controls columns
            cout << j << "×" << i << "=" << j*i << "\t"; // Print product
        }
        cout << endl; // New line after each row
    }
    return 0;
}

Output:

1×1=1   
1×2=2   2×2=4   
1×3=3   2×3=6   3×3=9   
... (subsequent rows omitted)

6. Common Errors and Precautions

  1. Infinite Loop: The condition is always true, causing the loop to never terminate.
    Example: for(int i=1; i<10; i--) (i decreases, so i<10 is always true).
  2. Loop Variable Scope: Variables defined inside the for loop (e.g., int i) are only accessible within the loop:
   for(int i=1; i<=3; i++) { /* i is accessible here */ }
   cout << i; // Error: i is undefined outside the loop
  1. Reversed Condition: For example, writing i < 10 as i > 10 causes the loop to execute zero times.

7. Summary

The for loop is a core tool in C++ for handling fixed-number repetitive tasks. It works by:
- Initializing a loop variable;
- Checking a condition;
- Updating the variable after each iteration.

Key takeaways:
- Understand the roles of the three components;
- Practice simple examples (e.g., summation, printing sequences);
- Avoid infinite loops and scope issues.

By practicing scenarios like factorial calculation or array traversal, you’ll master for loop usage!

Xiaoye