Home > Software engineering >  the largest element in the array outputs as -858993460 [C ]
the largest element in the array outputs as -858993460 [C ]

Time:11-28

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

CodePudding user response:

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.

CodePudding user response:

in the line int max = people[0] you are dereferencing the first element of the array. But dereferencing to what? at that point in the program you have not initialised any of the 10 elements in the people array. So taking the value at people[0] at that point in the program and copying it into another int for later comparison is undefined behaviour. Best solution is to simply move int max = people[0] to after you take the user input, and for the comparison loop start with i = 1, because max is already equivalent to the first inputted value.

  • Related