# 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

```java
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
```

?מה יודפס כאן

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

        int i = 10;
        for ( ; i > 5; i--) 
            System.out.print(i + ", ");
    }
}
```

```
10, 9, 8, 7, 6,
```

?מה יודפס כאן

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

        for (int i = 10; i < 20; i++) {
            System.out.print(i + ", ");
            i++;
        } // end of for
    }
}
```

```
10, 12, 14, 16, 18,
```

?מה יודפס כאן

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

        for (int i = 0; i < 10; i++) {
            if (i==3)
                continue;
            else if (i==6)
                break;
            System.out.print(i + ", ");
        } // end of for
    }
}
```

```
0, 1, 2, 4, 5,
```

**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! = 1 \cdot 2 \cdot3\cdot ... \cdot n \qquad and \qquad \sum \_{i=0}^{n}i=1+2+..+n
$$

example `n=4`

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

```java
public class Main {
    public static void main(String[] args) {
        int n = 5; // or enter from user
        int factorial = 1;

        for (int i = 1; i <= n; i++)
            factorial*=i;

        System.out.println(n + "! = " + factorial);

        int sum = 0;
        for (int i = 1; i <= n; i++)
            sum+=i;

        System.out.println("Summation of " + n + " = " + sum);
    }
}
```

```
5! = 120
Summation of 5 = 15
```

**version 2**

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

```java
public class Main {
    public static void main(String[] args) {
        int n;


        while ((n = MyConsole.readInt("enter num: "))!=-1){
            int factorial = 1;
            for (int i = 1; i <= n; i++)
                factorial*=i;

            System.out.println(n + "! = " + factorial);

            int sum = 0;
            for (int i = 1; i <= n; i++)
                sum+=i;

            System.out.println("Summation of " + n + " = " + sum);
        }

    }
}
```

```
enter num:  5
5! = 120
Summation of 5 = 15
enter num:  10
10! = 3628800
Summation of 10 = 55
enter num:  -1
```

## Question - Formula ⭐⭐

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

$$
(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)
$$

```java
public class Main {
    public static void main(String[] args) {
        int a = MyConsole.readInt("enter a: ");
        int b = MyConsole.readInt("enter b: ");
        int n = MyConsole.readInt("enter n: ");

        int sum = a;

        for (int i = 0; i < n; i++) {
            sum+=Math.pow(2,i)*b;
            System.out.println(sum);
        }
    }
}
```

```
enter a:  3
enter b:  5
enter n:  6
```

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

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

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

```java
public class Main{
    public static void main(String[] args) {
        int amount = MyConsole.readInt("enter loan amount: ");
        int original_amount = amount;

        for (int i = 1; i < 4; i++){
            System.out.println("month " + i + " payback: " + amount*.10);
            amount-= (amount * .10);
        }

        System.out.println("He still owes " + amount + " from the " + original_amount + " loan");
    }
}
```

```
enter loan amount:  5000
month 1 payback: 500.0
month 2 payback: 450.0
month 3 payback: 405.0
He still owes 3645 from the 5000 loan
```

## Catalan number ⭐⭐⭐

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

$$
C\_{n}={\frac {(2n)!}{(n+1)!,n!}}\qquad {\text{for }}n\geq 0.
$$

for example

$$
C\_{4}={\frac {(2 \cdot4)!}{(4+1)!,4!}}={\frac {(8)!}{(5)!,4!}} = 14
$$

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

![](https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/Catalan_number_4x4_grid_example.svg/450px-Catalan_number_4x4_grid_example.svg.png)

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

```java
public class Main{
    public static void main(String[] args) {
        int n = MyConsole.readInt("enter number: ");

        int numerator = 1;
        int denominator1 = 1;
        int denominator2 = 1;

        //numerator
        for (int i = 1; i <= n * 2; i++)
            numerator *= i;

        //denominator
        for (int i = 1; i <= n; i++)
            denominator1 *= i;

        denominator2 = denominator1*(n+1);

        int result = numerator/(denominator1*denominator2);
        System.out.println("C_"+ n + " = " + result);
    }
}
```

**version 2**

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

```java
public class Main{
    public static void main(String[] args) {
        int n = MyConsole.readInt("enter number: ");

        for (int each_c = 0; each_c <= n; each_c++) {
            int numerator = 1;
            int denominator1 = 1;
            int denominator2 = 1;

            //numerator
            for (int i = 1; i <= each_c * 2; i++)
                numerator *= i;

            //denominator
            for (int i = 1; i <= each_c; i++)
                denominator1 *= i;

            denominator2 = denominator1*(each_c+1);

            int result = numerator/(denominator1*denominator2);
            System.out.println("C_"+ each_c + " = " + result);
        }
    }
}
```

```java
enter number:  6
C_0 = 1
C_1 = 1
C_2 = 2
C_3 = 5
C_4 = 14
C_5 = 42
C_6 = 132
```

## Nested Loops

### Print stars ⭐⭐

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

example:

```
enter number:  4
*
**
***
****      <--- The height of the triangle is 4 stars
***
**
*
```

**code:**

```java
public class Main{
    public static void main(String[] args) {
        int n = MyConsole.readInt("enter number: ");

        //*
        //**
        //***
        //****
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <=i ; j++)
                System.out.print("*");
            System.out.println();
        }


        //***
        //**
        //*
        for (int i = n-1; i > 0; i--) {
            for (int j = i; j > 0 ; j--)
                System.out.print("*");
            System.out.println();
        }
    }
}
```

כתוב תוכנית אשר יציג את לוח הכפל (עד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 |

```java
public class Main{
    public static void main(String[] args) {
        for (int i = 1; i < 10; i++) {
            for (int j = 1; j < 10; j++)
                System.out.print(j + "x" + i +"=" +(i*j) +"\t");
            System.out.println();
        }
    }
}
```

```
1x1=1    2x1=2    3x1=3    4x1=4    5x1=5    6x1=6    7x1=7    8x1=8    9x1=9    
1x2=2    2x2=4    3x2=6    4x2=8    5x2=10    6x2=12    7x2=14    8x2=16    9x2=18    
1x3=3    2x3=6    3x3=9    4x3=12    5x3=15    6x3=18    7x3=21    8x3=24    9x3=27    
1x4=4    2x4=8    3x4=12    4x4=16    5x4=20    6x4=24    7x4=28    8x4=32    9x4=36    
1x5=5    2x5=10    3x5=15    4x5=20    5x5=25    6x5=30    7x5=35    8x5=40    9x5=45    
1x6=6    2x6=12    3x6=18    4x6=24    5x6=30    6x6=36    7x6=42    8x6=48    9x6=54    
1x7=7    2x7=14    3x7=21    4x7=28    5x7=35    6x7=42    7x7=49    8x7=56    9x7=63    
1x8=8    2x8=16    3x8=24    4x8=32    5x8=40    6x8=48    7x8=56    8x8=64    9x8=72    
1x9=9    2x9=18    3x9=27    4x9=36    5x9=45    6x9=54    7x9=63    8x9=72    9x9=81
```

> 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 }](https://wikimedia.org/api/rest_v1/media/math/render/svg/6a6236165aab16da0c5c8949b93e70c049f72402)

example:

$$
e^3  =20.0855369232
$$

if `accurray` or `n=12` we get

$$
e^3 = 1 + 3 + \frac{3^2}{2!} + \frac{3^3}{3!} + \frac{3^4}{4!} + .. + \frac{3^{12}}{12!} =20.0855369232
$$

```java
public class Main{
    public static void main(String[] args) {
        double e = 1;
        double x = MyConsole.readDouble("enter exponent: ");
        double accuracy = MyConsole.readDouble("enter accuracy: ");

        for (int n = 1; n <= accuracy; n++) {
            int factorial = 1;

            //find factorial
            for (int i = 1; i <= n; i++) {
                factorial*=i;
            } // end of inner for
            e += Math.pow(x, n)/factorial;
        } // end of outer for
        System.out.println("e^"+ x +" = " + e);
    }
}
```

```
enter exponent:  3
enter accuracy:  12
e^3.0 = 20.08521256087662
```

in the outer loop

```java
for (int n = 1; n <= accuracy; n++) {
            int factorial = 1;
```

each time we reset `factorial` to calculate the factorial

while the inner loop runs until `n` each time

```java
for (int n = 1; n <= accuracy; n++) {
            ...
            for (int i = 1; i <= n; i++) {
```

**version 2**

display each accuracy until n

```java
public class Main{
    public static void main(String[] args) {
        double e = 1;
        double x = MyConsole.readDouble("enter exponent: ");
        double accuracy = MyConsole.readDouble("enter accuracy: ");

        double real_value_of_e = 2.718281828459045;

        for (int i = 1; i <= accuracy; i++) {
            e = 1;

            for (int n = 1; n <= i; n++) {
                int factorial = 1;

                //factorial
                for (int j = 1; j <= n; j++) {
                    factorial*=j;
                } // end of inner for
                e += Math.pow(x, n)/factorial;
            } // end of middle for
            System.out.println("accuracy: "+ i + ", e^"+ (int)x +" = " + e + ", loss of: " + (real_value_of_e-e));
        } // end of outer for
    }
}
```

```
enter exponent:  1
enter accuracy:  10
accuracy: 1, e^1 = 2.0, loss of: 0.7182818284590451
accuracy: 2, e^1 = 2.5, loss of: 0.2182818284590451
accuracy: 3, e^1 = 2.6666666666666665, loss of: 0.05161516179237857
accuracy: 4, e^1 = 2.708333333333333, loss of: 0.009948495125712054
accuracy: 5, e^1 = 2.7166666666666663, loss of: 0.0016151617923787498
accuracy: 6, e^1 = 2.7180555555555554, loss of: 2.262729034896438E-4
accuracy: 7, e^1 = 2.7182539682539684, loss of: 2.7860205076724043E-5
accuracy: 8, e^1 = 2.71827876984127, loss of: 3.0586177750535626E-6
accuracy: 9, e^1 = 2.7182815255731922, loss of: 3.0288585284310443E-7
accuracy: 10, e^1 = 2.7182818011463845, loss of: 2.7312660577649694E-8
```

> 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 = m \cdot x+n
$$

![img](https://upload.wikimedia.org/wikipedia/commons/thumb/0/0e/Linear_Function_Graph.svg/300px-Linear_Function_Graph.svg.png)

```java
public class Main{
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int m = MyConsole.readInt("m = ");
        int n = MyConsole.readInt("n = ");
        for (int y = 10; y >= -10; y--) {
            for (int x = -10; x <= 10; x++) {
                if (y == m*x + n) {
                    System.out.print(" * ");
                }
                else if (y == 0 && x == 0){
                    System.out.print(" + ");
                }
                else if (x == 0) {
                    System.out.print(" | ");
                }
                else if (y == 0) {
                    System.out.print(" - ");
                }
                else {
                    System.out.print("   ");
                }
            }
            System.out.println();
        }

    }
}
```

```
m =  2
n =  3
                               |                               
                               |        *                      
                               |                               
                               |     *                         
                               |                               
                               |  *                            
                               |                               
                               *                               
                               |                               
                            *  |                               
 -  -  -  -  -  -  -  -  -  -  +  -  -  -  -  -  -  -  -  -  - 
                         *     |                               
                               |                               
                      *        |                               
                               |                               
                   *           |                               
                               |                               
                *              |                               
                               |                               
             *                 |                               
                               |
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nissan-goldberg.gitbook.io/java101/lesson-3-for-loops/untitled.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
