Reputation: 33
I am trying to write a simple code to get the minimum and the maximum of an array. The problem is that if I choose to put this sequence of values 5 2 -13 5 1. the output is Maximum number is 5 minimum number is 1. why the code is ignoring the negative number? the same thing goes if I put a sequence of negative numbers like -2 -4 -123 -4 5 the maximum number is 5 and minimum is -4
I cant understand why!
cout<<"Enter the Value of the Array"<<endl;
cin>>valueOfArray;
cout<<"Enter the Array Elements"<<endl;
for(int i=0; i<valueOfArray;i++)
{
cin>>ArrayOfNumbers[i];
minimum=ArrayOfNumbers[0];
if(ArrayOfNumbers[i]>maximum)
{
maximum=ArrayOfNumbers[i];
}
else if(ArrayOfNumbers[i]<minimum)
{
minimum=ArrayOfNumbers[i];
}
}
cout<<"the Maximum number is "<<maximum<<endl;
cout<<"The Minimum number is "<<minimum<<endl;
Upvotes: 0
Views: 329
Reputation: 16325
There are a few problems, some of which are pointed out in the other answers.
Ultimately, to get proper output, you'll have to initialize your minimum
and maximum
vars to their polar opposites outside your array.
#include<climits>
long minimum = LONG_MAX;
long maximum = LONG_MIN;
for(int i = 0; i < valueOfArray; i++){
cin>>ArrayOfNumbers[i];
if (ArrayOfNumbers[i] > maximum) {
maximum = ArrayOfNumbers[i];
} else if (ArrayOfNumbers[i] < minimum) {
minimum = ArrayOfNumbers[i];
}
}
This solution will ensure that any number in the range LONG_MIN < n < LONG_MAX will register either as a minimum or maximum, as appropriate.
Upvotes: 1
Reputation: 1171
your looping logic is little wrong.
maybe this can help
minimum=0;
maximum=0;
for(int i=0; i<valueOfArray;i++){
cin>>ArrayOfNumbers[i];
if(ArrayOfNumbers[i]>maximum){
maximum=ArrayOfNumbers[i];
}
else if(ArrayOfNumbers[i]<minimum){
minimum=ArrayOfNumbers[i];
}
}
that happen because everytime you input data, you change your minimum value to your first data.
Upvotes: 0