Reputation: 13
#include<iostream>
main()
{
int limit,input;
int sum=0;
int i;
std::cout<<"Please Enter the limit: ";
std::cin>>limit;
for(i=0;i<limit;i++)
{
std::cout<<"Please Input values: ";
std::cin>>input;
sum+=input;
}
std::cout<<"The sum of the values is: "<<sum;
std::cout << std::endl;
std::cout<<"The average of the values is: "<<sum/1+i;
}
What to do if i want to find Max and Min Values from the values input by the user?
Upvotes: 1
Views: 23157
Reputation: 431
int max=0, min=0;
for(i=0;i<limit;i++)
{
std::cout<<"Please Input values: ";
std::cin>>input;
sum+=input;
if(i==0){
max=input;
min=input;
}
if(input>max)
max=input;
if(input<min)
min=input;
}
Now, you got the max and min value.
Upvotes: 0
Reputation: 605
There are multiple ways,
You can store all values input from user into a std::vector<int>
. Use this vector to find out sum of elements and then sort it using std::sort
to get Max and Min values as well. Simple!
vector<int> v(limits);
for(int i = 0; i<limits; i++)
{
int input;
cin >> input;
v.push_back(input);
}
int sum = 0;
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
sum += *it;
}
cout << "sum = " << sum << endl;
sort(v.begin(), v.end());
cout << "Min = " << v[0] << endl;
cout << "Max = " << v[v.size() -1] << endl;
Upvotes: 1
Reputation: 3614
Try this
int min_v = std::numeric_limits<int>::max();
int max_v = std::numeric_limits<int>::min();
for(i=0;i<limit;i++)
{
std::cout<<"Please Input values: ";
std::cin>>input;
sum+=input;
min_v = std::min(input, min_v);
max_v = std::max(input, max_v);
}
Upvotes: 5
Reputation: 955
Please try the code below.
int main()
{
int limit,input;
int sum=0;
int i;
std::cout<<"Please Enter the limit: ";
std::cin>>limit;
int min = 0;
int max = 0;
for(i=0;i<limit;i++)
{
std::cout<<"Please Input values: ";
std::cin>>input;
if(i == 0)
{
min = input;
max = input;
}
else
{
if(input < min)
min = input;
if(input > max)
max = input;
}
sum+=input;
}
std::cout<<"The sum of the values is: "<<sum<<std::endl;
std::cout<<"The average of the values is: "<<sum/(1+i)<<std::endl;
std::cout<<"Max: "<<max<<std::endl;
std::cout<<"Min: "<<min<<std::endl;
return 0;
}
Upvotes: 0
Reputation: 7197
Generally you need to do the following:
Max
and Min
values.Min
with a very big value, e.g. 2147483647, and Max
to a very small value, e.g. -2147483648.input
with Min
, if input
is smaller than Min
, update Min
. Do the reverse with Max
.That's it.
Upvotes: 0