Malik Salah
Malik Salah

Reputation: 3

How to find sum of even numbers in a list using recursion in c++?

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

Answers (3)

Labonneguigue
Labonneguigue

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

Remy Lebeau
Remy Lebeau

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;
}

Live Demo

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

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

  • When the current node represents an even number - your code already covers this case,
  • When the current node represents an odd number - you need to return the same value as if the node is not there, and
  • When there is no current node - that's the value you'd return when the list is null or empty (i.e. zero).

You need to add return statements for the remaining two cases. Once you do that, your function would be complete.

Upvotes: 2

Related Questions