0

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!

alfred
  • 1
  • 3
  • 5
    The best way to learn is through doing. Try some stuff out and then post here with your problems. :) – abalos Aug 05 '14 at 16:06

1 Answers1

2

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();
        }
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
kirti
  • 4,499
  • 4
  • 31
  • 60
  • It's clear and accurate! But the variable "number" has no relationship with variables "i" and "j" in the for-loop. Why does it work? – alfred Aug 06 '14 at 16:08
  • number variable is initialized with 1 and then will increment by 1 with each parse and thus it prints no 1,2,3...10 in triangle – kirti Aug 06 '14 at 16:34