Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

the largest element in the array outputs as -858993460 [C++]

im trying to let the user input a number for each person. the console then outputs the maximum value in the array. everything works fine but the max always outputs as -858993460. i tried multiple combinations but i cant seem to figure it out

im new to arrays so any help would be appreciated as well as an feedback on how to improve my code

#include <iostream>


int main()
{

    int people[10];
    int max = people[0];

    std::cout << "please enter number of pancakes eaten by each person.\n";

//lets the user input values for each element

    for (int i = 0; i < 10; ++i) {

        std::cin >> people[i];

    }
//outputs all the elements of the array

    for (int i = 0; i < 10; ++i) {

        std::cout << people[i] << " ";

    }

//finds the largest element in the array

    for (int i = 0; i > 10; ++i) { 

        if (people[i] > max) {

            max = people[i];
        }
        
    }

    std::cout << "\nmax: " << max;
    return 0;

}

also i keep getting a warning saying: ill-defined for-loop. loop body not executed. i tried looking this warning up but the warning seems very broad and i couldnt find anything that helped

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

int people[10];

This declares an array of ten int values. None of the values are explicitly initialized. This is how plain values that get declared in automatic scope work in C++, they are not initialized to any values. It is the code’s responsibility to initialize them.

int max = people[0];

This sets the value of max to the first value of the array. Which has not been initialized to any value. This is undefined behavior. From this point on the program’s behavior is undefined.

Furthermore, even if peoples values were initialized this will still be broken. The intent of the program is clear: read values into the people array, and then find their maximum value.

However, at this point, nothing has been read from anywhere.

The attempted goal here is to set max, initially, to the first value in the array, the first read value.

But in order for this to make sense, max should be set after the values in the array get read from input, and not before. This should be done after all the values are read in, and not before.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading