This add function is supposed to return the sum of the 5 values of the iterator. It is not doing so. I'm getting a value of 0. Also, the display function is not displaying the list of numbers. How can I solve this? Thank you.
Your getNumbers() takes parameter by value. A local copy. That has no effect on the aList in main(). Pass parameter by reference.
What do you do in the main() with the int value that the addNumbers() returns? Nothing.
Your addNumbers() is equivalent to:
1 2 3 4 5 6 7 8
int addNumbers(list<int> aList)
{
if ( aList.begin() != aList.end() ) {
return *aList.begin();
} else {
// you return nothing, if list is empty. Nothing is not a int.
}
}
You cannot return from the body of the loop, because then you skip all but first element.
Complete the loop first. Then return the result.
What is the task of the displaySum()? To display the sum? To display the elements of the list? Both?
I put the return outside the for loop in addNumbers but it still returns 0. It now displays the values of the inputted integers but still displays the sum as 0. The task of the displaySum() is to display the list of numbers just entered and the sum of their values. Currently after your help, it does display the numbers but gives me a wrong sum...(0).
Here is my altered code that doesn't work. Thanks for the help:
Line 6: You're declaring aList as global, but it is never used. It's declared again inside main. You should remove line 6.
Line 41: You're going to return the first time through the loop.
36 37 38 39 40 41 42
int addNumbers(list<int> &aList)
{
int sum = 0;
for (it = aList.begin(); it != aList.end(); it++)
sum += *it; // Add to the sum each time through the loop
return sum; // Return the total when done
}
void displaySum( list<int> &aList )
{
for (it = aList.begin(); it != aList.end(); it++)
{
cout << *it << ' ';
}
int sum = 0;
cout << "The sum equals: " << sum << endl;
}
The loop does not do anything with the variable sum.
Therefore, the variable declaration can be moved after the loop.
Now it is more clear why you see the 0; you explicitly print a 0.
You have a function that returns a value. Not just any value, but the value that you want. Why don't you call that function and then use the value that you get from the function?