I am stuck one one task and I need some help. This is the code I already wrote:
int [][] arr = new int [5][5];
for(int val = 1; val<=5;val++){
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
arr[i][j] = val;
}
}
}
for(int k = 0; k < 5; k++){
for(int l = 0; l < 5; l++){
System.out.print(arr[k][l] + " ");
}
System.out.println();
}
The out put is only:
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
The out put should look ike this:
1 2 3 4 5
6 7 8 9 10
...and so on 25
>Solution :
You dont need 3 loops, 2 are enough to populate the array.
public class MyClass {
public static void main(String args[]) {
int [][] arr = new int [5][5];
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
arr[i][j] = (i * 5) + (j + 1);
}
}
for(int k = 0; k < 5; k++){
for(int l = 0; l < 5; l++){
System.out.print(arr[k][l] + " ");
}
System.out.println();
}
}
}
prints
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25