0
0
CHow-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 syntax is for (initialization; condition; update) { /* code */ }, which runs the code while the condition is true.
📐

Syntax

The for loop has three main parts inside parentheses separated by semicolons:

  • Initialization: Sets the starting point, usually a counter variable.
  • Condition: Checked before each loop; if true, the loop runs.
  • Update: Changes the counter after each loop iteration.

The loop body inside curly braces { } contains the code to repeat.

c
for (initialization; condition; update) {
    // code to repeat
}
💻

Example

This example prints numbers from 1 to 5 using a for loop. It shows how the loop starts at 1, checks if the number is less than or equal to 5, prints it, then increases the number by 1.

c
#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}
Output
1 2 3 4 5
⚠️

Common Pitfalls

Common mistakes with for loops include:

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

Always check your loop parts carefully to avoid these errors.

c
/* Wrong: missing update causes infinite loop */
for (int i = 1; i <= 5;) {
    printf("%d\n", i);
    i++; // Must update inside loop if not in for statement
}

/* Right: update included in for statement */
for (int i = 1; i <= 5; i++) {
    printf("%d\n", i);
}
📊

Quick Reference

Remember these tips for using for loops in C:

  • Initialization runs once at the start.
  • Condition is checked before each loop; if false, loop ends.
  • Update runs after each loop iteration.
  • Use curly braces { } to group multiple statements inside the loop.
  • Keep your loop simple and clear to avoid bugs.

Key Takeaways

A for loop repeats code using initialization, condition, and update parts.
The loop runs while the condition is true and stops when it becomes false.
Always update the counter to avoid infinite loops.
Use curly braces to include multiple statements inside the loop.
Check your loop logic carefully to prevent common mistakes.