Learn how to use for and while loops in C with step-by-step visual examples.
#include <stdio.h> int main(void) { printf("1\n"); printf("2\n"); printf("3\n"); printf("4\n"); printf("5\n"); return 0; }
printf("1\n"); printf("2\n"); ... printf("100\n"); for 100 lines? And if the requirement changed to "print only multiples of 3", you'd have to rewrite everything.#include <stdio.h> int main(void) { for (int i = 1; i <= 5; i++) { printf("%d\n", i); } return 0; }
5 to 100. Even 10,000 iterations fit in the same amount of code.// Without loop: manually add each number int sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10; // With loop int sum = 0; for (int i = 1; i <= 10; i++) sum += i;
for (int i = 0; i < 5; i++) { printf("i = %d\n", i); }
int n = 1; while (n <= 100) { n = n * 2; } printf("n = %d\n", n); // -> 128
| Name | Type | Value |
|---|
while checks the condition before the body; do-while checks it after. As a result, the body of a do-while runs at least once.while (condition) { body; // 0 iterations if false }
do { body; // runs at least once } while (condition);
; after } while (condition); is a compile error.int choice; do { printf("Pick 1-3> "); scanf("%d", &choice); if (choice < 1 || choice > 3) printf("Invalid input\n"); } while (choice < 1 || choice > 3); printf("You picked %d\n", choice);
| Construct | Test timing | Min iterations | When to use |
|---|---|---|---|
for | Pre-test | 0 | Known number of iterations |
while | Pre-test | 0 | Unknown count, stop on condition |
do-while | Post-test | 1 | Must run at least once (input validation, etc.) |
for (int i=0; i<10; i++) { if (i == 5) break; printf("%d ", i); } // Output: 0 1 2 3 4
for (int i=0; i<5; i++) { if (i == 2) continue; printf("%d ", i); } // Output: 0 1 3 4 (skips 2)
break and continue only affect the innermost loop. break inside a nested loop does not exit the outer loop.Check your understanding of this lesson!
for (int i=0; i<5; i++) execute?i takes the five values 0, 1, 2, 3, 4, so the body runs 5 times.
while(1)?The condition is always 1 (true), so the loop keeps running forever unless broken out of by break or return.
do-while tests the condition at the end of the loop, so the body always runs at least once. while tests first, so it can run zero times.
Combine this interactive site with books for more practice.
* Links above are affiliate links. Purchases help support this site.