-2

I dont understand, why these numbers are printed out. Shouldn't it just out print 3 2 1? Instead, it prints: 3 0 0 0 2 0 0 0 1

Thank you for your help :)

public static void main(String[] args) {

    int i, j, n = 3;

    int[][] polje = new int[n][n];

    polje[0][0] = 3;
    polje[1][1] = 2;
    polje[2][2] = 1;

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            System.out.print(polje[i][j] + " ");
            System.out.println();
        }
    }

}
Damodaran
  • 10,882
  • 10
  • 60
  • 81
energetics
  • 25
  • 4
  • 2
    You have created a 2D array, basically a square of numbers with three rows and three columns. You have assigned numbers to three positions in this square; the other 6 positions are zero. – khelwood Nov 30 '15 at 11:45

1 Answers1

0

you have set likewise,

3 0 0
0 2 0
0 0 1

so obviously you get, 3 0 0 0 2 0 0 0 1

if you want to print only 3 2 1 then made this changes only,

if(i == j){
   System.out.print(polje[i][j] + " ");
    System.out.println();
}
Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55