i want to know how can i find the maximum and minimum value in c++ by user input value and and user also put the limit for for loop , for example :
Write a c++ prog
To ensure that any value entered will be a larger value than what you initialize "max" to, you need to initialize it to the smallest possible integer value.
int max = INT_MIN;
You will need to do the opposite for the minimum, for the same reasons.
int min = INT_MAX;
You also need to keep track of the iteration of the loop in order to find the position when the maximum and minimum were entered.
int count = 1;
Through each iteration of your loop, you will increment your count variable.
count++;
Now you will need two variables to track the position of your maximum and minimum.
int maxPos = 1;
int minPos = 1;
We can initialize the positions to one as we know that at least the first user-entered value will be our new maximum and minimum.
Then, inside your for loop, you will need to test if the value entered by the user is greater than the current maximum, and if it is, to set that value as the new maximum and update the position.
if (ivalue > max) {
max = ivalue;
maxPos = count;
}
You will also need to test the minimum and assign it if the user-entered value is smaller than the current minimum as well as update the position.
if (ivalue < min) {
min = ivalue;
minPos = count;
}
you should define the maximum as the lowest possible value:
int maximum = -INFINITY;
then at each value compare and set new maximum if necessary:
if (ivalue > maximum)
maxumum = ivalue;
for minimum you would use the same kind of logic...
int input;
int max = 0;
int min = 0;
cout << "Enter number: ";
while (input != -1)
{
cin >> input;
if(input != -1)
{
if(input > max)
{
max = input;
}
if(input < min)
{
min = input;
}
}
}
cout <<"Max: " << max << " Min " << min << endl;
}