# 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。
答案 0 :(得分:2)
您的交换代码如下所示:
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
function。