I have almost figured this program out...but I need to be able to return the values from the function. It should return the number of perfect scores there were (100's). I am not sure how to do this...any help would be great!
#include <iostream>
usingnamespace std;
int countPerfect(int perfect); //Function prototype
int main()
{
int score;
constint TEST_SCORES = 10;
int testScores[TEST_SCORES]; // holds test scores for 10 tests
cout << "Enter ten " << TEST_SCORES
<< " test scores. " ;
for (score = 0; score < TEST_SCORES; score++)
{
cin >> testScores[score];
if (testScores[score] < 0 || testScores[score] > 100)
{
cout << "Please enter a score higher than 0 and lower than 100. ";
cin >> testScores[score];
}
}
// I need to be able to return the values from countPerfect
system("pause");
return 0;
}
int countPerfect(int perfect)
{
if (perfect == 100)
return 1;
elsereturn 0;
}
You need to declare an int variable to store the number of perfect scores then go in to a loop that loops TEST_SCORES number of times and call the function countPerfect on each element.
The for loop needs to be as for(int i = 0; i < TEST_SCORES; i++)
Then you need to call countPerfect for each of the elements of testScores.
Post again with what you tried if you're having problems.
#include <iostream>
usingnamespace std;
int countPerfect(int nums[], int perfect); //Function prototype
int main()
{
int score, perfect;
constint TEST_SCORES = 10;
int testScores[TEST_SCORES]; // holds test scores for 10 tests
cout << "Enter ten " << TEST_SCORES
<< " test scores. " ;
for (score = 0; score < TEST_SCORES; score++)
{
cin >> testScores[score];
if (testScores[score] < 0 || testScores[score] > 100)
{
cout << "Please enter a score with a value from 0 to 100. ";
cin >> testScores[score];
}
}
for (int i = 0; i < TEST_SCORES; i++)
{
perfect = countPerfect(testScores, TEST_SCORES);
}
cout << "The number of perfect scores was" << perfect;
system("pause");
return 0;
}
int countPerfect(int nums[], int perfect)
{
for (int index = 0; index < perfect; index++)
if (nums[index] == 100)
return 1;
elsereturn 0;
}
..the code above is absolutely correct!!!
except it it only returning 1, not adding 1 each time?
int countPerfect(int nums[], int perfect)
{
for (int index = 0; index < perfect; index++)
if (nums[index] == 100)
return 1;
else
return 0;
}
this function is correct .
it starts from nums[0] to num[99] ,when there's a perfectnumber(100),it returns 1;not add 1.
any question?
Ok I see what you're trying to do there. See you have return 1 and return 0. Once the control hits one of those statements it will exit the program regardless of the loop.
Change your function to this
1 2 3 4 5 6
void countPerfect(int nums[], int index, int &perfect)
{
for (int i = 0; i < index; i++)
if (nums[i] == 100)
perfect++;
}
then instead of this
1 2 3 4
for (int i = 0; i < TEST_SCORES; i++)
{
perfect = countPerfect(testScores, TEST_SCORES);
}