Problem Statement:
Write a program that prints a given name n times using recursion.
Problem Understanding
To tackle this problem, we need to understand the recursive nature of printing the name n times. Recursion involves breaking down a problem into smaller instances of the same problem until a base case is reached. In this case, the base case occurs when the number of times to print the name (n) becomes zero or negative
Different Approach
1️⃣ Using Recursion
Code:
#include <iostream>
void printNameNTimes(const std::string& name, int n) {
// Base case: If n is 0 or negative, return without printing anything
if (n <= 0) {
return;
}
// Print the name
std::cout << name << std::endl;
// Recursively call printNameNTimes with n-1
printNameNTimes(name, n - 1);
}
int main() {
std::string name;
int n;
// Prompt the user to enter their name
std::cout << "Enter your name: ";
std::cin >> name;
// Prompt the user to enter the number of times to print the name
std::cout << "How many times would you like to print your name? ";
std::cin >> n;
// Call the recursive function to print the name n times
printNameNTimes(name, n);
return 0;
}
Complexity Analysis:
- Time Complexity:
- The function
printNameNTimesis called recursivelyntimes. - Each recursive call performs a constant amount of work (printing the name) which can be considered
O(1)time complexity. - Therefore, the overall time complexity of the solution is
O(n), wherenis the number of times the name is printed.
- The function
- Space Complexity:
- The space complexity of the solution is
O(n)as well, considering the recursive calls create a call stack withnframes, each storing information about the function call.
- The space complexity of the solution is
