我已经编写了一个代码来查找数组元素的反向,但它没有给出所需的输出

I have written a code to find reverse of array elements but it doesnot gives required output

本文关键字:输出 数组元素 查找 代码 一个      更新时间:2023-10-16
# include <iostream>
using namespace std;
const int size=5;
void inputdata(int arr[], int n);    //function prototype
void display(int arr[],int n);    //function prototype
void Reverse(int arr[],int n);    //function prototype

int main()    //start of main function
{
    int list[size];    //array declaration
    inputdata(list ,size);    //fuction call
    display(list,size);     //fuction call         
    Reverse(list,size);    //fuction call

}
void inputdata(int arr[], int n)    //function definition that takes input from user
{
    int index;
    for(index=0;index<n;index++)    //loop to take input from user
    {
        cout<<"Enter element ["<<index<<"]"<<endl;
        cin>>arr[index];
    }
}
void display(int arr[],int n)    //displays the input  
{
    int index;
    for(index=0;index<n;index++)    //loop to display output
    {
        cout<<"Element on ["<<index<<"] is:"<<arr[index]<<endl;
    }
}
void Reverse(int arr[],int n)    //function to find reverse
{
    int i,temp;    //here i have taken a variable temp of integer type for swapping
    for(i=0;i<n/2;i++)
    {
        temp=arr[i];
        arr[i]=arr[n-i-1];
        arr[n-i-1]=arr[i];
    }
    cout<<"the reverse order array is:"<<endl;
    for(i=0;i<n;i++)    //this loop is used to display the reverse order
    {
        cout<<arr[i]<<endl;
    } 
return 0;
}

上面的C ++代码旨在查找数组元素的反面,该元素被视为用户的输入。输入数据功能用于从用户那里获取输入。显示功能用于显示该输入。然后有一个函数反向,它找到反向。但它没有给出正确的反向(输出(,例如,如果我输入 5 个数组元素作为 1,2,3,4,5,它的输出应该是 5,4,3,2,1.但这结果是 5,4,3,4,5。

您的交换代码如下所示:

temp=arr[i];
arr[i]=arr[n-i-1];
arr[n-i-1]=arr[i];

但它应该是:

temp=arr[i];
arr[i]=arr[n-i-1];
arr[n-i-1]=temp;

一个更简洁、更简单的选择是使用 algorithm 库中的 swap 函数。