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:
| i | value | value == -1 | sum |
|---|---|---|---|
| 0 | 4 | false | 4 |
| 1 | 7 | false | 11 |
| 2 | -1 | true | break |
sum=11The sentinel is not added, and 9 is never read by this loop.
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:
| i | value | then | sum | valid |
|---|---|---|---|---|
| 0 | 4 | add | 4 | 1 |
| 1 | -2 | skip | 4 | 1 |
| 2 | 7 | add | 11 | 2 |
| 3 | -1 | skip | 11 | 2 |
| 4 | 3 | add | 14 | 3 |
| 5 | 5 | add | 19 | 4 |
sum=19 valid=4Here -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?
| break | continue | |
|---|---|---|
| what it does | ends the nearest loop | skips to the next iteration |
| use it for | an early stop: a sentinel, a target found | rejecting one item: an invalid reading |
with 4 -2 7 -1 3 5 and if (value < 0) | sum = 4 | sum = 19 |
Only break changes how many iterations will still run.
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.
Trace: nested loops
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i * j);
}
printf("\n");
}| i | j | i * j |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 2 |
| 1 | 3 | 3 |
| 2 | 1 | 2 |
| 2 | 2 | 4 |
| 2 | 3 | 6 |
1 2 3
2 4 6Trace 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;
}| n | n % 10 | rev | n / 10 |
|---|---|---|---|
| 4567 | 7 | 7 | 456 |
| 456 | 6 | 76 | 45 |
| 45 | 5 | 765 | 4 |
| 4 | 4 | 7654 | 0 |
7654rev = 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;
}322111Team lab: the battery discharge sampler
The specification:
- Read at most 12 integer readings in millivolts.
-1stops the input immediately.- 2500 to 4300 mV is valid, both boundaries included.
- Count invalid readings, but leave them out of the statistics.
- 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:
| test | input | expected output |
|---|---|---|
| boundary | 2500 4300 -1 | valid=2 invalid=0 avg=3400.0 min=2500 max=4300 |
| both invalid | 2499 4301 -1 | NO VALID DATA |
| one invalid | 3000 5000 3200 -1 | valid=2 invalid=1 avg=3100.0 min=3000 max=3200 |
| no data | -1 | NO VALID DATA |
| limit | twelve valid values 3000 3100 ... 4100, then 3500 | valid=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
| English | Hebrew | Meaning |
|---|---|---|
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.