Thread: replacing a loop with recursion

  1. #1
    Advanced Novice linucksrox's Avatar
    Join Date
    Apr 2004
    Location
    Michigan
    Posts
    198

    replacing a loop with recursion

    I'm trying to replace my a loop in a exponent function but I'm not sure how to go about doing it... thanks for any help
    Code:
    double power(double a, double b)
    {
        double pow = 1;
        int i = 1;
        char flag = OFF;            /* the reason for using (char) is that it only takes up 1 byte */
    
        if (b == 0)
          return a;
    
        if (b < 0)
          flag = ON;
    
        if (i <= b)                      /* this loop is what's messed up... */
          pow *= power(a, i + 1);
    
        if (flag == ON)
          pow = 1 / power(a, -b);
    
        return pow;
    }
    that loop would normally be
    Code:
    for (i = 1; i <= b; i++)
      pow *= a;
    but that's my poor attempt at recursion...
    Last edited by linucksrox; 04-14-2004 at 06:11 PM.

  2. #2
    C > C++ duders ggs's Avatar
    Join Date
    Aug 2001
    Posts
    435
    try power(a, b-1);

    i dun think you need i anymore
    .sect signature

  3. #3
    Advanced Novice linucksrox's Avatar
    Join Date
    Apr 2004
    Location
    Michigan
    Posts
    198
    thanks, I finally got it. I still don't quite understand it, but it works fine.
    Code:
    double power(double a, double b)
    {
        double pow = a;
        char flag = OFF;            /* the reason for using (char) is that it only takes up 1 byte */
    
        if (b < 0)
          flag = ON;
    
        if (b > 0)
          pow *= power(a, b - 1);
    
        if (flag == ON)
          pow = 1 / power(a, -b);
    
        if (b == 0)
          pow = 1;
    
        return pow;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  3. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  4. A somewhat bizzare problem!!! - WHILE LOOP
    By bobthebullet990 in forum C Programming
    Replies: 3
    Last Post: 03-31-2006, 07:19 AM
  5. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 03:45 PM