I am building a program that allows the user to enter ages of up to one hundred people. The program then should keep track of the amount of each age. My program is giving me incorrect results?
#include <iostream>
usingnamespace std;
int main ()
{
constint TOTALYEARS = 100; //constant for array max
int currentAge; //variable for the current age entry
int numOfAges = 0; //count for the total array entrys
int ageFrequency[TOTALYEARS]; //array to hold age values
//input users age entrys
cout << "Please input an age from one to 100 or -99 to stop" << endl;
cin >> currentAge;
while (currentAge != -99)
{
ageFrequency[currentAge-1] = ageFrequency[currentAge-1] + 1;
cout << "Please input an age from one to 100. input -99 to stop" << endl;
cin >> currentAge;
numOfAges = numOfAges + 1; //increments to hold the total amount of entrys
}
//Loop to count a certain ages frequency
for (int pos = 0; pos <= numOfAges; pos++)
ageFrequency[currentAge-1] = 0;
//Prints the results of the tally
for (int ageCounter = 0; ageCounter < numOfAges; ageCounter++)
{
if (ageFrequency[ageCounter] >= 0)
cout << "The number of people " << ageCounter + 1 <<" years old is " << ageFrequency[ageCounter] << endl;
}
return 0; //End program!
}
#include <iostream>
// using namespace std;
int main ()
{
constint TOTALYEARS = 100; //constant for array max
int currentAge; //variable for the current age entry
// int numOfAges = 0; //count for the total array entrys
// int ageFrequency[TOTALYEARS]; //array to hold age values
int ageFrequency[TOTALYEARS] = {0}; // *** initialise with all zeroes ***
//input users age entrys
std::cout << "Please input an age from one to 100 or -99 to stop\n" ; // << endl;
std::cin >> currentAge;
while (currentAge != -99)
{
if( currentAge < 1 || currentAge > 100 ) std::cout << "age must be in range [1,100]\n" ; // **** added ****
else ageFrequency[currentAge-1] = ageFrequency[currentAge-1] + 1;
std::cout << "Please input an age from one to 100. input -99 to stop\n" ; // << endl;
std::cin >> currentAge;
// numOfAges = numOfAges + 1; //increments to hold the total amount of entrys
}
///////////////////// remove this ////////////////////////
//Loop to count a certain ages frequency
// for (int pos = 0; pos <= numOfAges; pos++)
// ageFrequency[currentAge-1] = 0;
///////////////////// remove this ////////////////////////
//Prints the results of the tally
// for (int ageCounter = 0; ageCounter < numOfAges; ageCounter++)
for (int ageCounter = 0; ageCounter < TOTALYEARS; ageCounter++)
{
// if (ageFrequency[ageCounter] >= 0)
if( ageFrequency[ageCounter] > 0 )
std::cout << "The number of people " << ageCounter + 1 <<" years old is " << ageFrequency[ageCounter] << '\n' ; // endl;
}
// return 0; //End program! *** implicit ***
}