Write an iterative function char* conversion(unsigned int num, int base),
that converts an integer num into any base (base <=10).
How to transform the following recursive function conversion() into iterative:

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

Edited 11 Months Ago by negru

You could form a string and print the reversed string ...
(i.e. similar to using a 'stack' to unwind the recursive calls)
like this:

#include <stdio.h>

/*
    Write an iterative function char* conversion(unsigned int num, int base),
    that converts an integer num into any base (base <=10).

    How to transform the following recursive function conversion() 
    into (an) iterative:
*/


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

/* assumes number is greater than base ... */
void conversion_iterative( unsigned num, unsigned base )
{
    char buf[64]; /* make extra large enough to hold digits */
    int i = 0, size = 0;
    while( num / base )
    {
        buf[size++] = num % base + '0';
        num /= base;
    }
    buf[size++] = num % base + '0';
    buf[size] = 0; /* '\0' terminate */

    /* now reverse string */
    --size;
    while( i < size )
    {
        char tmp = buf[i];
        buf[i] = buf[size];
        buf[size] = tmp;
        ++i, --size;
    }
    printf( "%s", buf );
}



int main()
{
    unsigned num, base;
    printf( "num = " );
    if( scanf( "%u", &num ) == 1 && getchar() == '\n' )
    {
        do
        {
            printf( "base = " );
            if( scanf( "%u", &base ) != 1 )
            {
                printf( "Numbers only here please in range 2..10\n" );
                while( getchar() == '\n' ); /* flush 'stdin' ... */
            }
        }
        while( base < 2 || base > 10 );

        conversion( num, base );
        putchar( '\n' );
        conversion_iterative( num, base );
    }


    return 0;
}

Edited 11 Months Ago by David W

This question has already been answered. Start a new discussion instead.