案例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;
}
学习过程:要充分利用下标,长度等来求出自己要求的东西,然后剖析题目,把题目一步一步转化为代码