Basically the program has two errors. One has already been indicated and it is that you have cast a ;
after a if
:
if(arr[i]<menor);
// ^
That semicolon causes the if
to do absolutely nothing ... silly language details. To see it more clearly we could replace that semicolon with two keys:
if(arr[i]<menor){ }
{
menor = arr[i];
}
Now it looks better than that semicolon overrides the conditional.
On the other hand the initialization of menor
is not correct.
Global arrays are initialized automatically, not those that belong to a function. That is:
int arr[MAX]; // Todos sus elementos valen 0
// Pero únicamente porque es variable global!!!
int main()
{
int arr2[MAX]; // Array no inicializado!!!
}
Well, the next thing you do after declaring the fix is to declare and initialize mayor
and menor
:
int mayor=arr[0], menor=arr[0];
And here the problems begin ... this initialization makes mayor=menor=0
. If we subsequently give values to arr[0]
, the value of mayor
and menor
will not change automatically. Your starting value will be always 0.
This initialization poses a problem and is that for menor
find the smallest number, it must be equal to or less than 0. Otherwise the program will not work.
To avoid this mess of minimums and maximums I would use pointers:
int* mayor = arr;
int* menor = arr;
for(int i=0; i<MAX; i++)
{
cin>>arr[i];
if(arr[i] > *mayor)
{
mayor = &arr[i];
}
if(arr[i] < *menor)
{
menor = &arr[i];
}
}
cout << *menor << ' ' << *mayor;
This solution uses pointers instead of variables. Thus, menor
does not store a value of its own, but will point to the smallest element (the same for mayor
).
If using pointers is not a possibility, then you should pay special attention to the initialization of menor
and mayor
. Pulling the standard the best is to use std::numeric_limits
:
int menor = std::numeric_limits<int>::max();
int mayor = std::numeric_limits<int>::min();
What we do here is initialize menor
with the largest number that can be stored in a int
, in this way any number that the user enters will be equal or smaller and, consequently, the algorithm will be able to detect it as smaller. In mayor
, instead, we store the smallest number possible, so that any number that the user enters is equal or larger.