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!
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
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.