Loops
for
C
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d squared is %d\n", i, i * i);
}
return 0;
}A for loop has three parts: start (int i = 1), condition (i <= 5) and step (i++, which adds 1).
while
C
#include <stdio.h>
int main() {
int n = 1234;
int digits = 0;
while (n > 0) {
n = n / 10;
digits++;
}
printf("1234 has %d digits\n", digits);
return 0;
}do-while
Runs the body at least once, then checks:
C
#include <stdio.h>
int main() {
int n;
do {
printf("Enter a positive number: ");
scanf("%d", &n);
} while (n <= 0);
printf("Thanks, you entered %d\n", n);
return 0;
}This "keep asking until the input is valid" pattern is the classic use of do-while.
break and continue
C
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 8) break; // stop the loop
if (i % 2 == 0) continue; // skip even numbers
printf("%d ", i);
}
printf("\n");
return 0;
}Nested loops
C
#include <stdio.h>
int main() {
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
printf("* ");
}
printf("\n");
}
return 0;
}Sum and average
C
#include <stdio.h>
int main() {
int count, value, total = 0;
scanf("%d", &count);
for (int i = 0; i < count; i++) {
scanf("%d", &value);
total += value;
}
printf("Total %d, average %.2f\n", total, (double)total / count);
return 0;
}Finished this lesson?Mark it complete to earn +20 XP and move your progress on.