Help | Site Map
Connecting Tech Pros Worldwide
 
 
LinkBack Thread Tools
  #1  
Old August 17th, 2005, 07:45 AM
kolari
Guest
 
Posts: n/a
Default Program

>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 !!

  #2  
Old August 17th, 2005, 10:25 AM
Michael Wohlwend
Guest
 
Posts: n/a
Default Re: Program

kolari wrote:
[color=blue]
> 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 !![/color]

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


  #3  
Old August 17th, 2005, 03:45 PM
shanemjtownsend@hotmail.com
Guest
 
Posts: n/a
Default Re: Program

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;
}

  #4  
Old August 18th, 2005, 07:15 AM
kolari
Guest
 
Posts: n/a
Default Re: Program

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)..
....
....

 

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles