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

The hourglass method accepts a single integer as a parameter. If that mteger is

ID: 3579895 • Letter: T

Question

The hourglass method accepts a single integer as a parameter. If that mteger is less than 1, the hourglass method should return an error message "Argument must be greater than or equal to 1". The hourglass base case with input 1 displays two lines with one star and one trailing space on each line. Otherwise, it prints a pattern of asterisks or stars (*) as shown below for an argument of 4. Note that there are four stars (and spaces) on the first and last lines. Also note that each pattern ends with a final newline ( ). Write a static recursive method. There are many ways to write this method, but most of them involve having two parameters representing the number of stars and the number of spaces in front of the stars on the top and bottom lines (to use this approach, implement a helper method). For the overall hourglass design, there are no spaces before the stars on the first and last lines. It will be extremely helpful to write a supporting/helper method called printMany that takes in an integer count and a String s. It prmts count copies of s without finishing the line. You wouldn't normally write such a method recursive!}' in Java, but this is recursion practice. Do even that recursively. No loops.

Explanation / Answer

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
// prints spaces and stars, n is for stars and i is for leading spaces
static void printMany(int n, int i)
{
if(n!=0)
if(i==0)
{
// printing stars once done with leading spaces
System.out.print("* ");
printMany(n-1, i);
}
else
{
// printing leading spaces
System.out.print(" ");
printMany(n, i-1);
}
// done with line, printing new lin
else
System.out.println();
  
}
  
static void hg(int n)
{
hourGlass(n, n);
}
  
static void hourGlass(int n, int m)
{
if(n!=0)
{
// for printing top hourglass
printMany(n,m-n);
hourGlass(n-1,m);
// for printing lower part of hourglass
printMany(n,m-n);
}
}
   public static void main (String[] args) throws java.lang.Exception
   {
   hg(4);
  
   /* Sample output
* * * *
* * *
* *
*
*
* *
* * *
* * * *
   */
   hg(1);
   /*Sample output
*
*
   */
   }
}