Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ หาค่าสูงสุด (Largest Element) ในอาร์เรย์


หาตัวเลขที่มากที่สุดในอาร์เรย์และตำแหน่ง index ของมัน

ตัวอย่าง: [5, 1, 7, 2, 4] → มากที่สุดคือ 7 อยู่ index 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

อธิบายอัลกอริทึม

1. largest = a[0] (สมมติตัวแรกมากที่สุด)

2. for loop เริ่ม i=1 ถึง 4 เปรียบเทียบ a[i] กับ largest:

for(i=1; i<5; i++) {
    if(a[i] > largest) {
        largest = a[i];
        pos = i;
    }
}

3. แสดงค่ามากที่สุดและ index