90 min

for and do...while

do...while that runs at least once, input validation and a menu; the for loop, the three parts of its header and the run order, boundaries, and how to choose a loop.

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++;
}
ii <= 3sum afteri after
1true12
2true33
3true64
4false

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.

whiledo...while
the test runsbefore the bodyafter the body
the body runszero or more timesone or more times
use it whenthe first input may already end the workthe 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);
iterationn beforeprintedn aftern > 0
1442true
2220false
4 2

The 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);
5

The 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=75

Read the condition aloud: repeat while the level is below 0 or above 100, that is, while it is outside the range.

Inputs 120, -4 and 75: only 75 gets past the loop.Open full screen

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
0

Choices 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
}
partin the headerwhen it runs
1. initializeint i = 0once, first
2. testi < 8before every iteration
3. body{ ... }when the test is true
4. updatei++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 (משתנה בקרה).

Watch the highlighted part of the header: initialize once, then test, body, update, test ...Open full screen

Trace: for

int sum = 0;
for (int i = 1; i <= 4; i++) {
    sum += i;
}
printf("%d\n", sum);
ii <= 4sum beforesum after
1true01
2true13
3true36
4true610
5false10(not run)
10

while 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 headervaluescountfirst rejected
for (i = 0; i < 5; i++)0 1 2 3 455
for (i = 0; i <= 5; i++)0 1 2 3 4 566
for (i = 1; i <= 5; i++)1 2 3 4 556
for (i = 5; i > 0; i--)5 4 3 2 150
for (i = 10; i >= 2; i -= 2)10 8 6 4 250
Predict each row before the click: values, count, first rejected value.Open full screen

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;
}
10

The 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 situationthe 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.

Choose a loop for each situation (questions 1 to 3).Open full screen

Key words

EnglishHebrewMeaning
for loopלולאת forinit; test; update in one header
do...while loopלולאת do...whilethe 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.