Basic Stats Problem

Been looking at this few lines all day.It doesn't add up in my head, but when I run it, it's perfect. Can anyone explain this line by line or point out where i might be getting lost?

#include <iostream>

using namespace std;

int main()
{
int N;
cout<<"Enter N: \n";
cin>>N;
int x=0;

cin>>x;
int minVal = x;
int maxVal = x;

for(int y=1; y<N; ++y)
{
int a;
cin>>a;
x += a;
if(a<minVal)
{
minVal=a;
}

if(a>maxVal)
{
maxVal=a;
}
}
cout<<"Mean: "<<(double)x/N<<"\n";
cout<<"Min: "<<minVal<<"\n";
cout<<"Max: "<<maxVal<<"\n";
cout<<"Range: "<<(maxVal-minVal)<<"\n";



return 0;
}

First off, how can x be both (=0) and (cin>>X)?

Also, minVal, maxVal, & x are all assigned to a value of zero, but somehow they all ad up to give mean when divided by N.

I give up...

the int x=0 isn't really necessary. It could just be written like this:
1
2
int x;
cin >> x;


It doesn't matter though, it's more stylistic, because when the user inputs for x, cin >> x just replaces 0 with whatever is entered. However, it's also not proper coding style because no error checking is being done to make sure that what is entered is an int, but I'm guessing it's probably an early assignment that doesn't take into account exception handling.

In terms of your second question, minVal, maxVal, and x are all initially assigned to the same value since minVal and maxVal are initially assigned the value of x, but later in the program the values can change based on the conditions set. If a is less than x, then minVal gets reassigned the value of a, and if a is greater than maxVal, maxVal gets reassigned the value of a.

Hope that helps.
Thanks randisking,

I think i know where I might got lost.

The x of (x=+a)does not modulate the x of (minValue=x) becasue the former is nested.

For example, if I enter 3 for (N) and then 2,4,6.

The 2 remains as the minValue throughout because the x in (x=x+a) is nested and therefore doesn't effect other's x outside its own block like (minValue = x).

I hope this is correct. exhausted...ha

Topic archived. No new replies allowed.