# Thread: Nested for loop explanation

1. Senior Member
Join Date
Oct 2010
Location
Newark,nj
Posts
111
Rep Power
0

## 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?

Java 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();
}```

2. Member
Join Date
Jun 2012
Location
Posts
25
Rep Power
0

## 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!

"If you fall... don't give up... get up and try harder."
- Daruma Daishi.
Last edited by Tha Boss; 06-21-2012 at 03:22 AM.

3. Senior Member
Join Date
Oct 2010
Location
Newark,nj
Posts
111
Rep Power
0

## 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.

4. Member
Join Date
Jun 2012
Location
Posts
25
Rep Power
0

## Re: Nested for loop explanation

You got it.. 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..
Last edited by Tha Boss; 06-21-2012 at 05:27 AM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•