These are the notes for C episode 6. Last episode our chai stall program learned to decide, but it took one order and stopped. Here programs learn to repeat: print a hundred tokens from one printf, add up a whole day's bills, keep taking orders until the customer says "that's all", and stop or skip in the middle. You will learn while, for and do-while, the infinite loop, the off-by-one error, the stray semicolon, running totals, break, continue and loops inside loops. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run with the input shown.
The problem: 100 tokens, copy-pasted
Mornings at the chai stall are chaos, so bhaiya wants paper tokens: Token 1, Token 2, Token 3... a hundred of them, printed by our program. With what we know, there's one way: one printf per token.
#include <stdio.h>
int main() {
printf("Token 1\n");
printf("Token 2\n");
printf("Token 3\n");
printf("Token 4\n");
printf("Token 5\n");
return 0;
}
Output:
Token 1
Token 2
Token 3
Token 4
Token 5
Five works. A hundred means a hundred lines; five hundred tomorrow means five hundred. And if bhaiya wants "Chai Token" instead of "Token", you edit every line and miss one. Copy-paste doesn't scale.
Why? Every line is the same; only the number changes. We are doing the repeating by hand, but repeating is exactly what computers are good at. The plan: print the token, add one, ask "still ≤ 100?", and if yes, go again. Write the work once and tell C: again, while the condition is true.
The fix: while
Think of making rotis. Before each roti: is there dough left? If yes, roll and cook one (the same work each time), and that uses up a ball of dough (something changes). Then back to the question. No dough → stop.
while (condition) {
// body: runs again and again while the condition is true
}
#include <stdio.h>
int main() {
int token = 1;
while (token <= 5) {
printf("Token %d\n", token);
token++;
}
return 0;
}
Output:
Token 1
Token 2
Token 3
Token 4
Token 5
Each trip round the loop is an iteration. When token becomes 6, 6 <= 5 is false and the loop ends. For a hundred tokens, change one number: while (token <= 100). Same three lines of code, a hundred tokens.
How it runs, step by step:
| token | check token <= 5 |
prints |
|---|---|---|
| 1 | true | Token 1 |
| 2 | true | Token 2 |
| 3 | true | Token 3 |
| 4 | true | Token 4 |
| 5 | true | Token 5 |
| 6 | false | (loop ends) |
The loop that never ends
If nothing inside the loop changes token, it stays 1 forever, and 1 <= 5 is true forever: an infinite loop.
#include <stdio.h>
int main() {
int token = 1, served = 0;
while (token <= 5) {
served = served + 1;
}
printf("Served: %d\n", served);
return 0;
}
On the SyntaxPilot compiler: nothing is printed, and after 8 seconds the run stops with Time Limit Exceeded. On your own computer it would run until you press Ctrl + C. Every loop needs something inside that moves it towards the end (here, token++).
for: start, check and step on one line
In the while loop, the start (int token = 1;) is above the loop, the check is in the while, and the step (token++) hides at the bottom of the body, which is exactly the line people forget. Think of a bus route board: first stop, last stop, next stop, all on one board.
for (start; check; step) {
// body
}
#include <stdio.h>
int main() {
for (int token = 1; token <= 5; token++) {
printf("Token %d\n", token);
}
return 0;
}
Output: Token 1 to Token 5.
- start runs once, before everything.
- check runs before every iteration; false → the loop ends.
- step runs after every iteration.
Use for when you know how many times (count from 1 to n). Use while when you keep going until something happens.
Two classic bugs
Off-by-one: < instead of <=
#include <stdio.h>
int main() {
for (int token = 1; token < 5; token++) {
printf("Token %d\n", token);
}
return 0;
}
Output:
Token 1
Token 2
Token 3
Token 4
Customer 5 gets no token. When token became 5, 5 < 5 was false. Doing one round too many or too few is called an off-by-one error, the most common loop bug.
A semicolon after for ( )
#include <stdio.h>
int main() {
int token;
for (token = 1; token <= 5; token++);
{
printf("Token %d\n", token);
}
return 0;
}
Output:
Token 6
The ; is the loop's empty body. The loop counts from 1 to 6 doing nothing; then the block below runs once, with token already 6. Same trap as the ; after if in episode 5, and gcc gives no warning.
A running total
Bhaiya wants the day's total. Think of his cash box: empty (zero) at 7 am, each bill goes in, and he counts it once at closing time.
- the total starts at
0before the loop, total += bill;adds each bill inside the loop,printfthe total after the loop.
#include <stdio.h>
int main() {
int n, bill, total = 0;
printf("How many bills? ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &bill);
total += bill;
}
printf("\nDay total: %d\n", total);
return 0;
}
Input 3, 120, 80, 50:
How many bills?
Day total: 250
The loop ran exactly n times because n came from the user. A common mistake is int total = 0; inside the loop: the box is emptied before every bill and you only get the last one.
do-while: at least once
At the stall, bhaiya always takes your first order, no question asked, and only then asks "anything else?". The check comes after the work. A loop that checks at the bottom is do ... while, and its body always runs at least once.
do {
// body: runs first, then the check
} while (condition); // the ; here is required
#include <stdio.h>
int main() {
int item, total = 0;
do {
printf("Item (1 Chai 2 Samosa, 0 = done): ");
scanf("%d", &item);
if (item == 1) total += 15;
else if (item == 2) total += 20;
} while (item != 0);
printf("\nTotal: %d\n", total);
return 0;
}
Input 1, 2, 2, 0:
Item (1 Chai 2 Samosa, 0 = done): Item (1 Chai 2 Samosa, 0 = done): Item (1 Chai 2 Samosa, 0 = done): Item (1 Chai 2 Samosa, 0 = done):
Total: 55
(The prompts sit on one line because the input comes from the input box, not typed in a terminal.) 15 + 20 + 20 = 55: a whole table's order in one run.
while vs do-while when the condition is false from the start:
#include <stdio.h>
int main() {
int i = 10;
while (i < 5) {
printf("while %d\n", i);
}
do {
printf("do-while %d\n", i);
} while (i < 5);
return 0;
}
Output:
do-while 10
break and continue
break: leave the loop now
Bhaiya has 5 samosas. Orders come in: 2, 2, then 3. There aren't enough, so the loop must stop from the middle.
#include <stdio.h>
int main() {
int stock = 5, wanted;
while (1) {
printf("Samosas wanted: ");
scanf("%d", &wanted);
if (wanted > stock) {
printf("\nSorry, only %d left. Closing!\n", stock);
break;
}
stock -= wanted;
}
return 0;
}
Input 2, 2, 3:
Samosas wanted: Samosas wanted: Samosas wanted:
Sorry, only 1 left. Closing!
while (1) is always true (1 is non-zero), so only break gets out.
continue: skip to the next round
Some bills are typed wrong (−20, 0). Don't stop; skip that bill.
#include <stdio.h>
int main() {
int n, bill, total = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &bill);
if (bill <= 0) {
printf("Skipping bad bill %d\n", bill);
continue;
}
total += bill;
}
printf("Day total: %d\n", total);
return 0;
}
Input 4, 100, -20, 50, 0:
Skipping bad bill -20
Skipping bad bill 0
Day total: 150
continue skips the rest of the body. In a for loop the step (i++) still runs; in a do-while it jumps to the check at the bottom.
Loops inside loops
The cinema from episode 5 needs seat labels: rows A to C, seats 1 to 4 in every row. For each row, go through every seat: a nested loop.
#include <stdio.h>
int main() {
for (char row = 'A'; row <= 'C'; row++) {
for (int seat = 1; seat <= 4; seat++) {
printf("%c%d ", row, seat);
}
printf("\n");
}
return 0;
}
Output:
A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
The inner loop runs completely for every single round of the outer loop: 3 × 4 = 12 seats. (row++ works on a char because characters are small numbers: 'A' + 1 is 'B'.)
A loop variable lives only inside its loop
#include <stdio.h>
int main() {
for (int i = 1; i <= 3; i++) {
printf("%d\n", i);
}
printf("After: %d\n", i);
return 0;
}
main.c: In function 'main':
main.c:7:27: error: 'i' undeclared (first use in this function)
7 | printf("After: %d\n", i);
| ^
main.c:7:27: note: each undeclared identifier is reported only once for each function it appears in
A variable declared inside the for ( ) exists only inside that loop. If you need it afterwards, declare it before the loop (int i; then for (i = 1; ...)).
Which loop when?
| Loop | Checks | Use it when | Example |
|---|---|---|---|
for |
before each round | you know how many times | tokens 1 to 100, n bills |
while |
before each round | until something happens | until stock runs out |
do-while |
after each round | the body must run at least once | menus, "anything else?", PIN entry |
Common mistakes (and the real gcc messages)
| Mistake | Code | What gcc says / what happens |
|---|---|---|
| No step | while (token <= 5) { ... } with no token++ |
no error; runs forever (Time Limit Exceeded on the stage) |
| Off by one | for (t = 1; t < 5; t++) |
no error; only 4 rounds |
; after for ( ) |
for (t = 1; t <= 5; t++); |
no error; the body runs once afterwards (Token 6) |
| Total reset inside the loop | for (...) { int total = 0; total += bill; } |
no error; only the last bill counts |
| Loop variable used after the loop | printf("%d", i); after for (int i ...) |
error: 'i' undeclared (first use in this function) |
Forgetting the ; after do { } while (...) |
} while (item != 0) |
error: expected ';' before ... |
break inside a switch inside a loop |
expecting it to leave the loop | it only leaves the switch |
Mini project: the chai stall's day closing
#include <stdio.h>
int main() {
int item, cups = 0, total = 0;
do {
printf("1 Chai 2 Samosa 3 Lassi, 0 = close: ");
scanf("%d", &item);
switch (item) {
case 1: total += 15; break;
case 2: total += 20; break;
case 3: total += 40; break;
case 0: break;
default: printf("\nNo item %d\n", item); continue;
}
if (item != 0) cups++;
} while (item != 0);
printf("\nItems sold: %d, Day total: %d\n", cups, total);
return 0;
}
Input 1, 3, 7, 2, 1, 0:
1 Chai 2 Samosa 3 Lassi, 0 = close: 1 Chai 2 Samosa 3 Lassi, 0 = close: 1 Chai 2 Samosa 3 Lassi, 0 = close:
No item 7
1 Chai 2 Samosa 3 Lassi, 0 = close: 1 Chai 2 Samosa 3 Lassi, 0 = close: 1 Chai 2 Samosa 3 Lassi, 0 = close:
Items sold: 4, Day total: 90
do-whilebecause the menu must show at least once.- Inside a
switch,breakleaves the switch, not the loop. continuein ado-whilejumps to the check at the bottom, so item 7 isn't counted.- 15 + 40 + 20 + 15 = 90.
Practice
- Read a number and print its multiplication table up to 10.
- Read
nand print the sum 1 + 2 + ... + n. - Read a number of rows and print a right triangle of
*with nested loops. - Keep asking for a PIN until it is 1234 (use
do-while), then print "Welcome!". - How many times does
for (int i = 10; i > 0; i -= 3)run, and what are the values ofi?
Solutions and hints
1. Input 7 prints 7 x 1 = 7 up to 7 x 10 = 70.
int n;
scanf("%d", &n);
for (int i = 1; i <= 10; i++)
printf("%d x %d = %d\n", n, i, n * i);
2. A running total. Input 100 prints Sum: 5050.
int n, sum = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
sum += i;
printf("Sum: %d\n", sum);
3. The inner loop runs r times on row r. Input 4 prints:
*
**
***
****
int rows;
scanf("%d", &rows);
for (int r = 1; r <= rows; r++) {
for (int c = 1; c <= r; c++)
printf("*");
printf("\n");
}
4. Input 1111, 4321, 1234 prints PIN: PIN: PIN: and then Welcome!.
int pin;
do {
printf("PIN: ");
scanf("%d", &pin);
} while (pin != 1234);
printf("\nWelcome!\n");
5. Four times: i is 10, 7, 4, 1. The next value, −2, fails i > 0.
Quick quiz
What does this print?
for (int i = 0; i < 10; i += 3)
printf("%d ", i);
- A.
0 3 6 9 - B.
0 3 6 - C.
3 6 9 - D.
0 3 6 9 12
Answer
A: 0 3 6 9. i starts at 0 and goes up by 3. 0, 3, 6 and 9 pass i < 10; 12 fails, so the loop stops before printing it.
Interview questions
- What is the difference between
whileanddo-while? - Write
for (int i = 0; i < n; i++)as an equivalentwhileloop. - What is an infinite loop? Give a case where one is useful on purpose.
- What is the difference between
breakandcontinue? - In a loop containing a
switch, what doesbreakinside the switch do? - What is an off-by-one error? How do you avoid it?
- How many times does the inner body run in two nested loops of
nrounds each? (n × n) - Can a
forloop have empty parts, likefor (;;)? What does it do?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Loop | Code that repeats while a condition holds | printing tokens 1 to 100 |
| Iteration | One trip round a loop | the round that prints "Token 3" |
while |
Checks the condition, then runs the body; repeats | while (token <= 5) { ... } |
| Loop condition | The check that decides whether to go round again | token <= 5 |
| Infinite loop | A loop whose condition never becomes false | while (1) with no break |
| Time Limit Exceeded | The online compiler stopped a program that ran too long | the loop with no token++ |
for |
A loop with start, check and step on one line | for (int i = 1; i <= n; i++) |
| Off-by-one error | One round too many or too few | < 5 instead of <= 5 |
| Running total | A variable that collects a sum across iterations | total += bill; |
| Accumulator | Another name for a running total variable | total, sum |
do-while |
Runs the body first, then checks; at least once | do { ... } while (item != 0); |
break |
Leaves the loop (or switch) immediately | if (wanted > stock) break; |
continue |
Skips the rest of the body and starts the next round | if (bill <= 0) continue; |
| Nested loop | A loop inside another loop | rows × seats |
| Scope of a loop variable | A variable declared in for ( ) exists only inside the loop |
'i' undeclared after the loop |
Summary
- A
whileloop checks, does the work, steps, and repeats. Forget the step and it never ends. for (start; check; step)puts the three parts on one line; use it for counting.- Watch for off-by-one (
<vs<=) and never put;right afterfor ( ). - Running totals start at 0 before the loop and grow with
+=inside it. do-whileruns at least once and needs a;afterwhile (...).breakleaves the loop;continueskips to the next round. Nested loops run the inner loop fully for every outer round.
Next episode: functions. Our main is getting long, and the same price calculation shows up in every program. Next time we pack code into reusable pieces.