Welcome to our deep dive into C Loop Control Structures! Let's embark on this exciting journey together, learning one of the most fundamental aspects of C programming. This guide is designed for both beginners and intermediates, so let's get started!
In C programming, loop control structures allow you to repeatedly execute a block of code. They are essential for writing efficient and practical programs.
while, do-while, and for š”C offers three main types of loops: while, do-while, and for. Let's explore each one!
while LoopA while loop checks the condition at the top of the loop and executes the loop body if the condition is true.
while (condition) {
// code to be executed
}š” Pro Tip: Make sure the condition eventually becomes false to avoid an infinite loop.
do-while LoopA do-while loop is similar to the while loop, but the loop body is executed at least once before checking the condition.
do {
// code to be executed
} while (condition);for LoopThe for loop is a convenient way to execute a loop for a specific number of iterations.
for (initialization; condition; increment/decrement) {
// code to be executed
}initialization: used to initialize the control variable (usually an integer)condition: checks if the control variable meets the condition to continue the loopincrement/decrement: increases or decreases the control variable by a specific amount after each iterationLet's see some practical examples of these loop structures!
while Loop#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("Iteration %d\n", i);
i++;
}
return 0;
}Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8
Iteration 9
Iteration 10
do-while Loop#include <stdio.h>
int main() {
int i = 1;
do {
printf("Iteration %d\n", i);
i++;
} while (i <= 10 && i % 2 != 0); // prints even numbers only
return 0;
}Output:
Iteration 2
Iteration 4
Iteration 6
Iteration 8
for Loop#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("Iteration %d\n", i);
}
return 0;
}Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteraction 7
Iteraction 8
Iteraction 9
Iteraction 10
:::quiz Question: What is the output of the following code?
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("Iteration %d\n", i);
i += 2; // increment by 2 instead of 1
}
return 0;
}A: Iteration 1, Iteration 3, Iteration 5, Iteration 7, Iteration 9 B: Iteration 1, Iteration 3, Iteration 5, Iteration 7, Iteration 9, Iteration 11 C: Iteration 1, Iteration 3, Iteration 5
Correct: A
Explanation: The loop increments i by 2, so it stops at 9.