Thread: Recursive Programming -- Power of function

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    21

    Recursive Programming -- Power of function

    I am using Stephen Prata's C Primer Plus (5th Edition) to teach myself C Programming. I am not a student (I wish), and am seeing myself stuck!

    (bear with me, this is my first post so I hope I get the formatting right)

    I have this code:

    Code:
    #include <stdio.h>
    
    double power(double a, int b);  /* ANSI prototype */
    
    int main(void)
    {
      double x, xpow;
      int n;
    
      printf("Enter a number and the integer power");
      printf(" to which\nthe number will be raised. Enter q");
      printf(" to quit.\n");
      while (scanf("%lf%d", &x, &n) == 2)
      {
           xpow = power(x,n);       /* function call           */
           printf("%.3g to the power %d is %.5g\n", x, n, xpow);
           printf("Enter next pair of numbers or q to quit.\n");
      }
      printf("Hope you enjoyed this power trip -- bye!\n");
      return 0;
    }
    
    // test runs:
    // 1 & 1 == 1
    // 5 & 5 == 3125
    // 6 & 7 == 2.7994e+005
    
    double power(double a, int b)   
    {
      double pow = 1.0;
      int i;
      
    	if ((b == 0) && (a == 0)) pow = 1.0;
    	else if (a == 0) pow = 0.0;
    	else if (b > 0)
          for(i = 1; i <= b; i++)
           pow *= a;
      else    /* b < 0 */
          pow = 1.0 / power(a, - b);
      return pow;   
    }
    I am learning Recursion and the books suggest transforming the above using a recursive approach; I just cant get my head around it. any suggestions would be highly appreciated.

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    You should concentrate on the loop

    Code:
     for(i = 1; i <= b; i++)
           pow *= a;
    on each iteration it multiplys the old value to a


    instead of the loop you can call power recursively to calculate the previous value, multiply it with a and return result
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    May 2007
    Posts
    21
    would you mind showing me in code?

    OOPS -- noticed I posted this in C++ and not the C section. sorry
    Last edited by Hansie; 05-21-2007 at 03:04 PM.

  4. #4
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    First, format this so that me/you/we know what we're looking at. That, and get your original in better shape before going for a recursive.
    Code:
    /*Decide between tabs/spaces, and stick to it.*/
    double power(double a, int b)   
    {
    	double pow = 1.0;
    	int i;
    
    /* This if() has no effect, pow is already 1.0...*/
    	if((b == 0) && (a == 0)) pow = 1.0;
    /* This if() is partially incorrect. 0^0 != 0, but it's a special case.*/
    	else if (a == 0) pow = 0.0;
    	else if (b > 0)
    	{
    		for(i = 1; i <= b; i++)
    			pow *= a;
    	}
    /* The comment on the else is wrong. b may == 0 here - if it does, this will stack fault. */
    	else /* b < 0 */
    		pow = 1.0 / power(a, - b);
    	return pow;   
    }
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  5. #5
    Banned
    Join Date
    May 2007
    Location
    Berkeley, CA
    Posts
    329
    Quote Originally Posted by Cactus_Hugger View Post
    First, format this so that me/you/we know what we're looking at. That, and get your original in better shape before going for a recursive.
    Code:
    /*Decide between tabs/spaces, and stick to it.*/
    double power(double a, int b)   
    {
    	double pow = 1.0;
    	int i;
    
    /* This if() has no effect, pow is already 1.0...*/
    	if((b == 0) && (a == 0)) pow = 1.0;
    /* This if() is partially incorrect. 0^0 != 0, but it's a special case.*/
    	else if (a == 0) pow = 0.0;
    	else if (b > 0)
    	{
    		for(i = 1; i <= b; i++)
    			pow *= a;
    	}
    /* The comment on the else is wrong. b may == 0 here - if it does, this will stack fault. */
    	else /* b < 0 */
    		pow = 1.0 / power(a, - b);
    	return pow;   
    }

    Technically

    Code:
    else if (b > 0)
    	{
    should be

    Code:
    else if (b > 0) {
    This subtle point in style only matters if you are doing coding for a major corporation. But whatever. I would have written the function like:

    Code:
    double power( double x, int n )
          {
          if ( n > 0 )
             return x * power( x, n- 1 );
          else if ( n < 0 )
             return ( 1/x ) * power( x, n + 1 );
          else
             return 1;
          }
    Last edited by Overworked_PhD; 05-21-2007 at 04:35 PM.

  6. #6
    Registered User
    Join Date
    May 2007
    Posts
    21
    Excellent feedback -- and so fast! I am impressed; Also highly impressed about the depth of knowledge and help!

  7. #7
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    Quote Originally Posted by Overworked_PhD View Post
    Technically

    Code:
    else if (b > 0)
    	{
    should be

    Code:
    else if (b > 0) {
    This subtle point in style only matters if you are doing coding for a major corporation.
    What in the world are you talking about?
    There are 10 types of people in this world, those who cringed when reading the beginning of this sentence and those who salivated to how superior they are for understanding something as simple as binary.

  8. #8
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    Quote Originally Posted by Overworked_PhD View Post
    Technically
    Code:
    else if (b > 0)
    	{
    should be
    Code:
    else if (b > 0) {
    This subtle point in style only matters if you are doing coding for a major corporation.
    (To clarify) Technically, both are correct. The compiler won't care two bits which is used. The only thing to care is a human. Religious wars have been started over which brace style is the best. Looking through some of the code I have, it seems that some of the SDL sub libraries are written using yours. It also appears that libpng and wxWindows are written in mine. (In the small samples of code that I checked, at least.) Neither is particularly predominant, and is the choice of the project developers/leaders. I perfer the former as it aligns the braces, letting me easily match braces, and spaces things out vertically a bit more. See One True Brace Style on wikipedia.
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  9. #9
    Banned
    Join Date
    May 2007
    Location
    Berkeley, CA
    Posts
    329
    Quote Originally Posted by Cactus_Hugger View Post
    (To clarify) Technically, both are correct. The compiler won't care two bits which is used. The only thing to care is a human. Religious wars have been started over which brace style is the best. Looking through some of the code I have, it seems that some of the SDL sub libraries are written using yours. It also appears that libpng and wxWindows are written in mine. (In the small samples of code that I checked, at least.) Neither is particularly predominant, and is the choice of the project developers/leaders. I perfer the former as it aligns the braces, letting me easily match braces, and spaces things out vertically a bit more. See One True Brace Style on wikipedia.
    Wrong. The style I mentioned is PREDOMINANT in BSD derived code. The other PREDOMINANT form is having the braces indented to mimic LISP. This style appears in GNU software.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  3. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. Recursive Ackermann's function - need help
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 03-04-2002, 04:42 AM