C++入门基础题:数组元素逆序(C++版互换方式)

1.题目:

数组元素逆置案例描述:

请声明一个5个元素的数组,并且将元素逆置.

(如原数组元素为:1,3,2,5,4;逆置后输出结果为:4,5,2,3,1)

2.图解思路:

3.代码演示:

cpp 复制代码
#include<iostream>

using namespace std;

int main(){
    int arr[]={20,50,70,80,40};
    cout<<"数组逆置前:"<<endl;
    for(int  i=0;i<sizeof(arr)/sizeof(arr[0]);i++){
        cout<<arr[i]<<endl;
    }

//    实现逆置
//    1.起始下标位置
//    2.结束下标位置
//    3.元素互换
//    4.起始位置++,结束位置--
//    5.循环执行,直到开始位置小于结束位置
    int start=0;
    int end=sizeof (arr)/sizeof(arr[0])-1;
    while (start<end){
        int temp=arr[start];
        arr[start]=arr[end];
        arr[end]=temp;
        start++;
        end--;
    }
    cout<<"数组逆置后:"<<endl;
    for(int  i=0;i<sizeof(arr)/sizeof(arr[0]);i++){
        cout<<arr[i]<<endl;
    }
    system("pause");
    return 0;
}

4.效果图:

相关推荐
dog2502 小时前
圆锥曲线和二次曲线
开发语言·网络·人工智能·算法·php
Wadli2 小时前
27.单调队列
算法
Navigator_Z3 小时前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode
Wect3 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·typescript
爱学习的张大3 小时前
具身智能论文问答(三):Open VLA
人工智能·算法
橙子也要努力变强3 小时前
信号的保存、阻塞与递达
linux·服务器·c++
wearegogog1233 小时前
基于Q-learning的栅格地图路径规划MATLAB仿真程序
开发语言·算法·matlab
旖-旎3 小时前
深搜练习(组合总和)(7)
c++·算法·深度优先·力扣
T0uken3 小时前
基于 vcpkg 与 LLVM-MinGW 的 Qt6 静态链接开发方案
c++·windows·qt