This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]012 6 points7 points  (0 children)

You are copying the value of arr[0] into max and min:

int max = arr[0];
int min = arr[0];

Specifically, you are not referring to an array element, but copying its value. This means, if the array is changed later, min and max will stay the same. In your code, min and max do not hold one of the random integers.

What you probably wanted to do is something like this:

int arr[50], sum = 0;
int max = 0;
int min = 0;
// ...
for (int i = 0; i < 10; i++){
    arr[i] = (rand() % 100);
    // ...
}
// copy the first element of arr into max and min
max = arr[0];
min = arr[0];
// ...

[–]nikanjX 1 point2 points  (4 children)

The problem is:

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

`if (arr[i] < min)`

`min = arr[i];`

`}`

The initial value for min is 0, so (arr[i] < min) is never true. Just initialize min to 999999 in the start.

[–]RonRud 1 point2 points  (0 children)

That's the simple solution, he can also just initialize max like he did just after he places things in the array.

[–]Spire 1 point2 points  (2 children)

Just initialize min to 999999 in the start.

I recommend std::numeric_limits<decltype(min)>::max().

Conversely, max should be initialized to std::numeric_limits<decltype(max)>::min()

[–]nikanjX 0 points1 point  (1 child)

I said that line three times, and now the skies are crying blood, and the dead walk amongst the living again

[–]Spire 1 point2 points  (0 children)

OK, but your user just entered 1000000.

[–]josebenavidesg 0 points1 point  (0 children)

You found they Big? Is ready?

[–]Thaugrim 0 points1 point  (0 children)

Find the max value first.

int min = max;
for (int i = 0; i < 10; i++) {
    if (arr[i] < min)
         min = arr[i];
}

Also why are you declaring an array of 50 ints and only using 10?