Adsense 728 * 15

Search

Custom Search

Write a Program to print Array in Reverse Order using Recursion

In my previous post, I wrote a code to reverse an array.  In this post, i'll show how to print array in reverse order using recursion.

Logic-

To print reverse order of an array, i use following logic

void reverse(int a[],int n){
    
    if(n==0){
        return;
    }else{
        printf("%d\n",a[n-1]);
        reverse(a,n-1);
    }

}

Let's check how it works. Suppose we have an array


int arr[]={4,3,2,6,7};


As per our reverse function, it takes two argument an array and it's size. The value of n is 5.

1. It prints a[5-1] = 7 and calls the reverse function reverse(a,4).
2. In second time a[4-1] = 6 and again call the reverse function reverse(a,3).

This goes on until the value of n becomes zero.


Program to Print an Array in Reverse Order Using Recursion




#include <stdio.h>

void reverse(int a[],int n){
    
    if(n==0){
        return;
    }else{
        printf("%d\n",a[n-1]);
        reverse(a,n-1);
    }
}

main()
{
  
  int arr[]={4,3,2,6,7};
  int size = sizeof(arr)/sizeof(arr[0]);

  // Function Call

  reverse(arr,size);
  
  }


Program to Find Highest and Second Highest Element of an Array



Program to Insert an Element in an Array

3 comments:

  1. dude, reversing and array and printing it in reverse are two different things

    ReplyDelete
    Replies
    1. Hi,
      What is the difference between printing an array in reverse order and reversing an array? It looks same thing right!


      Arr[] = {1,2,3,4,5};
      If I want it to print in reverse order or reversing then it will become
      Arr[] = {5,4,3,2,1} only.

      Delete
  2. Thanks for pointing my mistake. I have corrected this program to print an array in Reverse order. To reverse an array check this program http://www.cquestions.in/2014/03/write-program-to-reverse-array.html.

    ReplyDelete