Eli Robbins
Eli Robbins

Reputation: 1

creating and printing a triangular array in java

here's my code:

public static int[][] arraytriangle(int lines){

    int[][] tri = new int[lines][];
    int c = 1; // incremented number to use as filler
    for (int i = 0; i < lines; i++){
        for (int j = 0; j <= i; j++){
        tri[i] = new int[i+1]; // defines number of columns
            tri[i][j] = c;
            System.out.print(c + " ");
            c++; // increment counter
        }
        System.out.println(); // making new line
    }
    System.out.println(Arrays.deepToString(tri));
    return tri;

arraytriangle(3) gives:

1

2 3

4 5 6

[[1], [0, 3], [0, 0, 6]]

So the program is printing correctly (the 1,2,3...), but the matrix values are not correct when I use deepToString. What gives?

Upvotes: 0

Views: 9419

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

This assignment

tri[i] = new int[i+1];

has to happen inside the outer loop but outside the inner loop. Currently, your inner loop keeps re-assigning tri[i], so only the last item remains assigned for deepToString.

Upvotes: 5

Related Questions