C Loops
for repeats a known number of times, while repeats while a condition is true, and do...while runs at least once.
ExampleC
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 3; i++) {
printf("for %d\n", i);
}
int n = 3;
while (n > 0) {
printf("while %d\n", n);
n--;
}
int k = 10;
do {
printf("do-while runs once: %d\n", k);
} while (k < 5);
for (int i = 0; i < 10; i++) {
if (i == 2) continue;
if (i == 4) break;
printf("i=%d\n", i);
}
return 0;
}Output
for 1 for 2 for 3 while 3 while 2 while 1 do-while runs once: 10 i=0 i=1 i=3
Quick check
Which loop always runs its body at least once?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.