9.2k views
5 votes
Write a program that asks the user to enter the size of a triangle (an integer from 1 to 50) and validate this input. Make sure that your program loops until it receives valid input. Display the triangle by displaying lines of asterisks.

User Petar
by
4.0k points

1 Answer

6 votes

Answer:

import java.util.Scanner;

public class num1 {

public static void main(String[] args) {

Scanner in = new Scanner (System.in);

int size;

do{

System.out.println("Enter the size of the traingle");

size = in.nextInt();

}while (size > 50);

//Using nexted for loop to print the triangle

for(int i=0; i<size; i++)

{

for(int j=0; j<=i; j++)

{

System.out.print("* ");

}

System.out.println();

}

}

}

Step-by-step explanation:

Use Scanner class to receive user input

Validate using a do while statement while(num>50) keep prompting the user for a valid input

Use nexted for loops to print the triangle (right-angled triangle call a half pyramid with stars)