for loops

This weeks lesson will cover:

  • break and continue

  • for loops

  • nested loops

⭐ - is difficulty of question

for loops

Simple for examples ⭐

הדפס מספרים 0 עד 3

public class Main {
    public static void main(String[] args) {

        for (int i = 0; i < 4; i++) {
            System.out.println(i);
        } // end of for
    }
}
0
1
2
3

?מה יודפס כאן

?מה יודפס כאן

?מה יודפס כאן

explanation

  • the keyword continue will continue to the next number in the loop

  • the keyword break will exit the loop altogether.

Factorial and Sum of values ⭐⭐

חשב עצרת וסכום עבור n

n!=123...nandi=0ni=1+2+..+nn! = 1 \cdot 2 \cdot3\cdot ... \cdot n \qquad and \qquad \sum _{i=0}^{n}i=1+2+..+n

example n=4

4!=1234=24andi=04i=1+2+3+4=104! = 1 \cdot 2 \cdot3\cdot 4=24 \qquad and \qquad \sum _{i=0}^{4}i=1+2+3+4=10

version 2

חשב את הערך של n עד שמקבלים -1

Question - Formula ⭐⭐

תקודדו את הנוסחה הבא:

(a+20b),(a+20b+21b),..,,(a+20b+21b+...+2n1b)(a+2 ^0\cdot b),(a+2 ^0\cdot b+2 ^1\cdot b),..,,(a+2 ^0\cdot b+2 ^1\cdot b+...+2 ^{n-1}\cdot b)

הלוואה מבנק ⭐⭐

פלוני לקח הלוואה מהבנק ומחזיר 10 אחוז מהלוואה כל חודש הדפיסו

  • כמה כסף הוא מחזיר כל חודש

  • כמה הוא עדיין חייב אחרי 3 חודשים מאז שהוא התחיל לפרוע בחזרה

Catalan number ⭐⭐⭐

חשב את מספר קלטן n

Cn=(2n)!(n+1)!n!for n0.C_{n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\text{for }}n\geq 0.

for example

C4=(24)!(4+1)!4!=(8)!(5)!4!=14C_{4}={\frac {(2 \cdot4)!}{(4+1)!\,4!}}={\frac {(8)!}{(5)!\,4!}} = 14

?מה זה מספר קלטן

זהו מספר האפשריות לניתן להגיע מפינה השמאלית למטה לפינה הימנית למעלה בלי לחצות את הקו וללכת רק ימינה ולמעלה

version 2

עכשיו תתדפיסו את כל המספרי קלטן עד n

Nested Loops

כתבו תוכנית אשר ידפיס משולש כוכבים עד גובה n

example:

code:

כתוב תוכנית אשר יציג את לוח הכפל (עד10)

1x1 = 1

2x1 = 2

3x1 = 3

4x1 = 4

5x1 = 5

6x1 = 6

7x1 = 7

8x1 = 8

1x2 = 2

2x2 = 4

3x2 = 3

4x2 = 8

5x2 = 10

6x2 = 12

7x2 = 14

8x2 = 16

1x10 = 10

2x10 = 20

3x10 = 30

4x10 = 40

5x10 = 50

6x10 = 60

7x10 = 70

8x10 = 80

Later on we will use more nested loops for accessing multi-dimension arrays

e^x ⭐⭐⭐⭐

compute e^x using the following formula:

{\displaystyle e^{x}=\sum _{n=0}^{\infty }{\frac {x^{n}}{n!}}=1+x+{\frac {x^{2}}{2!}}+{\frac {x^{3}}{3!}}+\cdots }

example:

e3=20.0855369232e^3 =20.0855369232

if accurray or n=12 we get

e3=1+3+322!+333!+344!+..+31212!=20.0855369232e^3 = 1 + 3 + \frac{3^2}{2!} + \frac{3^3}{3!} + \frac{3^4}{4!} + .. + \frac{3^{12}}{12!} =20.0855369232

in the outer loop

each time we reset factorial to calculate the factorial

while the inner loop runs until n each time

version 2

display each accuracy until n

think how large 12! is its 479,001,600

Remember than e = 2.718281828459045 which isn't bad at all, each time we are accurate by one decimal

Graph ⭐⭐

תכתבו תוכנית אשר מקבלת 2 מספרים שלמים m וn

ומדפיסה בטרמינל את הישר שלהם על גרף בין 10 למינוס 10 בציר הx והציר הy

y=mx+ny = m \cdot x+n
img

Last updated

Was this helpful?