0

I have a code below

#include <iostream>

void print(int n){
     if(n == 0) {return;}
     for(int i=0; i<n; i++)
     cout<<"Hello world"<<endl;
}

int main(){
   print(n);
}

What it does is it prints "Hello world" using for loop n times. My question is would it be possible to print it using recursion instead of using for loop?

4
  • 3
    Yes, it would be possible. Commented May 26, 2020 at 7:43
  • 1
    remove the for part, and after the cout add print(n-1);. Commented May 26, 2020 at 7:44
  • 1
    This feels like a homework question. Commented May 26, 2020 at 7:46
  • In the iterative version, if(n == 0) {return;} is unneeded. Commented May 26, 2020 at 8:12

3 Answers 3

1

You can adapt your code like this. The print function will be called recursively n times, then return since in the last call n will be equal to 0 and because of the first condition it will stop the recursion.

#include <iostream>

void print(int n) {
     if(n == 0) { return; }
     std::cout << "Hello world" << std::endl;
     print(n-1);
}

int main(){
   print(n);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Recursion is simply a function that calls itself. There's a pretty good tutorial HERE.

Basically, you would create a counter, and add to that counter every time the function is called, and don't call it from inside itself if the counter is higher than a certain value.

Comments

0

I would simply do something like this:

#include <iostream>

void print(int n){
     if(n!=0){
         std::cout<<"Hello world"<<std::endl;
         return print(n-1);
     }
}

int main(){  
   print(n);
   return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.