712055. Print GFG n times
Easy
Print GFG n times
Slug: print-gfg-n-times
Difficulty: Easy
Id: 712055
Topic Tags: Recursion, Algorithms
Company Tags: None
Summary
This problem involves printing a specific string ("GFG") a given number of times (n). The key concept involved is recursion.
Detailed Explanation
To solve this problem, we can use recursion to print the string "GFG" n times. Here's a step-by-step breakdown of the solution:
- Define a function
printGFG(n)that takes an integernas input. - Inside the function, if
nis 0, return immediately (base case). - Otherwise, print the string "GFG" and recursively call the function with
n-1as input. - Repeat step 3 until
nbecomes 0.
Here's an ASCII art diagram representing the recursion:
+---------------+
| printGFG(2) |
+---------------+
|
|
v
+---------------+ +---------------+
| printGFG(1) | | printGFG(1) |
+---------------+ +---------------+
|
|
v
+---------------+ +---------------+
| printGFG(0) | | printGFG(0) |
+---------------+ +---------------+
Time complexity: O(n) Space complexity: O(n) (recursion stack)
Optimized Solutions
Java
public class Main {
public static void printGFG(int n) {
if (n == 0) return;
System.out.println("GFG");
printGFG(n-1);
}
public static void main(String[] args) {
int n = 5; // number of times to print "GFG"
printGFG(n);
}
}