Loops (Lesson)
Loops: Repetition Control
Loops are used to repeat a block of code multiple times. This is essential for tasks like processing arrays, printing patterns, or running simulations.
8.1 The while Loop
A pre-test loop. It checks the condition before executing the block.
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
8.2 The do-while Loop
A post-test loop. It executes the block at least once before checking the condition.
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
8.3 The for Loop
The most compact loop, combining initialization, condition, and increment/decrement.
Syntax: for (init; condition; update) { ... }
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
8.4 Loop Control Statements
break
Immediately terminates the loop and jumps to the statement following the loop.
for (int i = 1; i <= 10; i++) {
if (i == 5) break; // Stops at 5
printf("%d ", i);
}
continue
Skips the rest of the current iteration and jumps to the next update/condition check.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // Skips printing 3
printf("%d ", i);
}
8.5 Nested Loops
Placing one loop inside another. Commonly used for multi-dimensional data or patterns.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("* ");
}
printf("\n");
}
Example: Factorial Calculation
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
if (n < 0)
printf("Error! Negative numbers don't have factorials.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}
Refer to the Lecture Slides for a comparison between while and for loops.