Write a program to display a right angle triangle of stars: Prompt the user for
ID: 3779258 • Letter: W
Question
Write a program to display a right angle triangle of stars:
Prompt the user for the number of stars that they want
Display the triangle, where the first row has 1 star, second row has 2 stars,… BONUS: Limit the input to the range of 0 to 20
Example 1: (Red is entered by user)
Number of stars: 1
*
Example 2: Number of stars: 9
*
**
***
****
*****
******
*******
********
*********
Example 3: (Bonus) Number of stars: -1 Enter a valid number: 0 Enter a valid number: 21 Enter a valid number: 3
*
**
***
Explanation / Answer
/* this code is in java,has been tested on eclipse */
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
//variable to store no.of stars entered by user
int stars;
Scanner input=new Scanner(System.in);
//prompting user to enter no.of stars
System.out.print("Number of stars: ");
stars=input.nextInt();
/* if user is entering value less than 1 or greater than 20
prompt the user to enter a valid number */
if(stars < 1 || stars > 20){
do{
System.out.print("Enter a valid number: ");
stars=input.nextInt();
}while(stars < 1 || stars > 20);
}
/* nested loop to print no.of stars */
for(int i=0;i<stars;i++){
System.out.println();
for(int j=0;j<=i;j++)
System.out.print("*");
}
}
}
//end of the program
/* OUTPUT
Number of stars: 9
*
**
***
****
*****
******
*******
********
*********
OUTPUT */
/* I have done this program in c++ as there is no any specific demand regarding language of code
in the question,Please do ask in case of any doubt,Thanks,God bless you */
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.