0

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);
}
2
  • Why would you use recursion when there is no need to? Simply print it backwards with a for loop Commented May 27, 2018 at 17:34
  • Likely because this is a homework exercise.. just a guess. Commented May 28, 2018 at 6:45

2 Answers 2

2

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]));
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.