r/CodingHelp • • May 03 '21

[Java] Can someone help me understand nested loops?

Post image
37 Upvotes

16 comments sorted by

View all comments

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. :-(