我已经编写了一个代码来查找数组元素的反向,但它没有给出所需的输出
I have written a code to find reverse of array elements but it doesnot gives required output
# 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
函数。
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 使用递归输出数组
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- C++ 输出数组中的最高元素
- 整数数组元素,前导 0 表示垃圾输出
- 我已经编写了一个代码来查找数组元素的反向,但它没有给出所需的输出
- 按相反顺序输出数组的元素
- 输出一个赋值给c++双精度数组元素的字符串
- 基于范围的for循环错误地输出了具有cout的数组元素