Output the position of the maximum value in c++

Asked 2 years ago, Updated 2 years ago, 20 views

using namespace std;

int main() { int x; int max = 0; cout << "Enter 10 numbers" << endl; for (int i = 0; i < 10; i++) { cin >> x; if (x > max) { max = x;
} } cout << "The max: " << max << endl; cout << "The location max: " << << endl;

} I want to print the maximum position without using pointers and arrays in the following code ex) If you put in 10 integers and assume that the 4th, 100th, is the largest, you want to output 3. I heard that there is a way to use index, but I don't know what to do.

c++

2022-09-20 19:55

1 Answers

Please refer to the code below.

#include <iostream>

using namespace std;

int main() {
    int x;
    int max = 0;
    int max_index;

    cout << "Enter 10 numbers" << endl;
    for (int i = 0; i < 10; i++)
    {
        cin >> x;

        if (x > max)
        {
            max = x;
            max_index = i;
        }
    }

    cout << "The max: " << max << endl;
    cout << "The location max: " << max_index << endl;

    return 0;
}


2022-09-20 19:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.