USING DATA STRUCTURES RECUSION Write a program, called RecursiveAsterisks, that
ID: 671192 • Letter: U
Question
USING DATA STRUCTURES RECUSION
Write a program, called RecursiveAsterisks, that has a recursive method called
printAsterisk that takes an integer n as a parameter. The method should print a
pattern of 2n lines of asterisks. The first line contains one asterisk, the next line
contains 2, and so on up to the nth line which contains n asterisks. Line number
n+l again contains n asterisks, the next line has n-l asterisks, and so on until
line number 2n which has just one asterisk. Your main method should ask the
user for the value of n. Below is an example of what would be displayed by the
call printAsterisk(4).
(Note: method header is: public static void printAsterisk(int n) )
A) *
**
***
****
****
***
**
*
B) ****
***
**
*
*
**
***
****
What if you could add a parameter to a) what would you add in order to complete the task.
Explanation / Answer
A)
import java.util.Scanner;
public class RecursiveAsterisks
{
public static void main (String[] args)
{
Scanner reader = new Scanner(System.in);
int n;
System.out.println("Enter a number: ");
n = reader.nextInt();
for ( int i = 0; i < (n+1); i++)
printAsterisks(i);
for ( int i = (n); i > 0; i--)
printAsterisks(i);
}
public static void printAsterisks(int n)
{
if (n > 0) {
for ( int i = n; i >0; i--)
System.out.print("*");
System.out.println();
}
}
}
B)
import java.util.Scanner;
public class RecursiveAsterisks
{
public static void main (String[] args)
{
Scanner reader = new Scanner(System.in);
int n;
int num;
System.out.println("Enter a number: ");
n = reader.nextInt();
printAsterisks(n);
}
public static void printAsterisks(int n)
{
if (n == 0)
return;
if (n > 0) {
printAsterisks(n - 1);
for( int i = 0; i < n; i++)
System.out.print("*");
System.out.println();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.