user11385192
user11385192

Reputation:

java 2D integer array looping wrong output

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

Answers (1)

Joni
Joni

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

  • using and editor or IDE that automatically formats your code, so that is shows you how the control structures are nested
  • using common idioms like declaring the loop variables with the smallest necessary scope:
for (int i = 0 ; i < a ; i++)

Upvotes: 1

Related Questions