rahul shrivastava
rahul shrivastava

Reputation: 1

c code to print reverse of array using recurion

This code is to print reverse of array using recursion I am using recursion function called from main output should be as 5,4,3,2,1 can someone help in debugging this

#include <stdio.h>
void recursion(int a[])
{
    int i=0;

    if(i<5)
    return;

    i++;
    recursion(i);
    printf("%d ",a[i]);

}
int main()
{
    int arr[]={1,2,4,5};
    recursion(arr);
}

Upvotes: 0

Views: 66

Answers (2)

Lakshraj
Lakshraj

Reputation: 291

Your recursion function is not working properly. Note whenever you are calling a function the parameters should be same. In your code parameter of your function is array, but when you are calling it from inside the function i.e recursion you are passing i.

So, what you can do is that

#include <stdio.h>
void recursion(int a[], int i)
{
  int t = i-1;
  if(t>=0)
  {
      printf("%d ",a[t]);
      return recursion(a, t);
  }

}
int main()
{
    int arr[]={1,2,4,5};
    recursion(arr,4);
}

Hopefully that helps

Upvotes: 0

0___________
0___________

Reputation: 67820

A good C book is needed:

#include <stdio.h>
void recursion(int a[], int i, int size)
{
    if(i < size -1)
        recursion(a, i + 1, size);
    printf("i = %d arr[%d] == %d \n",i, i, a[i]);

}
int main()
{
    int arr[] = {1, 2, 4, 5};
    recursion(arr, 0, sizeof(arr) / sizeof(arr[0]));
}

Upvotes: 2

Related Questions