How to I make a recursive version of this function?


Code:
int Exp(int n, int a)
{
int i, res = 0;
for (i=1 ; i<=n; i++)
res+=( a+i/n)*(a+i/n);
return res;
}


I tried to, but the cmd crashes for some reason:


Code:
#include <stdio.h>
int func ( int x, int n);

int func ( int x, int n)
{
   int i;
   for ( i=0; i>=n; i++)
   x*= x;
   
   return x;
}

int *Exp ( int a, int n, int i)
{
   int *ptr;
   if (i>n)
   return (*ptr = 0);
   else
    {
     Exp ( a, n, i++);
     *ptr += func( (a+(i/n)), 2);
     return *ptr;
    }
   
   
}

main()

{
   printf ( "%d \n", *Exp ( 5, 10, 1) );
}
The crash is probably because you never set up your pointer correctly, so when you dereference it, it could be pointing anywhere.

That said, I'm also fairly certain that the code you've written out here does not correctly re-implement your original function.
this will probably just be unrolled by your compiler to the same code underneath.


Code:

#define exp(n, a) exp_real(n, a, 0, 0)

int exp_real(int n, int a, int i, int res)
{
   res+=(a+i/n)*(a+i/n);
   return (i < n) ? exp_real(n, a, i+1, res) : res;
}
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement