I guess the first thing as a newbie using loops, is not to use infinite loops. Advanced coders use them sometimes, but only in certain valid situations where they know what they are doing.
Check out the tutorial page on this website, and while you are at it, read some of the reference pages as well. They are both at the top left of this page.
With loops, there are several parts - initialisation, increment and most importantly an end condition.
With
Maxim Podolski
post there are some minor improvements that could be made.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
//declare variables outside for loop so they are availble afterwards
int Counter;
const unsigned SIZE = 3;//Number of scores to input, and array sze
double Score = 0.0; //double not ints
double Sum = 0.0;
double ScoreArray[SIZE];
for (Counter = 0; Counter < SIZE; Counter++) {
cout<<"\nPlease input score #"<<Counter + 1<<"."<<endl;
cin>>Score; //There is no error checking using the cin.fail bit
ScoreArray[Counter] = Score; //Store everything in an array
Sum += Score; //Getting the total sum of all the scores combined
}//ending the for loop
double Average = Sum / SIZE; //Integer division was no good - automatic
//cast to double
cout << "The Sum is " << Sum << endl;
cout << "The average is "<<Average << endl;
cout << "The number of scores was " << SIZE;
return 0; //this is not absolutely necessary but I do it anyway
}
|
Instead of having the magic number of 3 throughout the code, it is better to make it a const variable at the start of the program, then refer to this variable where necessary.
With the for loop:
for (x=1;x<=3;x++){
The normal idiom for doing something 3 times is this, and combining the const variable:
1 2 3 4 5 6
|
const unsigned SIZE = 3;
for (int x = 0; x < SIZE; x++){
//your code here
}
|
I stored the values in array, this means you can calculate other things like standard deviation, residuals or whatever.
As the comment says - there is no error checking on the input. It is a very good idea to do this - always validate input.
Hope all goes well
Edit:
With the values in the array, you could also print them out - use a for loop to do so.