C For Loop
Introduction to For Loop
The for loop in C is a control flow statement that allows code to be executed repeatedly based on a specified condition. It's particularly useful when you know in advance how many times you want to execute a statement or a block of statements.
The for loop is often called a 'definite loop' because it typically executes a specific number of times, unlike while loops which are often 'indefinite loops'.
Syntax and Structure
A for loop has three parts—initialization, condition, and increment/decrement—executed in that order on each iteration. The semicolons are required; any of the three expressions may be omitted, but the semicolons must remain.
for (initialization; condition; increment_or_decrement) {
// code to be executed
}
How For Loop Works
1. The initialization expression is executed once
2. The condition is evaluated
3. If the condition is true, the loop body is executed
4. The increment/decrement expression is executed
5. Steps 2-4 repeat until the condition becomes false
6. Control passes to the statement following the loop
Basic Example
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\nLoop ended.\n");
return 0;
}
1 2 3 4 5 Loop ended.
Loop Control Variable
The loop control variable (often 'i', 'j', 'k') is typically:
• Initialized before the loop starts
• Tested before each iteration
• Modified at the end of each iteration
It's good practice to use meaningful variable names when appropriate, especially in nested loops or complex algorithms.
#include <stdio.h>
int main(void) {
for (int count = 10; count >= 1; count--) {
printf("%d ", count);
}
printf("\nLiftoff!\n");
return 0;
}
10 9 8 7 6 5 4 3 2 1 Liftoff!
Multiple Expressions
You can use multiple expressions in the initialization and increment/decrement sections by separating them with commas. This can be useful for managing multiple loop variables simultaneously.
Note: Only the initialization and increment/decrement fields support comma-separated expressions. The middle expression is a single condition; combine checks with logical operators (&&, ||) rather than commas.
#include <stdio.h>
int main(void) {
for (int i = 0, j = 10; i < j; i++, j--) {
printf("i=%d, j=%d\n", i, j);
}
return 0;
}
i=0, j=10 i=1, j=9 i=2, j=8 i=3, j=7 i=4, j=6
Optional Expressions
Any of the three expressions in a for loop can be omitted, but the semicolons must remain.
This flexibility allows for various loop patterns, but should be used judiciously for readability.
#include <stdio.h>
int main(void) {
int i = 0;
for (; i < 5; i++) {
printf("%d ", i);
}
printf("\n");
for (int j = 0; j < 5;) {
printf("%d ", j);
j++;
}
printf("\n");
int k = 0;
for (;;) {
printf("%d ", k);
k++;
if (k >= 3) break; // ensure termination
}
printf("\n");
return 0;
}
0 1 2 3 4 0 1 2 3 4 0 1 2
Loop Control Statements
C provides two important statements for controlling loop execution:
• break: Immediately terminates the loop
• continue: Skips the current iteration and proceeds to the next iteration
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
if (i == 3) {
continue;
}
if (i == 8) {
break;
}
printf("%d ", i);
}
printf("\nLoop ended.\n");
return 0;
}
1 2 4 5 6 7 Loop ended.
Common Patterns
For loops are commonly used for:
• Iterating through arrays
• Processing sequences of numbers
• Repeating operations a specific number of times
• Implementing various algorithms
#include <stdio.h>
int main(void) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
printf("Sum of first 10 numbers: %d\n", sum);
int factorial = 1;
for (int i = 1; i <= 5; i++) {
factorial *= i;
}
printf("Factorial of 5: %d\n", factorial);
return 0;
}
Sum of first 10 numbers: 55 Factorial of 5: 120
Best Practices
1. Use meaningful variable names for loop counters when appropriate
2. Keep loop bodies concise; consider moving complex logic to functions
3. Avoid modifying the loop counter within the loop body unless necessary
4. Use the most appropriate loop type for your specific use case
5. Be cautious with floating-point numbers as loop counters due to precision issues
6. Consider performance implications for very large loops
7. Prefer declaring the loop variable in the for header (C99+) to limit its scope to the loop