even summation with recursive function in c++


by NewDesigner
Tags: function, recursive, summation
NewDesigner
NewDesigner is offline
#1
May6-08, 05:53 PM
P: 1
Hi,

I'm a beginner in C++.
I wan't to write this program:

Write a program that asks the user to enter n numbers –where n entered by the user- and calculates the sum of even numbers only. main function asks the user to enter n and then calls the recursive function Sum to read the values entered by the user. The function Sum returns the summation of even numbers only. At the end, main prints the summation that is returned by the recursive function.

Sample run:

How many numbers do you have:? 6
Enter number:3
Enter number:2
Enter number:9
Enter number:5
Enter number:6
Enter number:8
Sum of odd numbers = 16

I solve this question in that way, and i know it's wrong. can any body help me please?

PHP Code:
#include<iostream>

using namespace std;

double sum(int);

int main()
{
    
int n;

    
cout << "How many numbers do you have? ";
    
cin >> n;

    
sum(n);

    
cout << "Sum of even numbers = " << sumEven << endl;

    return 
0;
}

double sum(int a)
{
    
int num;
    
double sumEven=0;
    
double sumOdd=0;

    
cout << "Enter number: ";
    
cin >> num;

    if(
num%2==0)
    {
        
sumEven += num;
        
sum(num);
    }

    else if(
num%2==1)
    {
        
sumOdd += num;
        
sum(num);
    }
        
    return 
sumEven;

Phys.Org News Partner Science news on Phys.org
Going nuts? Turkey looks to pistachios to heat new eco-city
Space-tested fluid flow concept advances infectious disease diagnoses
SpaceX launches supplies to space station (Update)
arunbg
arunbg is offline
#2
May7-08, 10:25 AM
P: 602
Few hints

1) Decrement your argument 'a' each time you get a number , otherwise the recursion executes infinitely. you must have a stopping condition.

2)Use sumEven (sumOdd also if you require sum of odd nos) as an argument in your function, rather than declaring it as a local variable. This way you will be able to use the same variable in each function (retaining previous value). Local declaration creates a new variable each time the function is called.


Register to reply

Related Discussions
Recursive probability function Set Theory, Logic, Probability, Statistics 1
Simplifying a recursive function Calculus & Beyond Homework 10
what the hell is going on with this recursive function Set Theory, Logic, Probability, Statistics 17
Recursive Function Computing & Technology 4