C++程序:查找数组中的最大元素
数组包含多个元素,数组中最大的元素是大于其他元素的元素。
例如。
| 5 | 1 | 7 | 2 | 4 |
在上面的数组中,7 是最大元素,位于索引 2。
查找数组最大元素的程序如下所示。
示例
#include <iostream>
using namespace std;
int main() {
int a[] = {4, 9, 1, 3, 8};
int largest, i, pos;
largest = a[0];
for(i=1; i<5; i++) {
if(a[i]>largest) {
largest = a[i];
pos = i;
}
}
cout<<"The largest element in the array is "<<largest<<" and it is at index "<<pos;
return 0;
}输出
The largest element in the array is 9 and it is at index 1
在上面的程序中,a[] 是包含 5 个元素的数组。变量 largest 将存储数组中的最大元素。
最初,largest 存储数组的第一个元素。然后启动一个 for 循环,该循环从索引 1 运行到 n。对于循环的每次迭代,将 largest 的值与 a[i] 进行比较。如果 a[i] 大于 largest,则该值将存储在 largest 中。并且对应的 i 值存储在 pos 中。
以下代码片段对此进行了演示。
for(i=1; i<5; i++) {
if(a[i]>largest) {
largest = a[i];
pos = i;
}
}之后,将打印数组中最大元素的值及其位置。
显示如下:
cout<<"The largest element in the array is "<<largest<<" and it is at index "<<pos;
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP