90 דק׳

תבניות של לולאות

תבניות בחינת המעבדה על לולאת זקיף: מונה, מונה עם תנאי, צובר, צובר עם תנאי, ממוצע, מקסימום ומינימום, ומקסימום עם ערך נלווה.

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

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

The patterns of the lab exam

The lab exam (בחינת המעבדה) checks eight loop patterns, named with Hebrew letters in the Ministry's document:

PatternAnswersLab experiments
אwhile with a sentinelread until a stop value1 to 5
בcountinghow many values?1
גcounting with a conditionhow many above 90?3, 4, 5
דsummingwhat is the total?1
הsumming with a conditionthe total of some values
וmax / minthe largest, the smallest2
זmax / min with a companion valuewho had the largest?
חcombining patternsfor example the average: sum / count1, 4

Pattern א is the sentinel loop from the previous lesson. All the others live inside it. One example runs through this whole lesson: four student grades, then -1 to stop.

72 95 64 91 -1

One skeleton, one variable per question

scanf("%d", &grade);
while (grade != -1) {
    /* the pattern's work */
    scanf("%d", &grade);
}
/* print the answer */

Each pattern adds a variable that answers one question:

variableanswerstypical update
counterhow many?count++
accumulatorwhat total?sum += grade
maximumwhat is largest?if (grade > max) max = grade
minimumwhat is smallest?if (grade < min) min = grade

The rule for all of them: initialize before the loop, update inside the loop only when the rule applies, print after the loop.

Counting (ב)

A counter (מונה) answers "how many". It starts at 0 before the loop and goes up by one for every real value. The sentinel is not data, so it is not counted.

int count = 0;
scanf("%d", &grade);
while (grade != -1) {
    count++;
    scanf("%d", &grade);
}
printf("count=%d\n", count);
count=4
The counter goes up once per grade. On -1 the loop ends and count stays 4.לפתיחה במסך מלא

Counting with a condition (ג)

How many grades are above 90? Same counter, but the ++ sits inside an if:

int above90 = 0;
scanf("%d", &grade);
while (grade != -1) {
    if (grade > 90)
        above90++;
    scanf("%d", &grade);
}
printf("above 90: %d\n", above90);
gradegrade > 90above90
72false0
95true1
64false1
91true2
above 90: 2

Summing (ד)

An accumulator (צובר) collects a running total. sum += grade; means sum = sum + grade;.

int sum = 0;
scanf("%d", &grade);
while (grade != -1) {
    sum += grade;
    scanf("%d", &grade);
}
printf("sum=%d\n", sum);
gradesum beforesum after
72072
9572167
64167231
91231322
sum=322

int sum = 0; must be before the loop. Written inside the loop, it would set the sum back to 0 every iteration, and the program would print only the last grade.

Summing with a condition (ה)

The total of only the grades above 90: the same if as in counting with a condition, with sum90 += grade; instead of ++.

int sum90 = 0;
scanf("%d", &grade);
while (grade != -1) {
    if (grade > 90)
        sum90 += grade;
    scanf("%d", &grade);
}
printf("%d\n", sum90);
186

Only 95 and 91 pass the if: 95 + 91 = 186.

The average (ח): combining a sum and a count

An average (ממוצע) needs two patterns at once: the sum and the count. Two things can go wrong.

Integer division. sum and count are both int, so sum / count is int / int: 322 / 4 gives 80, and the fraction is lost before anything else happens. A cast (המרת טיפוס) turns one of them into a double first: (double)sum / count gives 322.0 / 4 = 80.5.

Division by zero. If the first value typed is -1, the loop body never runs and count is 0. Dividing by zero is an error. The count > 0 test guards the division.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int grade;
    int sum = 0;
    int count = 0;
 
    scanf("%d", &grade);
    while (grade != -1) {
        sum += grade;
        count++;
        scanf("%d", &grade);
    }
 
    if (count > 0) {
        double avg = (double)sum / count;
        printf("avg=%.1f\n", avg);
    } else {
        printf("NO DATA\n");
    }
    return 0;
}

Input 72 95 64 91 -1:

avg=80.5

Input -1:

NO DATA
Turn the cast off to see integer division, and change the input to only -1 to see the guard.לפתיחה במסך מלא

Max and min (ו)

The maximum (מקסימום) and minimum (מינימום) start from the first real value: it is the largest and the smallest seen so far. Every next value is compared with them.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int grade;
    scanf("%d", &grade);
    if (grade == -1) {
        printf("NO DATA\n");
        return 0;
    }
 
    int max = grade;   // the first grade
    int min = grade;   // starts both
    while (grade != -1) {
        if (grade > max) max = grade;
        if (grade < min) min = grade;
        scanf("%d", &grade);
    }
    printf("max=%d min=%d\n", max, min);
    return 0;
}
grademaxmin
727272
959572
649564
919564
max=95 min=64
The same grades, min starting from 0 and min starting from the first grade.לפתיחה במסך מלא

Max with a companion value (ז)

Sometimes the question is not only "what is the top grade" but "who got it". The value that goes with the max (here the student's number) is a companion value (ערך נלווה). Save it in the same if as the max, so the two always match.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int grade;
    int n = 0;
    int best = 0;
    int who = 0;
 
    scanf("%d", &grade);
    while (grade != -1) {
        n++;
        if (n == 1 || grade > best) {
            best = grade;
            who = n;   // the companion
        }
        scanf("%d", &grade);
    }
 
    if (n > 0)
        printf("best %d by student %d\n", best, who);
    else
        printf("NO DATA\n");
    return 0;
}
best 95 by student 2

n == 1 means "this is the first grade": it starts best, exactly as the first grade started max above. The values 0 given to best and who are never printed; they only keep the compiler from warning about variables without a value.

best and who change together, only when a new best grade appears.לפתיחה במסך מלא

Several patterns in one loop

Lab experiment 4 asks for the average and for how many grades are above 90. One loop does both: a counter, an accumulator and a counter with a condition, updated in the same body.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int grade;
    int count = 0;
    int sum = 0;
    int above90 = 0;
 
    scanf("%d", &grade);
    while (grade != -1) {
        count++;
        sum += grade;
        if (grade > 90) above90++;
        scanf("%d", &grade);
    }
 
    if (count > 0)
        printf("avg=%.1f\n", (double)sum / count);
    printf("above 90: %d\n", above90);
    return 0;
}
avg=80.5
above 90: 2

Any value that is not data can be the sentinel

The sentinel does not have to be -1. In question 24 the values are positive and negative numbers, and 0 ends the input:

scanf("%d", &value);
while (value != 0) {
    if (value > 0) positive++;
    else negative++;
    scanf("%d", &value);
}
printf("positive=%d negative=%d\n", positive, negative);

With 4 -2 -7 3 0 it prints positive=2 negative=2. The 0 ends the loop and is in neither count. In lab experiment 4 the sentinel is any impossible grade, below 0 or above 100.

Key words

EnglishHebrewMeaning
counterמונהcounts how many: count++
accumulatorצוברa running total: sum += x
sentinelזקיףa stop value that is not data
averageממוצעsum / count, only when count > 0
maximumמקסימוםthe largest value
minimumמינימוםthe smallest value
companion valueערך נלווהsaved together with the max or min
integer divisionחילוק שלמיםint / int drops the fraction
castהמרת טיפוס(double)sum turns sum into a double
division by zeroחלוקה באפסguard it with count > 0

Practice

Answers and more questions: Practice: Loops.