Search code examples
c++maxminimum

Finding Maximum and Minimum values in c++ by user input


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++ program that initially takes an integer value from the user as the loop’s limit. It means that the loop will execute the same times as the input from the user. The loop will then take integer values as input from the user until it reaches loop limit. You are required to use only one variable which will be used to take input repeatedly from the user inside the loop. It means you are not allowed to use the array or multiple variables for this purpose. After that your program will calculate sum of entered values, their average, minimum and maximum values along with position on which these values were entered.

i wrote but stuck on maximum and minimum.. here is

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
using namespace std;

int main(){
int value;
int ivalue;
int sum=0;
int average;
int x,y;


cout << "Enter loop limit : "; cin >> value ;
cout<<endl;
cout<<endl;

for( x=0;x<=value-1;x++){
        cout << "Enter "<<x+1<<" value : "; cin >> ivalue;
        sum=sum+ivalue;
}
   cout<<endl;
   cout<<endl;
   cout << "Sum of entered values : " <<sum <<endl;
   cout << "Average of entered values : "<< sum/value<<endl;

 }

Solution

  • 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...