Will
Will

Reputation: 103

Recursive function in c++

All,

I'm writing a recursive function to do the following:

//addbig( ) -- This function is sent an array of integers and the length of the array.  
//It returns the sum of all integers in the array that are larger than 1000.

Somehow my function is not working. It is giving me zero as the output.

long addbig (const int arrInt[],int l)
{
        if (l == 0)
            return 0;
    else if(arrInt[l]>1000)
        return  arrInt[l] + addbig (arrInt,l-1);
    else
        return  addbig (arrInt,l-1);
}

My integer array is:

 int  arrInt[10]={1000,1,1000,2,1000,3,1000,4,1000,5};

Could anybody shed some light as to why this is not working, and help me a bit. haha no pun intended

Upvotes: 0

Views: 179

Answers (4)

RouteMapper
RouteMapper

Reputation: 2560

Your base case is wrong. I fixed it below. Note: none of the numbers in arrInt are greater than 1000, so you will always get zero as output.

long addbig (const int arrInt[],int l)
{
        if (l <= 0)
            return 0;
    else if(arrInt[l-1]>1000)
        return  arrInt[l-1] + addbig (arrInt,l-1);
    else
        return  addbig (arrInt,l-1);
}

Upvotes: 0

user2972135
user2972135

Reputation: 1461

This can help you :D

#include <iostream>

using namespace std;

long addbig(const int arrInt[], int l)
{
    if (l == 0)
        return 0;
    else if (arrInt[l - 1] > 1000)
        return arrInt[l - 1] + addbig(arrInt, l - 1);
    else
        return addbig(arrInt, l - 1);
}

int main()
{
    int  arrInt[10] = {1001, 1, 2000, 2, 1000, 3, 1000, 4, 1000, 5};

    cout << addbig(arrInt, 10) << endl;

    return 0;
}

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

long addbig( const int a[], size_t n )
{
   const int LIMIT = 1000;
   return ( n == 0 ? 0 : a[0] > LIMIT + addbig( a + 1, n - 1 ) );
}

Upvotes: 0

Zac Howland
Zac Howland

Reputation: 15870

First, none of the numbers in your test array are larger than 1000. So you would get 0.

Second, you are invoking UB:

long addbig (const int arrInt[],int l)
{
    if (l == 0)
        return 0;
    else if(arrInt[l] > 1000) // PROBLEM!
        return  arrInt[l] + addbig (arrInt,l-1);
    else
        return  addbig (arrInt,l-1);
}

If l is your array length, the first time you call this function will access 1 element beyond the array. What I think you want is:

long addbig (const int arrInt[],int l)
{
    if (l == 0)
        return 0;
    return addbig(arrInt, l - 1) + (arrInt[l - 1] > 1000 ? arrInt[l - 1] : 0);
}

Upvotes: 4

Related Questions