Programs & Examples
C Loops · Study material
Centered star pyramid
For row r of n: print n − r spaces, then 2r − 1 stars. Pattern programs are mostly about finding these two formulas.
#include <stdio.h>
int main(void) {
int rows = 4;
for (int r = 1; r <= rows; r++) {
for (int s = 0; s < rows - r; s++)
putchar(' '); /* rows - r leading spaces */
for (int k = 0; k < 2 * r - 1; k++)
putchar('*'); /* 2r - 1 stars */
putchar('\n');
}
return 0;
}
* *** ***** *******
Floyd's triangle
Row r prints r consecutive numbers; one counter outside the loops keeps counting across rows.
#include <stdio.h>
int main(void) {
int n = 1;
for (int r = 1; r <= 4; r++) {
for (int c = 1; c <= r; c++)
printf("%d ", n++);
printf("\n");
}
return 0;
}
1 2 3 4 5 6 7 8 9 10
Sieve of Eratosthenes
Nested loops cross out multiples of each prime, starting at p². It finds all primes up to N in O(N log log N) – much faster than testing each number separately.
#include <stdbool.h>
#include <stdio.h>
int main(void) {
enum { N = 30 };
bool composite[N + 1] = {false};
for (int p = 2; p * p <= N; p++)
if (!composite[p])
for (int m = p * p; m <= N; m += p) /* cross out the multiples of p */
composite[m] = true;
for (int i = 2; i <= N; i++)
if (!composite[i])
printf("%d ", i);
printf("\n");
return 0;
}
2 3 5 7 11 13 17 19 23 29