Loops: while, for, and accumulation · לולאות: while, for ואיסוף
Loops
- A loop repeats a block of code many times.
- Loops let you count, add up numbers, and do work without copying lines.
- In this lesson you learn the
whileloop and theforloop.
לולאות
- לולאה מבצעת חזרה על בלוק קוד מספר רב של פעמים.
- לולאות מאפשרות לספור, לחבר מספרים ולבצע עבודה ללא צורך בהעתקת שורות.
- בשיעור זה תלמדו על לולאת
whileולולאתfor.
The while loop
- A
whileloop runs its block again and again while a condition istrue. - You need three parts: start a counter, test it, and change it inside the loop.
- If you never change the counter, the loop runs forever. Be careful.
לולאת while
- לולאת
whileמבצעת את הבלוק שלה שוב ושוב כל עוד התנאי הואtrue. - יש צורך בשלושה חלקים: התחלת סופר, בדיקה שלו, ושינוי בתוך הלולאה.
- אם לעולם אינך משנה את הסופר, הלולאה תפעל לנצח. היזהר.
public class Main {
public static void main(String[] args) {
int i = 1; // start
while (i <= 3) { // test
System.out.println("Line " + i);
i = i + 1; // change
}
}
}
The for loop
- A
forloop puts the start, test, and change on one line. - The shape is
for (start; test; change) { ... }. - It does the same job as the
whileabove, but it is shorter and clearer.
לולאת for
- לולאת
forכוללת את ההתחלה, הבדיקה והשינוי בשורה אחת. - הצורה היא
for (start; test; change) { ... }. - היא עושה אותו עבודה כמו לולאת
whileלמעלה, אך קצרה ומובהרת יותר.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("Line " + i);
}
}
}
Accumulation
- Accumulation means building up an answer step by step inside a loop.
- Use a variable that starts at
0and grows:sum = sum + i;. i++is a short way to writei = i + 1.sum += iis short forsum = sum + i.
הצטברות
- הצטברות פירוניה בניית תשובה צעד אחר צעד בתוך לולאה.
- השתמש במשתנה שמתחיל ב-
0וגדל:sum = sum + i;. i++היא דרך קצרה לכתובi = i + 1.sum += iהוא קיצור עבורsum = sum + i.
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i; // add each number
}
System.out.println(sum); // 15
}
}
Counting with a condition
- You can count how many times something is true.
- Start a counter at
0, and add1only when the test passes. - Here we count even numbers from 1 to 10.
ספירה עם תנאי
- ניתן לספור כמה פעמים משהו מתקיים.
- התחל סופר ב-
0, והוסף1רק כאשר המבחן עובר. - כאן אנו סופרים מספרים זוגיים מ-1 עד 10.
public class Main {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) { // % gives the remainder
count++;
}
}
System.out.println(count); // 5
}
}
Off-by-one care
- The most common loop bug is doing one too many or one too few steps.
i <= nincludesn.i < nstops beforen.- To loop from 1 to
n(and includen), usefor (int i = 1; i <= n; i++).
זהירות בשגיאת אי-התאמה
- השגיאה הנפוצה ביותר במחזור היא ביצוע שלב אחד יותר או שלב אחד פחות.
i <= nכולל אתn.i < nנעצר לפניn.- כדי לLoop מ-1 עד
n(ולכלול אתn), השתמש ב-for (int i = 1; i <= n; i++).
public class Main {
public static void main(String[] args) {
int n = 4;
// i goes 1, 2, 3, 4 — four times, because of <=
for (int i = 1; i <= n; i++) {
System.out.println(i);
}
}
}
Common mistakes
for (int i = 0; i < n; i++)runsntimes;<=runs one extra.- Do not put a
;right afterfor(...).
טעויות נפוצות
for (int i = 0; i < n; i++)רץnפעמים;<=רץ פעם נוספת.- אל תשים
;ישר אחריfor(...).
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
כעת תנסו בעצמכם
- כל משימה ממלאת מראש את שלד המחלקה — כתוב את הקוד שלך בתוך main, או השלם את השיטה המוצגת.
- לחץ על Run כדי להרכיב ולהריץ, ולאחר מכן לחץ על Check answer.
- הקוד שלך נרכב ונרץ על השרת, ולכן גם ההפעלה הראשונה היא מהירה.
Loops and accumulation · לולאות ואיסוף
A loop repeats; an accumulator builds up across the passes. · לולאה חוזרת; אוסף (accumulator) בונה ערך בהדרגה לאורך הפסגות.
Use a for loop to print the numbers 1 to 5, each on its own line. · השתמשו בלולאת for כדי להדפיס את המספרים 1 עד 5, כל אחד בשורה משלו.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete sumTo(int n) so it returns the sum 1 + 2 + ... + n. For example sumTo(5) is 15. If n is 0 or less, return 0. · השלימו את sumTo(int n) כך שתחזיר את הסכום 1 + 2 + ... + n. לדוגמה, עבור sumTo(5) התוצאה היא 15. אם n הוא 0 או פחות, החזירו 0.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete countMultiples(int n, int k) so it returns how many numbers from 1 to n divide evenly by k (use % == 0). For example countMultiples(10, 3) is 3 (that is 3, 6, 9). · השלם countMultiples(int n, int k) כך שיתחזיר כמה מספרים מ-1 ועד n מתחלקים במספר k ללא שארית (השתמש ב-% == 0). לדוגמה, עבור countMultiples(10, 3) התוצאה היא 3 (כלומר 3, 6, 9).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.