I am coding a program in my Java class and I need to print a pyramid of stars. My code reads:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 1 and 20: ");
int value = sc.nextInt();
System.out.println("Pattern B: ");
for(int x = 1; x <= value; x++){
for(int y = value; y>=x; y-- ){
System.out.print("*");
}
System.out.print("\n");
}
my result prints a line of 5 stars, then 4, 3, 2, 1 (if the user enters the number 5). What I want is to have the stars all pushed to the right. Such as:
a line of 5 stars, (space) line of 4 stars, (two spaces) line of 3 stars, (three spaces) line of 2 stars, (four spaces) line of one star
Am I making sense?
Should I introduce an if then statement, check the variable y and increment spaces accordingly? I am sorry if I am confusing you.
You could introduce a new for
loop to print the required number of whitespace prior to printing your stars:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 1 and 20: ");
int value = sc.nextInt();
System.out.println("Pattern B: ");
for(int x = 1; x <= value; x++){
for(int c = value-x; c<value; c++){
System.out.print(" ");
}
for(int y = value; y>=x; y-- ){
System.out.print("*");
}
System.out.print("\n");
}