For Loop in C
The for loop in C is used to execute a block of code repeatedly for a known number of times. It is commonly used when the number of iterations is predetermined.
Syntax
for (initialization; condition; increment/decrement) { // Code to be executed repeatedly }
Example
for (int i = 1; i <= 5; i++) { printf("%d\n", i); } // Output: 1 2 3 4 5
How It Works
- Initialization happens once at the beginning (e.g., int i = 1).
- The condition is checked before every iteration; if true, the loop executes, if false, it terminates.
- The increment/decrement step executes after each iteration.
- The loop repeats until the condition becomes false.
Tips
- Use for loops when the number of iterations is known in advance.
- Keep loop body simple to avoid complexity.
- Avoid modifying the loop counter inside the loop body unless intentional.
- Use proper indentation to visualize the loop clearly.
Common Mistakes
- Forgetting to increment/decrement the loop variable, causing an infinite loop.
- Using the wrong condition, leading to zero iterations or infinite loops.
- Declaring the loop variable outside when not needed or inside when it should be reused.
- Modifying the loop variable inside the loop body unexpectedly, causing incorrect results.
Codecrown