Skip to content
Loops
step 1/5

Reading — step 1 of 5

Learn

~3 min readControl Flow

Loops

C gave the world the three-part for loop — the exact syntax you've seen in Java, JavaScript, and half of everything else was designed here in 1972. C's versions have no safety rails, which makes them the best place to learn the failure modes everyone else's rails are guarding against.

for: the original

int sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;
}

for (init; condition; step) — init once, test before every iteration, step after every body. Declaring i inside the parens scopes it to the loop (standard since C99; the grader's compiler is fine with it).

The array-walking form you already know from chapter 2:

for (int i = 0; i < n; i++) {
    process(a[i]);
}

i < n for arrays (indices 0…n−1), i <= n for counting 1…n. C has no range syntax to encode this decision for you and no bounds checker to catch the wrong choice — the < vs <= call is made consciously, every time, forever. That's not a weakness of this course's exercises; it's the actual daily texture of C.

while and do-while

while (n > 1) {                 /* test first: may run zero times */
    n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
}

do {
    printf("menu> ");
    scanf("%d", &choice);
} while (choice != 0);          /* test after: always runs at least once */

while when iteration count is unknown; do-while for the rare "must happen once" shape (input prompts being the classic). Note the semicolon after a do-while's condition — and the classic typo in the other direction: a stray semicolon after while (cond); or for (…); is an empty loop body, the code below runs once, and -Wall (again) flags it.

break, continue, and infinite loops

while (1) {                     /* C's idiomatic infinite loop */
    int x = read_next();
    if (x < 0) continue;        /* skip this one */
    if (x == 0) break;          /* done entirely */
    process(x);
}

while (1) — "while true" via truthiness — plus break is the C server/REPL skeleton. break exits one loop level only; nested-loop escapes use a flag or (whisper it) a goto to a cleanup label, which is the one goto use case C programmers still defend.

Your exercise: Sum 1 to N

Read n, print 1 + 2 + … + n. The accumulator, C edition:

int n;
scanf("%d", &n);
long long total = 0;
for (int i = 1; i <= n; i++) {
    total += i;
}
printf("%lld\n", total);

Details with your name on them: total initialized to 0, before the loop (uninitialized = garbage sum that works on your machine and fails on the grader's); <= not < (summing to N−1 is this exercise's signature wrong answer); and the type — n(n+1)/2 clears int's 2.1-billion ceiling around n ≈ 65,536, so long long with %lld is the adult choice. C won't warn on the overflow; it'll just be wrong. You know this now; that's the course working.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Loops — C Fundamentals