0
0
Cprogramming~5 mins

For loop in C

Choose your learning style9 modes available
Introduction

A for loop helps you repeat a set of actions many times without writing the same code again and again.

When you want to count from 1 to 10 and do something each time.
When you need to process each item in a list one by one.
When you want to repeat a task a fixed number of times, like printing a message 5 times.
When you want to run a block of code while increasing or decreasing a number step by step.
Syntax
C
for (initialization; condition; update) {
    // code to repeat
}

initialization sets a starting point, like int i = 0;

condition is checked before each loop; if false, the loop stops.

Examples
This prints numbers 0 to 4, increasing i by 1 each time.
C
for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}
This counts down from 10 to 1, decreasing i by 1 each time.
C
for (int i = 10; i > 0; i--) {
    printf("%d\n", i);
}
This prints even numbers from 0 to 8 by adding 2 each time.
C
for (int i = 0; i < 10; i += 2) {
    printf("%d\n", i);
}
Sample Program

This program prints "Hello" followed by numbers 1 to 5, each on a new line.

C
#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) {
        printf("Hello %d\n", i);
    }
    return 0;
}
OutputSuccess
Important Notes

Remember the semicolons inside the for loop parentheses separate the parts.

If you forget to update the variable, the loop might run forever.

You can use any variable name, not just i.

Summary

A for loop repeats code a set number of times.

It has three parts: start, condition, and update.

Use it to count, repeat tasks, or process items step by step.