recursive function

I'm learn recursive function this week , and I have a problem ...
In this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
using namespace std;
#define dimension 2

int CalcuAddic(int Array[ ], int Nnumbers)
{
	int addiction=0;
	if(Nnumbers > 0)
		addiction=Array[Nnumbers-1] + CalcuAddic(Tab,Nnumbers-1);
	else
		return(addiction);
}

int main()
{
	int Array[dimension]={1,1};
	int addiction;
	for(int i=0; i< dimension; i++)
    {
        cout << "\n" << Tab[i];
    }
    cout << endl;
	addiction=CalcuAddic(Tab,dimension);
	cout << "The addiction of these elements is: " << addiction << endl;
	return(0);
    
}


the addiction is 32676, and should be 2 . what the problem ?
Last edited on
The code does not compile, inside function CalcuAddic, Tab is not defined.

The function must always return a result.

if (Nnumbers > 0) when this condition is true the function does not return a value.

That means the results are unpredictable.
1) your program won't compile.

In the following line, Tab is undefined:
 
addiction=Tab[Nnumbers-1] + CalcuAddic(Tab,Nnumbers-1);


2) In the above line you calculate addiction, but you never return it, yet you use the result of your function in that line.

PLEASE USE CODE TAGS (the <> formatting button) when posting code. It makes you code easier to read and it makes it easier to respond to you post.

How I can get the result correct ?
I make alterations
Last edited on
Show us your changes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
using namespace std;
#define dimension 2

int CalcuAddic(int Array[ ], int Nnumbers)
{
	int addiction=0;
	if(Nnumbers > 0)
		addiction=Array[Nnumbers-1] + CalcuAddic(Array,Nnumbers-1);
	else
		return(addiction);
}

int main()
{
	int Array[dimension]={1,1};
	int addiction;
	for(int i=0; i< dimension; i++)
    {
        cout << "\n" << Array[i];
    }
    cout << endl;
	addiction=CalcuAddic(Array,dimension);
	cout << "The addiction of these elements is: " << addiction << endl;
	return(0);
    
}
As I said in item #2 above, at line 9 you're not returning the value of addiction.
how i make this change ?
- This function is not recursive (if it was even supposed to be)

- Additionally, as an individual above mentioned, that function must always return a value as it has an integer return type.
@thejman250 - Yes it it. It calls itself at line 9.

@dioing - You return addiction at line 11. How is it you don't understand how to do so at line 9?
@AbstractionAnon

- Then i suppose he intended Tab to be an array of ints.

- Additionally, he probably needs to return addiction at line 9 for this to work.
Last edited on
Topic archived. No new replies allowed.