Recursive problem!

It's workable, but the sum of 5 integers is wrong!
I put in 5 integers like:1,2,3,4,5
but the sum by recursion is 3681871?
please correct my code, thanks!



---------------

#include
using namespace std;
int add_arr(int n);
int arr[5];
int main()
{
int i;
cout << "Please input the 5 integers you gonna add them: "<< endl;

for (i=0 ; i<5 ; i++)
{
cout << "#" << i+1 << ": ";
cin >> arr[i];
};

cout <<"Your Input are:" << arr[0] <<" "<< arr[1] <<" "<< arr[2] <<" "<< arr[3] <<" "<< arr[4];
cout << "The Sum is: " << add_arr(i);
return 0;

}
int add_arr(int n)
{
if (n == 0)
return arr[0];
return arr[n] + add_arr(n-1);

}

Comments

  • : cout << "The Sum is: " << add_arr([red]i[/red]);
    [purple]the value of i is 5 here. what it should be?
    [/purple]
    [hr][purple]~Donotalo()[/purple]

  • In addition to Donatello,

    [code]
    : #include
    : using namespace std;
    : int add_arr(int n);
    : int arr[5];
    : int main()
    : {
    : [red]//int i;[/red]
    : cout << "Please input the 5 integers you gonna add them: "<< endl;
    :
    : for ([red]int [/red]i=0 ; i<5 ; i++)
    : {
    : cout << "#" << i+1 << ": ";
    : cin >> arr[i];
    : };
    :
    : cout <<"Your Input are:" << arr[0] <<" "<< arr[1] <<" "<< arr[2] <<" "<< arr[3] <<" "<< arr[4];
    : cout << "The Sum is: " << add_arr(i); [red]//Will yield an error[/red]
    : return 0;
    :
    : }
    : int add_arr(int n)
    : {
    : if (n == 0)
    : return arr[0];
    : return arr[n] + add_arr(n-1);
    :
    : }
    [/code]

    Put the variable i in the for loop and the compiler will give you a hint.

    See ya,
    bilderbikkel

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories