1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C: Recursive function into iterative

  1. Dec 19, 2015 #1
    1. The problem statement, all variables and given/known data
    Write an iterative function char* conversion(unsigned int num, int base),
    that converts an integer num into any base (base <=10).

    2. Relevant equations


    3. The attempt at a solution
    How to transform the following recursive function conversion() into iterative:
    Code (Text):

    #include <stdio.h>

    void conversion(unsigned num, unsigned base)
    {
      if (num / base)
        conversion(num / base, base);
      printf("%u", num % base);
    }

    int main()
    {
      unsigned num, base;
      printf("num=");
      scanf("%u", &num);
      do{
         printf("base=");
         scanf("%u", &base);
        }
      while (base < 2 || base > 10);
      conversion(num, base);
      return 0;
    }
     
     
  2. jcsd
  3. Dec 19, 2015 #2
    When I have convert between recursive and iterative thinking I find it's best to think about:
    * what is changing between the function calls
    * how do we know when to terminate and return

    So in your example with every recursive call to conversion(num, base) you do num/base so this should be done every loop.

    You return when num/base truncates to 0 so use this as the condition in your loop.
     
  4. Dec 19, 2015 #3

    rcgldr

    User Avatar
    Homework Helper

    If goal is to follow the logic in the recursive function, use an array like a stack, filling the array from [0] to [n-1], printing the array from [n-1] to [0]. Assuming unsigned is 32 bits, you'll need an array of 32 characters to hold the digits for base 2, less for other bases, so make the array size 32 characters.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: C: Recursive function into iterative
  1. C++ Lists & Iterators (Replies: 24)

  2. Recursive function (Replies: 16)

Loading...