Basic programming help

Here is a sample output to my problem:

Please enter the make and model of the car (e.g., Toyota Prius): Toyota
Prius
Please enter the number of Toyota Prius's that we own: 8
Please enter the mpg for each car: 42 61 55 29 38 23 57 66
Toyota Prius average mpg = 46

My trouble is i don't know how to store the mpg for each car. I know im supposed to use a for loop but im not sure how to store what the user enters. Any help would be appreciated.
You could use a for loop to do the job and an array, should look something like this:

1
2
3
4
5
6
int mpg[8];
for ( int i = 0 ; i < 8 ; ++i )
{
cout<<"Enter the mpg for each car: ";
cin>>mpg[i];
}
Were not supposed to use an array. I also believe the cout statement should only be executed once. Is there any other way you can think of solving this problem?
ow, you don't want to store it in array and it you only need to find an average ?

then perhaps you should do this
1
2
3
4
5
6
7
8
9
10
int n;
int input;
int total = 0;

cin >> n;
for( int i = 0; i < n; ++ i ){
   cin >> input; total += input;
}

cout << static_cast<double>( total ) / static_cast<double> ( n ) << endl;


this code is pretty much ok, if you are not dealing with overwhelming inputs

Edit : Thanks for the notice @keskiverto
Last edited on
rmxhaha's code has a tiny little error, which makes the result undefined. I would correct it on line 3.
Thanks guys works perfectly
Topic archived. No new replies allowed.