I'm having trouble with recursion!
If I have an array as: int a[] = {1, 2, 3, 4, 5};
and I want to display it on the screen like this:
1 2 3 4 5
I have to write : void PrintData(int a[], int n) to do that and using recursion!
How can I do that!
Please help me and thanks a lot!

Recommended Answers

All 4 Replies

Rather than predefining your array a[], why not use the integer value of n as the final output?

I don't like that you didn't post any code, but here's a hint:

for( i=0;i<n; ++i ) {
  a[i] = i+1;
  std::cout << a[i] << " ";
}

Thanks for your help!
Before I posted code, I don't know what to do!
But now I can reply for this:

void PrintData(int a[], int n)
{
if (n == 1)
return;

PrintData(a, n-1);
cout<<a[n-1] <<" ";
}

I have said : "display the array on the screen", we must do with recursion.
And here is the answer!

Mathematical recursion is expressed with the capital sigma character, and I think what you mean is a self-addressing function. My misunderstanding.

void print(int a[], int n) {
  if(n==0)return; // a[0] is the first element, not a[1]
  std::cout<< a[--n] << " "; // print before calling this function again
  // the above line also has the effect of decrementing n by 1
  print(a, n); // this is called only if n wasn't 0
}

Good luck!

Edit: At some point you may want to print a newline (return character), to do this (in windows) just insert "\n" like so:
std::cout << "\n";

On that note, you might be interested in "escape characters", if you google that with quotes you will find plenty of documentation about them.

Sorry for my trouble: The code is just right as this:

void Print(int a[], int n)
{
   if (n == 0)
      return;
   Print(a, n-1);
   cout<<a[n-1] <<"  ";
}

I change that: n==1 to n==0. And I think these codes above is the best answer!
Thanks for your care!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.