简体   繁体   English

使用递归函数以相反的顺序打印数组

[英]Printing Array In Reverse Order using Recursive function

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;
}

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:现在让我强调您的错误:

  1. While using scanf("%d", a[i]) you have to use address of the input location.使用scanf("%d", a[i])您必须使用输入位置的地址。 ie &a[i] .&a[i]

  2. Your recursive function was of type int and was not returning anything.您的递归函数是int类型并且没有返回任何内容。 therefore use void instead of int .因此使用void而不是int

  3. 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);

  4. Your logic in the function is absolutely wrong .The printf("%d ",a[k]);你在函数中的逻辑是绝对错误的。 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.永远不会被执行,因为它被放在函数调用之后,所以要么下一个递归函数将被调用,要么不会满足 while 循环条件。

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; 
}

function功能

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM