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
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.
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
dude, reversing and array and printing it in reverse are two different things
ReplyDeleteHi,
DeleteWhat 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.
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