Reputation:
code :
class test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt(); // input number rows & colums
int twoD[][] = new int[a][];
int z;
for (z = 0 ; z < a ; z++) {
twoD[z] = new int[z + 1];
}
int i,j,k = 0;
for (i = 0 ; i < a ; i++) {
for (j = 0 ; j <= i ; j++){
twoD[i][j] = k;
k++;
}
for (i = 0 ; i < a ; i++ ) {
for (j = 0 ; j <= i ; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
my expected output is ( for a = 4) :
0
1 2
3 4 5
6 7 8 9
my output is (for a = 4):
0
0 0
0 0 0
0 0 0 0
please help me fix my problem. according to me the lopping is correct. there might be mistake somewhere else...
Upvotes: 0
Views: 36
Reputation: 111239
The loop that prints the contents of the array is contained within the loop that is supposed to fill the 2D array with values. Since it uses the same variables, it interferes with the execution of the first loop. Move it out:
int i,j,k = 0;
for (i = 0 ; i < a ; i++) {
for (j = 0 ; j <= i ; j++){
twoD[i][j] = k;
k++;
}
}
for (i = 0 ; i < a ; i++ ) {
for (j = 0 ; j <= i ; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You could have avoided this by
for (int i = 0 ; i < a ; i++)
Upvotes: 1