•Given an input number, print a pattern such that you subtract 3 from the input number and print it until it reaches zero or to a negative value. After that, you will add 3 to the number and repeat until it reaches the same input value
•E.g: n= 15 Output = 15 12 9 6 3 0 3 6 9 12 15
•E.g: n = 8 Output = 8 5 2 -1 2 5 8
Note: You are supposed to use the recursive method to solve this question.
You cannot use a loop for this task!
#include <iostream>
using namespace std;
void RecursiveOutput(int n)
{
cout<<n<<" ";
static int start=n;
static bool state=false;
if(n<=0)state=true;
if(!state)
{
n-=3;
RecursiveOutput(n);
}
else if(state&&n<start)
{
n+=3;
RecursiveOutput(n);
}
}
int main()
{
int num;
cout<<"Please, enter an integer: ";
cin>>num;
RecursiveOutput(num);
}
Comments
Leave a comment