输入一个数组倒序输出数组
时间: 2024-06-03 20:03:07 浏览: 17
以下是两种倒序输出数组的方法:
1. Python实现,使用切片[::-1]将数组倒序输出:
```python
arr = [1, 2, 3, 4, 5]
reverse_arr = arr[::-1]
for i in reverse_arr:
print(i)
```
2. C语言实现,使用循环将数组倒序输出:
```c
#include <stdio.h>
#define N 5
int main() {
int arr[N];
printf("请输入%d个数:\n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
printf("倒序输出为:\n");
for (int i = N - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
return 0;
}
```
相关问题
c+++字符数组倒序输出
以下是C++字符数组倒序输出的例子:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main(){
int cnt=0;
string a[1000];
int n;
cout<<"字符串个数:";
cin>>n;
for(int i=0; i<n;i++){
cin>>a[i];
}
for(int i=n-1; i>=0;i--){
cout<<a[i]<<endl;
}
return 0;
}
```
注意:以上代码中使用了string类型,而不是字符数组类型。如果要使用字符数组类型,可以参考以下代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char s[1000];
cin.getline(s, 1000); // 输入字符串
int len = strlen(s);
for(int i=len-1; i>=0; i--){
cout<<s[i];
}
return 0;
}
```
编写一个程序使用户输入10个整数赋值给一个数组,使用指针和函数实现数组倒序输出。编写一个函数实现数组元素的倒序,然后编写一个测试程序来调用该函数
以下是代码实现:
```c
#include <stdio.h>
void reverse_array(int *arr, int size) {
int *start = arr;
int *end = arr + size - 1;
while (start < end) {
int temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
int arr[10];
printf("请输入10个整数:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
reverse_array(arr, 10);
printf("倒序输出:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
运行程序后,输入10个整数,程序将会输出这10个整数的倒序。其中,`reverse_array` 函数接受一个指向数组开头的指针和数组的大小,然后对该数组进行倒序操作。主函数中调用该函数,将输入的数组倒序后输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)