לולאות for ו־do...while
do...while שרצה לפחות פעם אחת, בדיקת קלט ותפריט; לולאת for, שלושת חלקי הכותרת וסדר הביצוע, גבולות, ואיך בוחרים לולאה.
השיעור הזה כתוב באנגלית בלבד.
Two more loop forms
while is one way to write a loop. C has two more: do...while and for. All three have the same four parts from the first lesson (initialize, test, work, progress). What changes is where the parts are written and when the test runs.
A warm-up from the first lesson. What are the final values of i and sum?
int i = 1, sum = 0;
while (i <= 3) {
sum += i;
i++;
}| i | i <= 3 | sum after | i after |
|---|---|---|---|
| 1 | true | 1 | 2 |
| 2 | true | 3 | 3 |
| 3 | true | 6 | 4 |
| 4 | false |
i = 4, sum = 6. A common wrong answer is i = 3: that is the last value that passed the test, not the value after the final update.
do...while: the body first
do {
statements;
} while (condition);do...while runs the body first and tests after it. If the test is true, the body runs again. So the body always runs at least once, even if the condition was never true. Note the semicolon after while (...): it is required.
| while | do...while | |
|---|---|---|
| the test runs | before the body | after the body |
| the body runs | zero or more times | one or more times |
| use it when | the first input may already end the work | the body must run once: a first input, a first menu |
Trace: do...while
int n = 4;
do {
printf("%d ", n);
n -= 2;
} while (n > 0);| iteration | n before | printed | n after | n > 0 |
|---|---|---|---|---|
| 1 | 4 | 4 | 2 | true |
| 2 | 2 | 2 | 0 | false |
4 2The condition sees the value of n after the update.
An exam-style check: what does this print?
int x = 5;
do {
printf("%d ", x);
x--;
} while (x > 5);5The body runs once and prints 5. Then x is 4, the test 4 > 5 is false, and the loop ends. The condition is tested after the body.
Input validation
Keep asking until the user types a valid value. One input always happens, so do...while fits. This is input validation (בדיקת קלט).
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int level;
do {
printf("Enter level 0-100: ");
scanf("%d", &level);
} while (level < 0 || level > 100);
printf("level=%d\n", level);
return 0;
}Enter level 0-100: 120
Enter level 0-100: -4
Enter level 0-100: 75
level=75Read the condition aloud: repeat while the level is below 0 or above 100, that is, while it is outside the range.
A menu that repeats
A menu (תפריט) must appear at least once and repeat until the user chooses to exit (question 21):
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int choice;
do {
printf("1=ON 2=OFF 0=EXIT\n");
scanf("%d", &choice);
if (choice == 1) printf("ON\n");
else if (choice == 2) printf("OFF\n");
} while (choice != 0);
return 0;
}1=ON 2=OFF 0=EXIT
1
ON
1=ON 2=OFF 0=EXIT
2
OFF
1=ON 2=OFF 0=EXIT
0Choices other than 0, 1 and 2 are ignored, and the menu shows again.
The for loop
When the number of iterations is known, for keeps all the loop's control in one line, the loop header (כותרת הלולאה):
for (int i = 0; i < 8; i++) {
// take one sample
}| part | in the header | when it runs |
|---|---|---|
| 1. initialize | int i = 0 | once, first |
| 2. test | i < 8 | before every iteration |
| 3. body | { ... } | when the test is true |
| 4. update | i++ | after the body, then back to the test |
The written order is init; test; update. The run order is 1, 2, 3, 4, then 2, 3, 4, ... until the test is false. The update never runs before the first body. i here is the loop's control variable (משתנה בקרה).
Trace: for
int sum = 0;
for (int i = 1; i <= 4; i++) {
sum += i;
}
printf("%d\n", sum);| i | i <= 4 | sum before | sum after |
|---|---|---|---|
| 1 | true | 0 | 1 |
| 2 | true | 1 | 3 |
| 3 | true | 3 | 6 |
| 4 | true | 6 | 10 |
| 5 | false | 10 | (not run) |
10while and for are the same loop
int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}for (int i = 0; i < 5; i++) {
printf("%d ", i);
}Both print 0 1 2 3 4. In the while the initialization, the test and the update are on three different lines; in the for they stay together in the header. Prefer for when the count is known.
Boundaries and steps
The update does not have to be i++. Write the first value, the last value and the first rejected value of every loop before you code it:
| loop header | values | count | first rejected |
|---|---|---|---|
for (i = 0; i < 5; i++) | 0 1 2 3 4 | 5 | 5 |
for (i = 0; i <= 5; i++) | 0 1 2 3 4 5 | 6 | 6 |
for (i = 1; i <= 5; i++) | 1 2 3 4 5 | 5 | 6 |
for (i = 5; i > 0; i--) | 5 4 3 2 1 | 5 | 0 |
for (i = 10; i >= 2; i -= 2) | 10 8 6 4 2 | 5 | 0 |
Counting with a condition in a for
How many multiples of 3 are there from 1 to 30?
#include <stdio.h>
int main(void)
{
int count = 0;
for (int i = 1; i <= 30; i++) {
if (i % 3 == 0) {
count++;
}
}
printf("%d\n", count);
return 0;
}10The loop visits every integer; the if picks the multiples. A shorter loop visits only the multiples: for (int i = 3; i <= 30; i += 3) count++;.
Which loop?
| the situation | the loop |
|---|---|
| the number of iterations is known ("read exactly 12 samples") | for |
| the number is unknown ("read until -1") | while |
| the body must run at least once ("show the menu, repeat until 0") | do...while |
This is a decision rule, not a law: every loop can be written in every form. The right form shows the reader what you meant.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| for loop | לולאת for | init; test; update in one header |
| do...while loop | לולאת do...while | the body first, the test after |
| loop header | כותרת הלולאה | the line for ( ... ) |
| control variable | משתנה בקרה | the counter of a for loop, often i |
| update | עדכון | i++ or i += 2, after the body |
| run order | סדר ביצוע | init, test, body, update, test ... |
| input validation | בדיקת קלט | ask again until the value is valid |
| menu | תפריט | choices shown at least once |
| known count | מספר חזרות ידוע | a reason to use for |
| at least once | לפחות פעם אחת | a reason to use do...while |
Practice
Answers and more questions: Practice: Loops.