Printing a number without using *printf

this would result correct order:

void print_int(int num){
    int a = num;

    if (num < 0)
    {
       putc('-');
       num = -num;
    }

    if (num > 9) print_int(num/10);

    putc('0'+ (a%10));
 }

Simply use the write() function and format the output yourself.


If your libc contains an itoa() function, you can use it to convert an integer to a string.
Otherwise you'll have to write the code to convert a number to a string yourself.

itoa() implementation from C Programming Language, 2nd Edition - Kernighan and Ritchie page 64:

/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
   int i, sign;

   if ((sign = n) < 0)  /* record sign */
      n = -n;           /* make n positive */
   i = 0;
   do {  /* generate digits in reverse order */
      s[i++] = n % 10 + '0';  /* get next digit */
   } while ((n /= 10) > 0);   /* delete it */
   if (sign < 0)
      s[i++] = '-';
   s[i] = '\0';
   reverse(s);
}

Well, its not hard to do for integers, but the job is a fair bit more complicated for floating point numbers, and someone has already posted a pointer to an explanation for that. For integers, you can do something like this:

void iprint(int n)
  { 
    if( n > 9 )
      { int a = n / 10;

        n -= 10 * a;
        iprint(a);
      }
    putchar('0'+n);
  }

Tags:

C