man i love programming! problem solving is so much fun!
so i started out with having to make a program that took the average of any number of test scores between 1-100. ok, no problem.
but i had to idiot proof it, which i never had to do in last semesters class. alright, that shouldnt be hard to figure out.
well i get it down, and i get the if statements in there to idiot proof it. but then i notice that the way i have it written to count up and display which score to enter, whenever an invalid number is entered, it just repeats that score number for the next and ends up being off on the numbers needed. so i try and figure out how to fix it.
first i switch the positions in the if statement for the true and false path. and now i realize that if its going to be wrong then i should stop the loop and have it say that there was an error. so i put and if statement around the final calculations and text display.
but i realize i have no way to stop the loop yet. so i look at it, and i think back to how with switch statements you could end them early with a break statement, and i wondered if using that would end the loop, so i try it and voila! it works. making my program neat and idiot proof!
i'm quite proud of myself for writing up all that off the top of my head after almost a month of not programming =D
Code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//variable list
double numAmt = 0;
double testScore = 0;
double scoreTotal = 0;
double scoreNum = 0;
double average = 0;
//processing: first ask how many scores will be entered to average.
cout << "Please enter the number of test scores wished to be averaged (This should be a number 1-100): ";
cin >> numAmt;
//test to see if it is a valid number
if(numAmt < 1 || numAmt > 100)
{
cout << "Invalid Number!" << endl;
}
else
{
//Create a for loop to get each test score, any number 0 through 100
for(int x = 0; x < numAmt; x++)
{
cout << "Please enter test score #" << scoreNum+1 << " (This should be a number 0-100): ";
cin >> testScore;
//check to see if a valid number is entered
if(testScore >= 0 && testScore <= 100)
{
scoreTotal += testScore; //add the entered score to the totaled scores
scoreNum++; //add 1 to scoreNum to make it display the next number
}
else
{
cout << "Invalid Number!" << endl;
break;
}//endif
}//end of for loop
//find the average of the scores entered, but test to see if there were any errors in the score entering phase.
if(scoreNum == numAmt)
{
average = scoreTotal / numAmt;
//display the number of scores an the average
cout << "total number of test scores: " << numAmt << endl;
cout << "Average of all test scores: " << fixed << setprecision(2) << average << endl;
}
else
{
cout << "Program has ended early due to an error." << endl;
}//endif
}//end of first if statment
return 0;
}
//end of main function