Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print an int in C without Printf or any functions

Tags:

c

int

printf

I have an assignment where I need to print an integer in C without using printf, putchar, etc. No header files allowed to be included. No function calls except for anything I wrote. I have one function my_char I am using (maybe its wrong) but it prints out a character. I currently have the following code which is printing the number out backwards. Not looking for an answer. Just looking for some direction, some help, maybe I'm looking at it completely wrong.

void my_int(int num)
{   
  unsigned int i;    
  unsigned int j;

  char c;

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

  do    
    {
      j = num % 10;
      c = j + '0';
      my_char(c);
      num = num/10;
    }while(num >0);
}
like image 324
CLZ828 Avatar asked Sep 09 '12 22:09

CLZ828


People also ask

Can we print in C without printf?

You can always use puts, fwrite, etc.

How do I print a number without printf?

Simply use the write() function and format the output yourself. Show activity on this post. I assume most people that come across this question because they have written their own serial tx functions and need to print some numbers. You will need to modify the putc call to fit with your setup.

How do you print an integer in C?

printf("Enter an integer: "); scanf("%d", &number); Finally, the value stored in number is displayed on the screen using printf() . printf("You entered: %d", number);

What can I use instead of printf in C?

puts() The function puts() is used to print the string on the output stream with the additional new line character '\n'. It moves the cursor to the next line. Implementation of puts() is easier than printf().


1 Answers

Instead of calling my_char() in the loop instead "print" the chars to a buffer and then loop through the buffer in reverse to print it out.

Turns out you can't use arrays. In which case you can figure out the max power of 10 (ie log10) with the loop. Then use this to work backwards from the first digit.

unsigned int findMaxPowOf10(unsigned int num) {
    unsigned int rval = 1;
    while(num) {
        rval *= 10;
        num /= 10;
    }
    return rval;
}

unsigned int pow10 = findMaxPowOf10(num);

while(pow10) {
    unsigned int digit = num / pow10;
    my_char(digit + '0');
    num -= digit * pow10;
    pow10 /= 10;
}
like image 56
James Avatar answered Sep 17 '22 01:09

James