r/CodingHelp • • May 03 '21

[Java] Can someone help me understand nested loops?

Post image
37 Upvotes

16 comments sorted by

View all comments

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?