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:

  1. Define a function printGFG(n) that takes an integer n as input.
  2. Inside the function, if n is 0, return immediately (base case).
  3. Otherwise, print the string "GFG" and recursively call the function with n-1 as input.
  4. Repeat step 3 until n becomes 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

View on GeeksforGeeks
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);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.