一维数组元素案例

案例1:在一个数组中记录了五只小猪的体重,如int arr[5] = {300,350,200,400,250};找出并且打印出最重的小猪体重

#include<bits/stdc++.h>
using namespace std;

int main() {
	int arr[5] = { 300,350,200,800,250 };
	int max = 0;//设一个值,用来和数组中的元素比较
	for (int i = 0; i < 5; i++) {
		if (max < arr[i]) {
			max = arr[i];
		}
		/*else {
			continue;
		}*/
	}
	cout <<"最重的小猪的体重为"<< max << endl;
	system("pause");
	return 0;
}

案例2:数组元素逆置:请声明一个5个元素的数组,并且将元素逆置. (如原数组元素为:1,3,2,5,4;逆置后输出结果为:4,5,2,3,1);

#include<bits/stdc++.h>
using namespace std;

int main() {
	int arr[5] = { 1,3,2,5,4 };
	cout << "初始数组的元素为:" << endl;
	for (int i = 0; i < 5; i++) {
		cout <<arr[i] << endl;
	}
	int start = 0;//初始位置下标
	int end = sizeof(arr) / sizeof(arr[0]) - 1;//通过长度-1求出结束位置下标
	while (start < end) {
		int temp = arr[start];//暂存第一个下标的值,用以后续赋值到结束位置
		arr[start] = arr[end];
		arr[end] = temp;
		start++;//下标更新,如0-4 1-3 2-2
		end--;
	}
	cout << "逆置后数组的元素为:" << endl;
	for (int j = 0; j < 5; j++) {
		cout << arr[j] << endl;
	}
	system("pause");
	return 0;
}

学习过程:要充分利用下标,长度等来求出自己要求的东西,然后剖析题目,把题目一步一步转化为代码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值