Print int in C without Printf or any functions

I have an appointment where I need to print an integer in C without using printf, putchar, etc. No header files can be included. No function calls except everything I wrote. I have one function my_char that I use (possibly incorrectly), but it prints a character. I currently have the following code that prints the number back. 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); } 
+4
source share
3 answers

Instead of calling my_char () in a loop, instead "print" the characters to the buffer, and then iterate over the buffer back to print it.

Turns out you can't use arrays. In this case, you can determine the maximum power of 10 (i.e. log10) using a loop. Then use this to work backward 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; } 
+5
source

One option might be to do this recursively, so the number will be printed in the correct order.

In this case, instead of a do / while loop, you will have a construction more similar to this, with the base case num = 0.

 if(num==0) return; j = num % 10; c = j + '0'; my_int(num/10); my_char(c); 

Edit: Noticed that you are not allowed to use recursion. It's a little ugly, but you can check the numbers in a number and then scroll back through the number.

To find the number of digits,

 int digitDivide = 1; int tempNum = num; while(tempNum>0){ tempNum= tempNum/10; digitDivide=digitDivide*10; } 

and then use this to scroll the number as follows:

 digitDivide = digitDivide/10; while(digitDivide>0){ tempNum = (num/digitDivide)%10; c = j + '0'; my_char(c); digitDivide=digitDivide/10; } 
+2
source

You can convert int to char *, char * and display this char *:

 char *put_int(int nb) { char *str; str = malloc(sizeof(char) * 4); if (str == NULL) return (0); str[0] = (nb / 100) + '0'; str[1] = ((nb - ((nb / 100 * 100 )) / 10) + '0'); str[2] = ((nb % 10) + '0'); return (str); } void put_str(char *str) { while (*str) write(1, str++,1); } int main(void) { put_str(put_int(42)); return (0); } 
0
source

Source: https://habr.com/ru/post/1433264/


All Articles