I have to write a code in c , which would display a monotonic sequence of numbers like 1 22 333 to the number I input, so number k is repeating k times. It's like i input 6, the code would display 1 22 333 4444 55555 666666. It has to be via recursion.
For now, if i cin >> 15 output is a row of numbers from 1 to 15. I have a feeling this is extremely easy but nothing crosses my mind right now. This is my attemp:
#include <iostream>
using namespace std;
int x;
void func(int n)
{
if(n>=1){
func(n-1);
std::cout<< n << " ";
}
}
int main()
{
cout << "Enter a natural number: ";
cin >> x;
func(x);
}
CodePudding user response:
There you go:
#include <iostream>
int x{0};
void func(int n)
{
if(n>=1){
func(n-1);
for (int i = 0; i != n; i)
std::cout << n;
std::cout << " ";
}
}
int main()
{
std::cout << "Enter a natural number: ";
std::cin >> x;
func(x);
}
CodePudding user response:
If you want a recursive solution add a 2nd variable so n will always have the original, and m will always have the modified value
using namespace std;
int x;
void func(int n,int m)
{
if(m>=1){
func(n,m-1);
std::cout<< n << " ";
}
}
int main()
{
cout << "Enter a natural number: ";
cin >> x;
func(x,x);
}