Reputation: 3
int list::Sum_Even_Values(node *head)
{
static int sum=0;
if(!isempty())
{
if(head->info %2==0)
return head->info +Sum_Even_Values(head->next);
}
}
Upvotes: 0
Views: 1242
Reputation: 133
Here is another way to achieve the same thing by passing the sum
variable by reference at every call to the function.
void sumEvenValues(Node * head, int& sum){
if (head != NULL){
if (head->info % 2 == 0){
sum += head->info;
}
sumEvenValues(head->next, sum);
}
}
Upvotes: 1
Reputation: 596352
Don't use a static
variable, as you won't be able to reset it back to 0 if you need to sum the list multiple times. Try this instead:
int list::Sum_Even_Values(node *head)
{
int sum = 0;
if (head) {
if ((head->info % 2) == 0)
sum = head->info;
sum += Sum_Even_Values(head->next);
}
return sum;
}
Upvotes: 0
Reputation: 726599
When you are writing a function that returns a value, recursive or not, you need to explore all paths through the code, not only your main "path of interest."
In your specific case you need to decide what to return
You need to add return
statements for the remaining two cases. Once you do that, your function would be complete.
Upvotes: 2