Loops are essential constructs in C programming, enabling you to execute a block of code repeatedly. In this comprehensive article, we’ll delve into loops in C: for
, while
, and do-while
. You’ll gain a deep understanding of how to use these control structures effectively with real-world examples and output demonstrations, allowing you to write efficient and flexible C programs. Loops (for, while, and do-while) are fundamental constructs in C programming, allowing you to execute code repeatedly. In this article, we’ve explored these loops with real-world examples and output demonstrations, giving you a solid foundation for writing efficient and flexible C programs.
The for
Loop
The for
loop is widely used in C for executing a block of code a specified number of times. It consists of three parts: initialization, condition, and increment/decrement.
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
The while
Loop
The while
loop repeatedly executes a block of code as long as a specified condition remains true.
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5) {
printf("Iteration %d\n", count);
count++;
}
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
The do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the code block is executed at least once before checking the condition.
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Iteration %d\n", count);
count++;
} while (count <= 5);
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Loop Control Statements
The break
Statement
The break
statement is used to exit a loop prematurely based on a certain condition.
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit the loop when i equals 6
}
printf("Iteration %d\n", i);
}
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
The continue
Statement
The continue
statement is used to skip the current iteration of a loop based on a certain condition and proceed to the next iteration.
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip iteration when i equals 3
}
printf("Iteration %d\n", i);
}
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 4
Iteration 5