You need to choose an initial value for min
and max
. You choose x
but x
is not initialized, it has an indeterminate value. Using x
to initialize min
and max
leads to undefined behavior.
You can use the first element as initial value for min
and max
. However, rather than fixing your mistake you can avoid it completely: Let someone else find min
and max
for you.
There is std::minmax_element
that given two iterators to being and end of a range returns a pair of iterator to the minimum element and iterator to maximum element. The iterators you pass to std::minmax_element
do not have to be iterators to a container, they can be std::istream_iterator
s that read from std::cin
on the fly.
#include <iostream>
#include <algorithm>
#include <iterator>
int main() {
auto res = std::minmax_element(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>());
std::cout << *(res.first) << " " << *(res.second) ;
}
Live Demo
It takes a bit to understand the code. I hope the links above help with that. But once you know what the code does it is as simple as it can get. There is almost no possibility to get something wrong. Well of course there are some, but for example it is just not possible to have wrong initial values for min
or max
in this code.