Reputation: 355
I am trying to print a array in Reverse order by using the recursive function but I am getting so many error can someone guide me through the process please where I am making the mistakes.
#include<stdio.h>
int PrintArray(int a[],int k) {
int z;
while(k>0) {
z=k-1;
PrintArray(a[],z);
printf("%d ",a[k]);
}
}
int main() {
int n,i;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",a[i]);
PrintArray(a[],n);
return 0;
}
Upvotes: 1
Views: 10789
Reputation: 1
This function will receive address of array in pointer variable and it will receive the size of array... Then the function displays array in reverse order.
void R_output(int *arr, int s) {
int l;
if(s > 0)
{
l = s - 1;
cout << arr[l] << " ";
R_output(arr, l);
}
return;
}
Upvotes: -1
Reputation:
This is not work, you need to use this code:
#include<stdio.h>
void PrintArray(int a[],int k)
{
int z;
if (k>0)
{
z= k-1;
printf("%d ",a[z]);
PrintArray(a,z);
}
return;
}
int main()
{
int n,i;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
PrintArray(a,n);
return 0;
}
Upvotes: 0
Reputation: 335
I edited your code . Here is a new one:
#include<stdio.h>
void PrintArray(int a[],int k)
{
int z;
if (k>0)
{
z= k-1;
printf("%d ",a[z]);
PrintArray(a,z);
}
return;
}
int main()
{
int n,i;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
PrintArray(a,n);
return 0;
}
Now let me highlight your errors:
While using scanf("%d", a[i])
you have to use address of the input location. i.e. &a[i]
.
Your recursive function was of type int
and was not returning anything. therefore use void
instead of int
.
The function calling was also syntactically incorrect. While calling the function you should not place []
when you are passing an array. Just Simply pass the name of the array. eg. PrintArray(a,z);
Your logic in the function is absolutely wrong .The printf("%d ",a[k]);
will never get executed because it is placed after the function call, so either the the next recursive function will be called or the while loop condition will not be satisfied.
Upvotes: 2