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

I would like to continue working on using ArrayLists and Nested Loops, so I thought about the next interesting problem.

The number of lines is specialized by the user, and something will look like this:

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

Can someone give me some tips to resolve this issue? Thanks in advance!

0
source share
1 answer

My first forloop is for creating triangle lines, and the second for creating coloumns.

For each line, print the first value, followed by spaces.

coloumns . coloumn

.

import java.util.Scanner;
class TriangleExample
{
    public static void main(String args[])
    {
        int rows, number = 1, counter, j;
        //To get the user 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();
        }
    }
}
+2

All Articles