Write a program that draws a pyramid of blocks of any given height in Java. Exam
ID: 3861608 • Letter: W
Question
Write a program that draws a pyramid of blocks of any given height in Java.
Example: like this for height 4:
[ ]
[ ] [ ]
[ ] [ ] [ ]
[ ] [ ] [ ] [ ]
Note that each block is a pair of square brackets.
-The program must use a recursive method to draw the pyramid.
-The recursive method should do two things: Make a recursive call, and print one line of the pyramid.
-Each line of the pyramid is a sequence of spaces followed by a sequence of blocks.
-Use two parameters for the recursive method: one that holds the number of spaces to print before the blocks, and one that holds the number of blocks to print.
Explanation / Answer
public class Pyramid
{
public static void main(String[] args)
{
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.println(“Enter the size : “);
int n = scn.nextInt();
for (int f=1;f<=n;f++) // for 5 loops
{
for (int sp=n-f;sp>=0;sp--) //for spaces
{
System.out.print(" ");
}
for (int s=f;s>=1;s--) // to display pyramid
{
System.out.print(“[]“+” ");
}
System.out.println(); // for line break
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.