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
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);
}
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);
}
long addbig( const int a[], size_t n )
{
const int LIMIT = 1000;
return ( n == 0 ? 0 : a[0] > LIMIT + addbig( a + 1, n - 1 ) );
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.