23.3k views
5 votes
Write a program that asks the user to enter the size of a triangle (an integer from 1 to 50). Display the triangle by writing lines of asterisks. The first line will have one asterisk, the next two, and so on, with each line having one more asterisk than the previous line, up to the number entered by the user. On the next line write one fewer asterisk and continue by decreasing the number of asterisks by 1 for each successive line until only one asterisk in displayed. (Hint: Use nested loops; the outside loop controls the number of lines to write, and the inside loop controls the number of asterisks to display on a line. Complete the program by solving the upper triangle followed by the lower triangle.)

User Nordine
by
6.2k points

1 Answer

4 votes

Answer:

import java.util.Scanner;

public class num4 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int size;

do{

System.out.println("Enter size of triangle");

size = in.nextInt();

}while(size<=1 || size>=50);

for(int i = 1; i <= size; ++i) {

for(int j = 1; j <= i; ++j) {

System.out.print("* ");

}

System.out.println();

}

System.out.println();

//Second triangle bottom up

for(int i = size; i >= 1; --i) {

for(int j = 1; j <= i-1; ++j) {

System.out.print("* ");

}

System.out.println();

}

}

}

Step-by-step explanation:

  • Use Scanner class to receive user value for size
  • Use a do......while loop to ensure user entered a valid range (1-50)
  • Use nested loops to print the first triangle from i = 1
  • Print also the second triangle from i = size downwards
User DiaMaBo
by
6.8k points