# Nested for loop explanation

Printable View

• 06-21-2012, 02:42 AM
Bgreen7887
Nested for loop explanation
Can anyone offer an explanation this multiplication table. I tried to work it out with pen and paper and can't even do that. If ran through first 2 runs,
1: it would evaluate to a[0][0] = 1*1;
2: it would evaluate to a[1][1] = 2*2;

shouldn't it instead go through each row populate it and so on?

Code:

```int rows = 10; int cols = 10; int[][] arr = new int[rows][cols]; for (int i = 0; i < rows; i++){         for (int j = 0; j < cols; j++){                 arr[i][j] = (i+1)*(j+1);                 System.out.print(arr[i][j] + " ");         }         System.out.println(); }```
• 06-21-2012, 03:19 AM
Tha Boss
Re: Nested for loop explanation
A for loop basically runs a block of code as long as it's counter "i" and "j" in your case is true to a defined range.
So your outer for loop will run the block of code within it until the "i" is out of it's defined range.. (which happens to be another for loop). Therefore this "nested" for loop will run it's block of code until the "j" is out of it's defined range. In your case, the result is.. "j" will count from 0 to 10 every time you add 1 to "i" which counts to 10 also; when the outer loop is broken (due to "i" being more than or = 10) neither loop will run.
- CHEERS!

Quote:

"If you fall... don't give up... get up and try harder."
- Daruma Daishi.
• 06-21-2012, 03:49 AM
Bgreen7887
Re: Nested for loop explanation
Thank you for a good explanation, i believe i fully understand it now. so as it stands the inner for loop actually builds the columns 1-10, then the outer loop increment to row 2, which then builds the second column.
• 06-21-2012, 05:17 AM
Tha Boss
Re: Nested for loop explanation
You got it..:(nod): so by switching the for loops, you can choose to populate all the columns first before moving on to the next row, or whatever you want..