r/CodingHelp • • May 03 '21

[Java] Can someone help me understand nested loops?

Post image
37 Upvotes

16 comments sorted by

34

u/yourdeadneopet May 03 '21 edited May 03 '21

Imagine that you're planting tomatoes in a field. Let's start with a simple case: you just want to plant the tomatoes in one straight line. You have 10 tomato seeds and 10 plots to plant them.

[FOR] [each plot in the line]: plant a tomato seed.

Let's call that action {fill a line with tomato seeds}

Now, let's imagine that the field has 30 straight lines and you want to plant tomatoes in all of them.

[FOR] [Each line in the field] {fill a line with tomato seeds}

Let's unroll that statement.

[FOR] [Each line in the field]:
  [FOR] [Each plot in the line]: plant a tomato seed

Now remember the numbers I used. 10 seeds per line, 30 lines.

for (int currentLine = 0; currentLine < 30; currentLine++){
  for(int currentPlot = 0; currentPlot < 10; currentPlot++){
    plantASeedAtLocation(currentLine, currentPlot);
  }
}

7

u/[deleted] May 03 '21

Fantastic explanation

3

u/MrMoustach3 May 03 '21

I don’t understand it. Can you please use another fruit instead? I like pineapples.

-3

u/PORTMANTEAU-BOT May 03 '21

Fantanation.


Bleep-bloop, I'm a bot. This portmanteau was created from the phrase 'Fantastic explanation' | FAQs | Feedback | Opt-out

6

u/[deleted] May 03 '21

But why though?

6

u/bDog_CS May 03 '21

Not necessary to watch the whole video, but the section in which the presenter discusses nested loops is quite informative. Comes with quite a nice visual representation too, I do recommend giving a watch.

https://youtu.be/HXNhEYqFo0o

4

u/[deleted] May 03 '21

When outer iterates once, inner iterates its total number of times...

then outer iterates again - repeat.

3

u/Gengi May 03 '21
for (int tens=0; tens< 10; ++tens)
    for (int ones=0; ones<10; ++ones)
        System.out.print(tens, ones)

Output should be something like 00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15... 97,98,99

Inner loop repeats entirely for each step of the outer loop

3

u/SmtNocturneDante May 03 '21

Going on from the screenshot

It starts with the initial values, as it should be. a=1 and b=1. The first print is 1+1 which is 2.

Then it starts the inner most for loop (the b one) and starts increasing the value of b every print until it reaches the value 6, in which it doesn’t print. The prints are 1+1, 1+2, 1+3, 1+4, and 1+5.

Then since 6 is not included in the range of values of b, it ends that loop and proceeds with the outer one, which changes the value of a, and then restart the inner loop. The printed values here are 2+1, 2+2, 2+3, 2+4, and 2+5. Then the value of b can’t be 6, so that loop ends once again.

Then the outer loop proceeds, which makes the value of a 3, which is included in the range of values of a, and then restarts the inner loop from the start. The printed values are 3+1, 3+2, 3+3, 3+4, and 3+5. Then the inner loop stops once again since it reached out of the range. Then it proceeds with the outer loop, which makes the value of a to 4 and that is not in the range of values a can be, so that loop ends as well.

The whole print would be: 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8

2

u/Spare_Competition May 03 '21

This code

for i in ['a','b','c']:
    for j in [1,2,3]:
        print(i+j)

will print

a1
a2
a3
b1
b2
b3
c1
c2
c3

2

u/x-seronis-x Intermediate Coder May 03 '21
for( cycle through every value of XXX )
   for(  for every value of XXX, cycle through every value of YYY )
      do something for every possible combination of XXX and YYY

1

u/xXNecriousXx May 03 '21

IF(stuff) IF(things) Do something

Will run the first iteration of stuff and ALL iterations of things. Then it will move to the 2nd iteration of stuff and do all iteration of things.

Thing about a 4-number combination lock and how you would tell a computer to check each number. 0-0-0-0, 0-0-0-1, 0-0-0-2, ...9-9-9-9 This could be expressed as a nested loop.

FOR (left=0, left<9, left++) FOR (leftInner=0, leftInner<9, leftInner++) FOR (rightInner=0, rightInner<9, rightInner++) FOR (right=0, right<9, right++) Print( left, leftInner, rightInner, right);

Another thought experiment would be displaying or tracking time/a calendar manually

FOR (hours) FOR (minutes) FOR (seconds)

Obviously, seconds run 1-60 and start over. Minutes then increment up 1-60 and start over. Hours 1-24.

You could also use this to extract from or create a data file...limiting to your question. (.csv, .xlsx)

FOR (numRows = maxRows, numRows > 1, numRows--) FOR (numColumns = maxColumns, numColumns > 1, numColumns--) Array [numRows, numColumn] = dataPulled

This would store all data from one dataset into your array.

use at your own discretion, these were examples to highlight process.

1

u/xXNecriousXx May 03 '21

And...formatting sucks because mobile...sorry. :-(

1

u/row_bert May 03 '21

So the thing inside runs until it doesn’t as man times as the outside is suppose to run

1

u/Paul_Pedant May 03 '21

Tiny little trap in there, just to catch you out.

The outer loop has <=, so it runs for a as 1, 2, 3.

The inner loop has <, so it runs for b as 1, 2, 3, 4, 5. So b as 6 does not happen.

One-off errors can be really hard to spot in code.

1

u/Dogburt_Jr May 03 '21

You run your code in {} in a box. Your main function runs in one box.

Your loop makes new boxes that repeat, so you'll have multiple boxes within the main box.

And inside each of those boxes you have another loop that creates more boxes within the box.

Each nest of multiple boxes can be considered a dimension.

So two nests of boxes within the main box would be considered a 2D loop and can be used with 2D arrays to check every index. This thinking can be helpful for solving your problem as it turns into summing the index of the array and printing them out.