Question:
How to create and print a triangular array in java?
Code:
import java.util.*; public class TriangularArray { public static void main(String[] args) { int[][] triangle = arraytriangle(5); System.out.println(Arrays.deepToString(triangle)); } public static int[][] arraytriangle(int lines){ int[][] tri = new int[lines][]; int x = 1; for (int i = 0; i < lines; i++){ tri[i] = new int[i+1]; for (int j = 0; j <= i; j++){ tri[i][j] = x; System.out.print(x + " "); x++; } System.out.println(); } return tri; } }
Output:
$ java TriangularArray 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]