C Loops
C has three loops: for, while (entry-controlled) and do-while (exit-controlled).
Pattern Printing with Nested for
#include <stdio.h>
int main() {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++)
printf("* ");
printf("\n");
}
return 0;
}
*
* *
* * *
* * * *
while: Armstrong Number
#include <stdio.h>
int main() {
int n = 153, t = n, sum = 0;
while (t > 0) {
int d = t % 10;
sum += d * d * d;
t /= 10;
}
printf(sum == n ? "%d is Armstrong\n" : "%d is not Armstrong\n", n);
return 0;
}
153 is Armstrong
break, continue, goto
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even
if (i > 7) break; // stop after 7
printf("%d ", i);
}
1 3 5 7
Track your progress through the C course