Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that draws a pyramid of blocks of any given height in Java. *USI

ID: 3862063 • Letter: W

Question

Write a program that draws a pyramid of blocks of any given height in Java. *USING RECURSION*

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

SquareBracketTest.java

import java.util.Scanner;


public class SquareBracketTest {

  
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.println("Enter the heigh: ");
       int n = scan.nextInt();
       System.out.println("Enter the number of spaces: ");
       int s = scan.nextInt();
       displaySquareBracket(n, s);
   }
   public static void displaySquareBracket(int n, int spaces) {
       if(n == 0){
           return;
       }
       else{
           displaySquareBracket(n-1, spaces);
           printSquareBracket(n, spaces);
           System.out.println();
          
       }
   }
   public static void printSquareBracket(int n, int spaces){
       if(n == 0){
           return;
       }
       else{
          
           printSquareBracket(n-1, spaces);
          
           System.out.print("[]");
           printSpaces(spaces);
       }
   }
   public static void printSpaces(int spaces){
       if(spaces ==0){
           return;
       }
       else{
           System.out.print(" ");
           printSpaces(spaces-1);
       }
   }
}

Output:

Enter the heigh:
4
Enter the number of spaces:
2
[]
[] []
[] [] []
[] [] [] []

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote