0

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

1
  • Have you tried using a debugger and step through it, evaluating the current values? Commented Apr 7, 2020 at 21:03

1 Answer 1

1

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++)
Sign up to request clarification or add additional context in comments.

2 Comments

Ok so are you trying to say that if it is one line code in for loop do not create blocks "{}". Please clarify my doubt i am beginner.
yes one of the closing } is in the wrong place, making the second double for loop go inside the first one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.