Search code examples
javaarraylistnested-loops

How to print a triangle of integers with number of lines specified by the user?


I would like to further exercise myself on the use of ArrayLists and Nested Loops, so I thought of the following interesting problem.

The number of lines is specialized by the user and something would come out like this:

Enter a number: 5
1
2      3
4      5      6
7      8      9      10
11     12     13     14     15

Can anybody give me some advice for doing this question? Thanks in advance!


Solution

  • My first forloop is for creating rows of triangle and second is for creating coloumns.

    For each row, you need to print first value and then spaces.

    The number of spaces should decrease by one per row and in coloumns no. of space will increase by one per coloumn

    For the centered output, increase the number of stars by two for each row.

    import java.util.Scanner;
    class TriangleExample
    {
        public static void main(String args[])
        {
            int rows, number = 1, counter, j;
            //To get the user's input
            Scanner input = new Scanner(System.in);
            //take the no of rows wanted in triangle
            System.out.println("Enter the number of rows for  triangle:");
            //Copying user input into an integer variable named rows
            rows = input.nextInt();
            System.out.println(" triangle");
            System.out.println("****************");
            //start a loog counting from the first row and the loop will go till the entered row no.
            for ( counter = 1 ; counter <= rows ; counter++ )
            {
                //second loop will increment the coloumn 
                for ( j = 1 ; j <= counter ; j++ )
                {
                    System.out.print(number+" ");
                    //Incrementing the number value
                    number++;
                }
                //For new line
                System.out.println();
            }
        }
    }