Loop patterns
The lab exam patterns on a sentinel loop: counting, counting with a condition, summing, summing with a condition, the average, max and min, and max with a companion value.
The patterns of the lab exam
The lab exam (בחינת המעבדה) checks eight loop patterns, named with Hebrew letters in the Ministry's document:
| Pattern | Answers | Lab experiments | |
|---|---|---|---|
| א | while with a sentinel | read until a stop value | 1 to 5 |
| ב | counting | how many values? | 1 |
| ג | counting with a condition | how many above 90? | 3, 4, 5 |
| ד | summing | what is the total? | 1 |
| ה | summing with a condition | the total of some values | |
| ו | max / min | the largest, the smallest | 2 |
| ז | max / min with a companion value | who had the largest? | |
| ח | combining patterns | for example the average: sum / count | 1, 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 -1One 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:
| variable | answers | typical update |
|---|---|---|
| counter | how many? | count++ |
| accumulator | what total? | sum += grade |
| maximum | what is largest? | if (grade > max) max = grade |
| minimum | what 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=4Counting 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);| grade | grade > 90 | above90 |
|---|---|---|
| 72 | false | 0 |
| 95 | true | 1 |
| 64 | false | 1 |
| 91 | true | 2 |
above 90: 2Summing (ד)
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);| grade | sum before | sum after |
|---|---|---|
| 72 | 0 | 72 |
| 95 | 72 | 167 |
| 64 | 167 | 231 |
| 91 | 231 | 322 |
sum=322int 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);186Only 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.5Input -1:
NO DATAMax 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;
}| grade | max | min |
|---|---|---|
| 72 | 72 | 72 |
| 95 | 95 | 72 |
| 64 | 95 | 64 |
| 91 | 95 | 64 |
max=95 min=64Max 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 2n == 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.
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: 2Any 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
| English | Hebrew | Meaning |
|---|---|---|
| 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.