90 דק׳

break, continue ולולאות מקוננות

break שעוצר את הלולאה, continue שמדלג על חזרה אחת, לולאה בתוך לולאה, פירוק מספר לספרות (ניסויים 8 ו־9), ומשימת הצוות: דוגם מתח הסוללה עם בדיקות קבלה.

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

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

break: leave the loop early

break ends the nearest loop immediately. The rest of the body does not run, and the loop does not test again. The program continues after the loop's closing }.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int value;
    int sum = 0;
    for (int i = 0; i < 8; i++) {
        scanf("%d", &value);
        if (value == -1) {
            break;
        }
        sum += value;
    }
    printf("sum=%d\n", sum);
    return 0;
}

The loop reads at most 8 values, but -1 stops it earlier. With the input 4 7 -1 9:

ivaluevalue == -1sum
04false4
17false11
2-1truebreak
sum=11

The sentinel is not added, and 9 is never read by this loop.

Follow the input queue: on -1 the loop ends, and 9 stays unread.לפתיחה במסך מלא

Use break for a real reason to stop early: a sentinel, or the item you were searching for was found. Do not use it to patch a loop condition that is wrong.

continue: skip one iteration

continue skips the rest of this iteration only. The loop goes on with the next one. In a for loop, the update (i++) still runs.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int value;
    int sum = 0;
    int valid = 0;
    for (int i = 0; i < 6; i++) {
        scanf("%d", &value);
        if (value < 0) {
            continue;
        }
        sum += value;
        valid++;
    }
    printf("sum=%d valid=%d\n", sum, valid);
    return 0;
}

With the input 4 -2 7 -1 3 5:

ivaluethensumvalid
04add41
1-2skip41
27add112
3-1skip112
43add143
55add194
sum=19 valid=4

Here -1 is just a negative reading, not a stop value: the loop still reads six values. Use continue to reject one item (an invalid sensor reading) while keeping the fixed number of samples.

break or continue?

breakcontinue
what it doesends the nearest loopskips to the next iteration
use it foran early stop: a sentinel, a target foundrejecting one item: an invalid reading
with 4 -2 7 -1 3 5 and if (value < 0)sum = 4sum = 19

Only break changes how many iterations will still run.

At i == 3 the computer jumps between the test and the continue, and i never changes.לפתיחה במסך מלא

Nested loops

A loop inside another loop is a nested loop (לולאות מקוננות). Think of an LED matrix with 3 rows and 4 columns: the outer loop chooses a row, and the inner loop goes through every column of that row.

#include <stdio.h>
 
int main(void)
{
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 4; col++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
****
****
****

For every single iteration of the outer loop, the inner loop runs completely. The inner body runs 3 × 4 = 12 times. The printf("\n") belongs to the outer loop, after the inner loop: once per row.

Row 0 step by step, then the other rows: the inner loop lights all four columns every time.לפתיחה במסך מלא

Trace: nested loops

for (int i = 1; i <= 2; i++) {
    for (int j = 1; j <= 3; j++) {
        printf("%d ", i * j);
    }
    printf("\n");
}
iji * j
111
122
133
212
224
236
1 2 3
2 4 6

Trace the inner loop to the end before you change the outer variable. j starts again at 1 for each new i.

How much work?

A single loop for (i = 0; i < n; i++) runs its body n times. Two nested loops, the outer one n times and the inner one m times, run the inner body n × m times. Count these exactly: with n = 3 and m = 4, that is 12. (Programs with nested loops slow down quickly as the data grows; that idea, "efficiency", returns in the sorting unit.)

A number, digit by digit

Lab experiments 8 and 9 take a number apart. Two operations from unit 2 do it: n % 10 is the last digit, and n / 10 (integer division) removes it. A loop repeats until no digits are left.

#include <stdio.h>
 
int main(void)
{
    int n = 4567, rev = 0;
    while (n > 0) {
        int digit = n % 10;
        rev = rev * 10 + digit;
        n = n / 10;
    }
    printf("%d\n", rev);
    return 0;
}
nn % 10revn / 10
456777456
45667645
4557654
4476540
7654

rev = rev * 10 + digit builds the reversed number. For lab experiment 8 (is the number a palindrome, the same read from both sides?) keep a copy of the number before the loop changes n, and compare the copy with rev at the end: 1221 reversed is 1221.

Lab experiment 9: each digit, one more time

Lab experiment 9 prints the digits from the right, the first one once, the next one twice, and so on: 123 gives 322111, 4567 gives 7665554444. The outer loop walks the digits; an inner loop prints the current digit times times.

#include <stdio.h>
 
int main(void)
{
    int n = 123, times = 1;
    while (n > 0) {
        int digit = n % 10;
        for (int k = 0; k < times; k++) {
            printf("%d", digit);
        }
        times++;
        n = n / 10;
    }
    printf("\n");
    return 0;
}
322111
The outer loop takes 3, 2, 1; the inner loop prints each one more time than the last.לפתיחה במסך מלא

Team lab: the battery discharge sampler

The specification:

  1. Read at most 12 integer readings in millivolts.
  2. -1 stops the input immediately.
  3. 2500 to 4300 mV is valid, both boundaries included.
  4. Count invalid readings, but leave them out of the statistics.
  5. Print the valid count, the invalid count, the average, the minimum and the maximum. If there is no valid reading, print NO VALID DATA.

The plan: read at most 12 values (a for), stop on -1 (break), reject an invalid reading (invalid++ and continue), process a valid one (sum, count, min, max). The core loop:

for (int sample = 0; sample < 12; sample++) {
    scanf("%d", &mv);
    if (mv == -1)
        break;
    if (mv < 2500 || mv > 4300) {
        invalid++;
        continue;
    }
    sum += mv;
    valid++;
}

Your part (question 32): the first valid reading starts min and max, the average is printed with one decimal, and NO VALID DATA is printed when valid is 0.

Acceptance tests

Write the expected output before you run the program, then check every test:

testinputexpected output
boundary2500 4300 -1valid=2 invalid=0 avg=3400.0 min=2500 max=4300
both invalid2499 4301 -1NO VALID DATA
one invalid3000 5000 3200 -1valid=2 invalid=1 avg=3100.0 min=3000 max=3200
no data-1NO VALID DATA
limittwelve valid values 3000 3100 ... 4100, then 3500valid=12 invalid=0 avg=3550.0 min=3000 max=4100

In the limit test the loop stops after 12 readings, so the thirteenth value is never read.

Key words

EnglishHebrewMeaning
breakיציאה מהלולאהends the nearest loop now
continueדילוג לחזרה הבאהskips the rest of this iteration
nested loopsלולאות מקוננותa loop inside a loop
outer / inner loopלולאה חיצונית / פנימיתthe row loop / the column loop
early exitיציאה מוקדמתstopping before the limit
flow controlבקרת זרימהwhich line runs next
digitספרהn % 10 is the last one
palindromeפלינדרוםreads the same from both sides
acceptance testבדיקת קבלהan input and its expected output
boundary valueערך גבולtest 2500 and 4300 exactly

Practice

Answers and more questions: Practice: Loops.