C Loops
Loops repeat a block of code as long as a condition stays true.
The while Loop
Example
c
#include <stdio.h>
int main(void) {
int i = 1;
while (i <= 3) {
printf("Round %d\n", i);
i++;
}
return 0;
}Output
Round 1 Round 2 Round 3
If the condition never becomes false, the loop runs forever. Make sure something inside the loop moves it towards the end.
The do...while Loop
do...while runs the body once before it checks the condition:
Example
c
#include <stdio.h>
int main(void) {
int pin;
do {
printf("Enter PIN: ");
scanf("%d", &pin);
} while (pin != 1234);
printf("Welcome!\n");
return 0;
}Output
Enter PIN: 1111 Enter PIN: 1234 Welcome!
This is useful for menus and input checks, where you must ask at least once.
The for Loop
A for loop keeps the start, condition and step together:
Example
text
for (start; condition; step) {
// code to repeat
}Example
c
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
printf("%d x 9 = %d\n", i, i * 9);
}
return 0;
}Output
1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45
Which Loop Should I Use?
| Loop | Best when |
|---|---|
for | You know how many times to repeat |
while | You repeat until something changes |
do...while | The body must run at least once |
break and continue
breakstops the loop immediatelycontinueskips to the next round
Example
c
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
if (i > 7) {
break; // stop after 7
}
printf("%d ", i);
}
printf("\n");
return 0;
}Output
1 3 5 7
Nested Loops
A loop inside another loop. The inner loop finishes all its rounds for each round of the outer loop:
Example
c
#include <stdio.h>
int main(void) {
for (int row = 1; row <= 3; row++) {
for (int star = 1; star <= row; star++) {
printf("*");
}
printf("\n");
}
return 0;
}Output
* ** ***
Exercise
Exercise
How many times does printf run in: for (int i = 2; i <= 10; i += 2) printf("x");
