Program

K

kolari

In an intrivew I had informed to add a array content using recurtion .

I wrote like this

void sum(int a[],int n)
{
static sum;
if (n==0)
return;

sum+=a[n-1];
sum(a,n-1);
}
i think it will work then he told to write without static variable.

then I wrote like this
int sum(int a[],int n)
{
if(n==0)
return 0;

return a[n-1]+sum(a,n-1);
}
then he told you are gone some where wrong. and told me to write whith
out using size of the array.
On that time i could not write program, but I told him that i can
limit by specifing some end character to inform the end of limit.

Now i think It would be a right program

int sum(int a[])
{
if(a[0]==-1) /* end of character I assume to be -1*/
return 0;
return a[0]+sum(++a);
}
!! Is it a right program and give me the right result !!
 
M

Michael Wohlwend

kolari said:
Now i think It would be a right program

int sum(int a[])
{
if(a[0]==-1) /* end of character I assume to be -1*/
return 0;
return a[0]+sum(++a);
}
!! Is it a right program and give me the right result !!

I don't know if this is relevant here or not but even if your compiler is
able to optimize tail-recursion, it cannot do it here. So depending on the
size of a[] you will run out of stack space quite fast.

tail recursive would be (not tested :) :

int sum(int *a, int erg)
{
if (*a == -1) return erg;
return sum(a+1, erg + *a);
}

call it with: sum(data,0)

Michael
 
S

shanemjtownsend

int n = (sizeof a) / (sizeof a[0]);

will retrun you the size of the array instead of sending it through
explicitly

And your function works just fine, as far as I can see
int sum(int a[],int n)
{
if (n)
return a[n-1]+sum(a,n-1);
else
return 0;
}
 
K

kolari

that was a good idia to find the size of a array . but sum of array I
have to increment the base address which is possible in called
function.

i.e

....
....
....
....sum(++a)..
....
....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top