Skip to main content

Command Palette

Search for a command to run...

loops in c

Published
2 min readView as Markdown

🔄 Loops in C Language

A loop in C means repeating a block of code multiple times until a condition becomes false.
It saves us from writing the same code again and again.


1. for loop

👉 Used when you know exactly how many times you want to repeat.

Syntax:

for(initialization; condition; update) {
    // code to repeat
}
  • initialization → set starting value (e.g., int i = 1)

  • condition → loop runs as long as this is true

  • update → changes the loop variable each time (e.g., i++)

Example:

#include <stdio.h>
int main() {
    for(int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}

✅ Output:

1
2
3
4
5

2. while loop

👉 Used when you don’t know how many times to repeat, and it depends only on a condition.

Syntax:

while(condition) {
    // code to repeat
}

Example:

#include <stdio.h>
int main() {
    int i = 1;
    while(i <= 5) {
        printf("%d\n", i);
        i++;
    }
    return 0;
}

✅ Output:

1
2
3
4
5

3. do-while loop

👉 Similar to while, but the body runs at least once, even if the condition is false.

Syntax:

do {
    // code to repeat
} while(condition);

Example:

#include <stdio.h>
int main() {
    int i = 1;
    do {
        printf("%d\n", i);
        i++;
    } while(i <= 5);
    return 0;
}

✅ Output:

1
2
3
4
5

🔑 Quick Difference:

  • for loop → best when number of iterations is fixed.

  • while loop → runs 0 or more times, based on condition.

  • do-while loop → runs at least once, then checks condition.

More from this blog

Amit singh's blog

235 posts