0
Hello, I'm a java newbie, Any one kindly explain for loops?
I'm certain that i understand how 1 for loop works on its own but when theres 2 like the following for (int i=0; i<5; i++){ for (int j=0; j<=i; j++) System.out.print("*"); System.out.println(""); } } } I dont understand it is there an easy way to remember?
9 ответов
+ 5
The running goes like this: first loop runs 5 times, second loop runs i+1 times each time (j turn 0 each run of the first loop), which means each time:
1. i=0: j=0 one run
2. i=1: j=0, j=1 two runs
3. i=2: j=0, j=1, j=2 three runs
4. i=3: j=0, j=1, j=2, j=3 four runs
5. i=4: j=0, j=1, j=2, j=3, j=4 five runs
got it?
+ 2
The terms of these for loops are simple: the first loop runs five times, each time the second loop runs i+1 times , according to the first loop's index
+ 2
Rheina, not really a duplicate question if the other question is on a completely different source
+ 2
Technically yes
+ 1
that went over my head 😅
Any simpler terms please rheina?
i did get that this is a nested loop.
0
@jordan or Ziv so the first loop completes 1 loop, moves to the next loop which always fully completes loops what ever the condition is then prints and moves back to the first loop always completing the second loop?
so first loop only loops once before reaching the second loop and prints nothing
second loop fully completes what ever the condion is and prints all?
thanks
0
got it thanks
0
so the outer loop 1, stores the increments on each loop until the condition is false
the nested inner loop 2, stores the increment untill conditions are false with loop 1 and resets going back to the outer loop 1 again
does that sound right? sorry im still learning what things are called
0
thanks Ziv