The sum() prototype is shown below, the problem asks for the implemention of the subroutine which returns the sum of the odd numbers in a list of integers.
My input is for example (-2,5,-7,0,11,-1,-3,12) in total the sum of the odd numbers should = 5
1 2 3 4 5 6 7 8 9 10 11
int sum (const list <int>&);
int main()
{
list <int> L; int x;
while (cin >> x) L.insert (L.end (), x );
cout << "sum = " << sum (L) << endl;
return 0;
}
Overall, trying to understand the code and how to do this. I have a written explanation of this, but would like to see code to put it together. I would assume you need to put if( num % 2 == 1) to determine the odd numbers, but before that I am a bit lost.
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
I found the second link to be the most help.
You appear to have left out the function "sum". With out this one can only guess at what you did and how it works. And since your question as about "Implementation of subroutine: sum()" it would be important to include it.
Also when you post a program it helps to post the whole program that can be compiled. Sometimes testing the program can answer questions or fiind other problems.
Reading over your post I now see what you are asking for. I apologize for missing it the first time. I was late and I was not reading correctly.
For your function take everything in line 1 up to the semicolon and this is the start of your function definition. After the & you will have to add a name for the list to use in the function.
Inside the function you will need a variable to hold the sum of the negative numbers. I used a for loop to iterate through the list. You are correct in thinking that if( num % 2 == 1) will be needed to get the odd numbers, but that is only half. It will get the positive numbers, but skips the negative numbers. What you will need is if (it % 2 == 1 || it % 2 == -1). Then it will work.
Put something together for the function. Do not worry if it is wrong we can fix it. I am more interested in seeing what you can do.