# Thread: Need help understanding nested for loops

1. Member
Join Date
Feb 2015
Posts
1
Rep Power
0

## Need help understanding nested for loops

Java Code:
```// Demonstrate a two-dimensional array
class TwoDArray {
public static void main(String args[]) {
int twoD[] [] = new int[4] [5];
int i, j, k = 0;

for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}

for (i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i] [j] + " " );
System.out.println();
}
}
}```
Output:

0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

(1) I don't understand how repeating the loop creates the structure of the output. Taking the second loop away and putting the "System.out.print(twoD[i] [j] + " " );" under k++ creates the output to print a number on each line. How do I write the code not having the second loop, assigning k to each value that is moved through the grid then printing it out but having the output the same?

Java Code:
``` for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;

System.out.print(twoD[i] [j] + " " );
System.out.println();
}```

(2) I don't understand why you can't put a new line sandwiched between the first for loop

Java Code:
```for(i=0; i<4; i++)
System.out.println();
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;```
It compiles, but I get the message:

"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TwoDArray.main(TwoDArray.java:11)
"

Thank you for taking the time to read my problem and offering an explanation.

2. ## Re: Need help understanding nested for loops

One way to make the code more understandable is to use variable names that describe the values they hold. For example change the variable names i and j to row and column.
The printed output has 4 rows with 5 columns.

You should always use {}s to enclose the code that is inside of a for statement and several other statements like if and while so it is clear what statements are inside.
As you have shown, code without {}s leaves a trap for anyone that tries to change it.

#### Posting Permissions

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