"Hendrik Belitz" <> wrote in message
news:buive2$92lb$...
> Karl Heinz Buchegger wrote:
>
> > Hendrik Belitz wrote:
> >> That's simple:
Despite its simplicity it turns out to be tricky
> >>
> >> int arr[arraySize};
Here we've got a typo!
> >> int min = INT_MAX; int max = INT_MIN;
> >> for ( i = 0; i < arraySize; i++ )
> >> if ( arr[i] < min ) min = arr[i];
> >> else if ( arr[i] > max ) max = arr[i];
> >>
You are lacking the definition of i!
> >
> > What would your code give in the case of:
> >
> > int arr[] = { 5 };
> >
> > min -> 5
> > max -> INT_MAX
>
> No, it won't:
>
> int arr[] = { 5 };
>
> min -> 5
> max -> 5
>
> which is correct
>
Yes, this is correct but it is not what your program delivers. If it does
then I'd suggest to get rid of the compiler you are using. The result is
min -> 5
max -> INT_MIN
due to the superficial else. Although removing the else only will not be
sufficient, for in that case you will introduce another bug due to the lack
of missing curly brackets in the for loop.
The correct solution is:
const int arraySize = 1;
int arr[arraySize] = {5};
int min = INT_MAX; int max = INT_MIN;
for( int i = 0; i < arraySize; ++i ) {
if ( arr[i] < min ) min = arr[i];
if ( arr[i] > max ) max = arr[i];
}
Or simply write
for ( int i = 0; i < arraySize; arr[i] < min ? min = arr[i] : i = i, arr[i]
> max ? max = arr[i++] : i++ ) {}
Regards
Chris