Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are different variations of for loop iterations?
The for loop in C offers several variations beyond its standard form, making it a versatile control structure. Each variation serves specific programming needs, from multiple variable initialization to infinite loops.
Syntax
for (initialization; condition; increment/decrement) {
// statements
}
The basic components are −
- Initialization − Sets the initial value of loop control variable(s)
- Condition − Tests whether to continue the loop execution
- Operation − Updates the loop variable after each iteration
Variation 1: Multiple Variable Initialization
The comma operator allows initializing multiple variables in a single for loop −
#include <stdio.h>
int main() {
int x, y;
for(x = 0, y = 10; x < y; x++, y--) {
printf("x = %d, y = %d
", x, y);
}
return 0;
}
x = 0, y = 10 x = 1, y = 9 x = 2, y = 8 x = 3, y = 7 x = 4, y = 6
Variation 2: Missing Loop Components
Any part of the for loop can be omitted. Here's an example with missing increment −
#include <stdio.h>
int main() {
int x = 0;
for(; x < 5; ) {
printf("x = %d
", x);
x += 2; /* increment inside loop body */
}
return 0;
}
x = 0 x = 2 x = 4
Variation 3: Infinite Loop
When all components are omitted, it creates an infinite loop that requires a break statement to exit −
#include <stdio.h>
int main() {
int count = 0;
for(;;) {
printf("Iteration %d
", count);
count++;
if(count == 3) {
printf("Breaking out of loop
");
break;
}
}
return 0;
}
Iteration 0 Iteration 1 Iteration 2 Breaking out of loop
Variation 4: Empty Loop Body
The loop body can be empty, useful for operations performed entirely in the for statement −
#include <stdio.h>
#include <string.h>
int main() {
char str[] = " Hello World";
char *ptr = str;
printf("Original string: '%s'
", str);
/* Remove leading spaces using empty loop body */
for(; *ptr == ' '; ptr++);
printf("After removing spaces: '%s'
", ptr);
return 0;
}
Original string: ' Hello World' After removing spaces: 'Hello World'
Conclusion
These for loop variations provide flexibility in C programming. Whether using multiple variables, omitting components, or creating empty bodies, each variation serves specific use cases that can make code more efficient and readable.
