While I was refreshing some of my java concepts I came across this site with an interesting problem to be solved using recursion. To brush up i quickly wrote three basic programs, viz, sum to given input, product to given input and value of 2^(given number).
Here's the problem statement:
Write a method that accepts an integer parameter n and returns a string of stars (asterisks) 2n long (i.e., 2 to the nth power).
For example:
Here is what I came up with:
Here's the problem statement:
Write a method that accepts an integer parameter n and returns a string of stars (asterisks) 2n long (i.e., 2 to the nth power).
For example:
| Call | Output | Reason |
|---|---|---|
stringRec(0); | "*" | 20 = 1 |
stringRec(1); | "**" | 21 = 2 |
stringRec(2); | "****" | 22 = 4 |
stringRec(3); | "********" | 23 = 8 |
stringRec(4); | "****************" | 24 = 16 |
Here is what I came up with:
| private static void stringRec(int i) { if (i == -1) { System.out.print("*"); } else { for (int j = i; j >= 0; j--) { stringRec(j - 1); } } } |
No comments:
Post a Comment