90 דק׳

לולאת while

ארבעת החלקים של כל לולאה, while שורה אחר שורה עם טבלת מעקב, הבדיקה האחרונה שנכשלת, אפס חזרות, לולאה אינסופית, גבולות, וקריאת קלט עד זקיף.

למצגתלקריאה באתרבאנגלית בלבד

השיעור הזה כתוב באנגלית בלבד.

Repeat without copying

To print the numbers 1 to 5 you can write five printf lines. For 1000 numbers, or for a number the user types, copying does not work. A loop (לולאה) runs the same lines again and again:

int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}
1 2 3 4 5

The loop is the same size for 5 numbers or for 5000: change 5 to 5000.

Ask one question about every loop you write: what changes each repetition, and what ends the loop?

The four parts of every loop

Every loop in C, whatever its form, has the same four parts:

  1. Initialize (אתחול): set the starting state. This happens once, before the loop.
  2. Test: decide whether another repetition starts. This is the loop's condition (תנאי).
  3. Work: process the current value. These are the statements of the loop body (גוף הלולאה).
  4. Progress: move toward the end, usually by changing the loop variable. This is the update (עדכון).

One run of the body is called an iteration (חזרה). After the progress the computer goes back to the test. When the test is false, the loop ends.

Click through: initialize once, then test, work, progress and back to the test, until the test is false.לפתיחה במסך מלא

In the loop above: int i = 1; initializes, i <= 5 is the test, printf("%d ", i); is the work, and i++; is the progress.

The while loop

while (condition) {
    statements;
}

while checks the condition before the body. If it is true, the body runs once and the computer comes back to check again. If it is false, the computer jumps past the closing }.

A complete program:

#include <stdio.h>
 
int main(void)
{
    int i = 1;
    while (i <= 5) {
        printf("%d ", i);
        i++;
    }
    printf("\nafter the loop i = %d\n", i);
    return 0;
}
1 2 3 4 5
after the loop i = 6

After the loop i is 6, not 5. The loop ended because the test 6 <= 5 was false.

Each click is one thing the computer does. Watch the line in focus, the box of i and the trace table.לפתיחה במסך מלא

Tracing a loop

A trace table (טבלת מעקב) follows a loop on paper. Write one row for every test of the condition, including the last test, the one that fails.

int i = 2;
while (i < 8) {
    printf("%d ", i);
    i += 2;
}
ii < 8printedi after
2true24
4true46
6true68
8false(not run)
2 4 6

The body ran 3 times. The final test is 8 < 8, which is false. Recording the value of i after the last update is what keeps you from being "one off" in your answer.

Zero iterations

Because while tests before the body, the body may run zero times:

int x = 8;
while (x < 5) {
    printf("%d", x);
    x++;
}

Nothing is printed. The first test, 8 < 5, is false, so the body never runs. This is exactly what you want when the first input may already be the signal to stop.

Choose a starting value for x and count how many times the body runs.לפתיחה במסך מלא

The infinite loop

If the body never makes progress, the test never becomes false:

int i = 1;
while (i <= 5) {
    printf("%d ", i);
}
1 1 1 1 1 1 1 1 1 1 ...

i is always 1, so 1 <= 5 is always true. This is an infinite loop (לולאה אינסופית). The fix is to add the progress, i++;, inside the body.

Boundaries: one too many

The task: take exactly 12 samples.

int sample = 0;
while (sample <= 12) {
    // read one sample
    sample++;
}

List the values of sample that pass the test: 0, 1, 2, ... 12. That is 13 values, one too many. With sample < 12 the values are 0 to 11: twelve.

Before you write a loop, write three numbers for it:

loop testfirst valuelast valuefirst rejected valuecount
sample <= 120121313
sample < 120111212

Reading until a sentinel

Often the program does not know in advance how many values will come. The user types values and then a special value that means "stop". That stop value is called a sentinel (זקיף). It is not data: it is never processed.

The pattern has three rules: read before the loop, process only real data, read the next value at the end of the body.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int value;
    scanf("%d", &value);
    while (value != -1) {
        printf("processing %d\n", value);
        scanf("%d", &value);
    }
    printf("done\n");
    return 0;
}

Typing 4, 7 and -1, each followed by Enter (what the user types is shown too):

4
processing 4
7
processing 7
-1
done
valuevalue != -1processed
4trueyes
7trueyes
-1falseno

-1 is tested, but it is never processed. If the first value typed is -1, the body runs zero times.

Follow the input 4 7 -1: the read before the loop, the test, and the read at the end of the body.לפתיחה במסך מלא

This is pattern א of the lab exam, "while with a sentinel". Lab experiments 1 to 5 all start with it. The next lesson builds the other patterns inside it.

Remember the line #define _CRT_SECURE_NO_WARNINGS at the top of the file: without it, Visual Studio stops on scanf with warning C4996.

Key words

EnglishHebrewMeaning
loopלולאהcode that runs again and again
iterationחזרהone run of the loop body
condition (test)תנאיchecked before every iteration
loop bodyגוף הלולאהthe statements inside { }
initializeאתחולset the starting value, once
update (progress)עדכוןmoves the loop toward its end
infinite loopלולאה אינסופיתthe test never becomes false
sentinelזקיףa stop value that is not data
trace tableטבלת מעקבone row per test of the condition
boundaryגבולfirst value, last value, first rejected value

Practice

Answers and more questions: Practice: Loops.