נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
5
חלקPart 1: יסודותFoundations כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

לולאותLoops

for, while, do-while ו-for-each, break ו-continue, לולאות מקוננות ומעקב אחרי משתני לולאה.

for, while, do-while and for-each, break and continue, nested loops and tracing loop variables.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • לולאה: קוד שחוזר שוב ושוב: for, while, do-while ו-for-each.loop: Code that repeats: for, while, do-while and for-each.
  • סיבוב (איטרציה): פעם אחת שבה גוף הלולאה רץ.iteration: One time the loop body runs.
  • מונה: משתנה שסופר את הסיבובים, בדרך כלל i: מתחיל, נבדק בתנאי, ועולה בסוף כל סיבוב.counter: A variable that counts the rounds, usually i: it starts, is checked by the condition, and goes up at the end of each round.
  • צובר: משתנה שאוסף תוצאה לאורך הלולאה, כמו sum += i. מאתחלים אותו לפני הלולאה.accumulator: A variable that gathers a result through the loop, like sum += i. Initialize it before the loop.
  • for-each: for (char c : s.toCharArray()): עובר על כל פריט, בלי מונה.for-each: for (char c : s.toCharArray()): goes over every item, with no counter.
  • לולאה מקוננת: לולאה בתוך לולאה: על כל סיבוב של החיצונית, הפנימית רצה מההתחלה עד הסוף.nested loop: A loop inside a loop: for each round of the outer one, the inner one runs from start to finish.
  • טעות של אחד (off-by-one): לולאה שרצה פעם אחת יותר מדי או פחות מדי, לרוב בגלל < במקום <= או התחלה מ-1 במקום מ-0.off-by-one: A loop that runs one time too many or too few, usually from < instead of <= or starting at 1 instead of 0.
  • לולאה אינסופית: לולאה שהתנאי שלה אף פעם לא נהיה false, למשל כששוכחים לשנות את המונה.infinite loop: A loop whose condition never becomes false, for example when you forget to change the counter.

02לולאת forThe for loop

שלושה חלקים בסוגריים: התחלה (int i = 1), תנאי להמשך (i <= 3), ושינוי בסוף כל סיבוב (i++). צפו בסימולציה איך i עולה, ואיך שורת ה-for נבדקת שוב בכל סיבוב.

Three parts in the brackets: a start (int i = 1), a condition to keep going (i <= 3), and a change at the end of each round (i++). Watch in the simulation how i goes up, and how the for line is checked again each round.

Main.java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("סיבוב " + i);
        }
        System.out.println("סוף");
    }
}
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Round " + i);
        }
        System.out.println("Done");
    }
}
פלטOutput
סיבוב 1
סיבוב 2
סיבוב 3
סוף
Round 1
Round 2
Round 3
Done
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03צובר: סכום בתוך לולאהAn accumulator: a sum in a loop

צובר מתחיל לפני הלולאה, ובכל סיבוב מוסיפים לו. בסוף הוא מחזיק את התוצאה.

An accumulator starts before the loop, and each round adds to it. At the end it holds the result.

Main.java
public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 4; i++) {
            sum += i;
        }
        System.out.println(sum);
    }
}
פלטOutput
10
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04while ו-do-whilewhile and do-while

while בודק לפני כל סיבוב, ומתאים כשלא יודעים כמה סיבובים יהיו. do-while בודק בסוף, ולכן רץ לפחות פעם אחת. שכחתם לשנות את המשתנה? זו לולאה אינסופית.

while checks before every round, and suits cases where you don't know how many rounds there'll be. do-while checks at the end, so it runs at least once. Forgot to change the variable? That's an infinite loop.

Main.java
public class Main {
    public static void main(String[] args) {
        int n = 20;
        int steps = 0;
        while (n > 1) {
            n = n / 2;
            steps++;
        }
        System.out.println(steps);
        int k = 10;
        do {
            System.out.println("פעם אחת לפחות");
        } while (k < 5);
    }
}
public class Main {
    public static void main(String[] args) {
        int n = 20;
        int steps = 0;
        while (n > 1) {
            n = n / 2;
            steps++;
        }
        System.out.println(steps);
        int k = 10;
        do {
            System.out.println("at least once");
        } while (k < 5);
    }
}
פלטOutput
4
פעם אחת לפחות
4
at least once
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05for-each, break ו-continuefor-each, break and continue

for-each עובר על כל פריט. continue מדלג לסיבוב הבא, ו-break יוצא מהלולאה מיד.

for-each goes over every item. continue skips to the next round, and break leaves the loop at once.

Main.java
public class Main {
    public static void main(String[] args) {
        for (char c : "ja-va!".toCharArray()) {
            if (c == '-') {
                continue;
            }
            if (c == '!') {
                break;
            }
            System.out.print(c);
        }
        System.out.println();
    }
}
פלטOutput
java
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06לולאות מקוננותNested loops

על כל סיבוב של הלולאה החיצונית, הפנימית רצה מההתחלה. כך בונים טבלאות וצורות.

For every round of the outer loop, the inner one runs from the start. That's how tables and shapes are built.

Main.java
public class Main {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
פלטOutput
*
**
***
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

07הצעד של היום בפרויקט מדףToday's step in the Shelf project

במחרוזת books יש שמות של 3 ספרים מופרדים ב-;: "Dune;Emma;Ulysses". עברו עליהם (books.split(";") נותן אותם אחד-אחד; מערכים נלמד במפגש 8) והדפיסו רשימה ממוספרת 1. Dune וכן הלאה, ובסוף 3 books.

books holds 3 titles separated by ;: "Dune;Emma;Ulysses". Go over them (books.split(";") hands them out one by one; arrays come in session 8) and print a numbered list 1. Dune and so on, then 3 books at the end.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich