0
0
CppHow-ToBeginner · 3 min read

How to Use For Loop in C++: Syntax and Examples

In C++, a for loop repeats a block of code a set number of times using three parts: initialization, condition, and update. The loop runs while the condition is true, updating the variable each time. Use for (initialization; condition; update) { /* code */ } to write a for loop.
📐

Syntax

The for loop in C++ has three main parts inside parentheses, separated by semicolons:

  • Initialization: Sets the starting point, usually a variable like int i = 0.
  • Condition: The loop runs as long as this is true, e.g., i < 5.
  • Update: Changes the variable each time, often i++ to add one.

The code inside the curly braces { } runs each time the condition is true.

cpp
for (int i = 0; i < 5; i++) {
    // code to repeat
}
💻

Example

This example prints numbers from 0 to 4 using a for loop. It shows how the loop runs 5 times, increasing i by 1 each time.

cpp
#include <iostream>

int main() {
    for (int i = 0; i < 5; i++) {
        std::cout << i << std::endl;
    }
    return 0;
}
Output
0 1 2 3 4
⚠️

Common Pitfalls

Common mistakes when using for loops include:

  • Forgetting to update the loop variable, causing an infinite loop.
  • Using the wrong condition, so the loop never runs or runs too many times.
  • Declaring the loop variable outside the loop and accidentally changing it inside the loop.

Always check your loop's start, end, and update steps carefully.

cpp
/* Wrong: missing update causes infinite loop */
for (int i = 0; i < 5;) {
    std::cout << i << std::endl;
    i++; // Must update inside loop if not in for statement
}

/* Right: update included in for statement */
for (int i = 0; i < 5; i++) {
    std::cout << i << std::endl;
}
📊

Quick Reference

PartDescriptionExample
InitializationSet starting valueint i = 0
ConditionLoop runs while truei < 5
UpdateChange variable each loopi++
BodyCode to repeatstd::cout << i << std::endl;

Key Takeaways

Use for (init; condition; update) to repeat code a set number of times.
The loop runs while the condition is true and updates the variable each time.
Always include an update step to avoid infinite loops.
Check your loop condition carefully to control how many times it runs.
Declare the loop variable inside the for statement for better scope control.