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

Hello, I am taking a Data Structures & Algorithms class in Java and we are curre

ID: 3733133 • Letter: H

Question

Hello,


I am taking a Data Structures & Algorithms class in Java and we are currently working on Recursion. I am struggling with understanding it and I don't really know how to approach the first part. If someone could help me with this, that would be super helpful!


Thanks!


1. Write a recursive method printStarPattern () that takes a nonnegative integer as a parameter and generates the following pattern of stars. If the nonnegative integer is 4, then the pattern generated is: 44* 4* *88* Also, write a main method that prompts the user to enter the number of lines in the pattern and uses the recursive method to generate the pattern. For example, specifying the number of lines to be 4 generates the preceding pattern.

Explanation / Answer

import java.util.*;

class StarPattern
{
public static void main (String[] args)
{
  int n = -1;
  Scanner input = new Scanner(System.in);
  
  while(n<0)// input validation
  {
  System.out.println("Enter a non negative integer : ");
  n = input.nextInt();
  }
  
  printStarPattern(n);
}
public static void printStarPattern(int n)
{
if(n > 0) {

for(int i = n; i >= 1; i--)
System.out.print("*"); //print * n times
System.out.println();
  
printStarPattern(n-1); // recursive call to print * n-1 times, n-2 times .... so on until n > 0
for(int i = 1; i <= n; i++)
System.out.print("*");
System.out.println();
}
}
}

Output:

Enter a non negative integer :4
****
***
**
*
*
**
***
****

Do ask if any query. Please upvote if the answer is useful

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