Write a C function print(n) that takes a long int number n as argument, and prints it on console. The only allowed library function is putchar(), no other function like itoa() or printf() is allowed. Use of loops is also not allowed.
We strongly recommend to minimize the browser and try this yourself first.
This is a simple trick question. Since putchar() prints a character, we need to call putchar() for all digits. Recursion can always be used to replace iteration, so using recursion we can print all digits one by one. Now the question is putchar() prints a character, how to print digits using putchar(). We need to convert every digit to its corresponding ASCII value, this can be done by using ASCII value of ‘0’. Following is complete C program.
One important thing to note is the sequence of putchar() and recursive call print(n/10). Since the digits should be printed left to right, the recursive call must appear before putchar() (The rightmost digit should be printed at the end, all other digits must be printed before it).
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Print "Hello World" in C/C++ without using any header file
- C Program to print numbers from 1 to N without using semicolon?
- Write your own memcpy() and memmove()
- How to write a running C code without main()?
- Convert a floating point number to string in C
- Integer Promotions in C
- Commonly Asked C++ Interview Questions | Set 1
- Bitwise Operators in C/C++
- Interesting Facts about Macros and Preprocessors in C
- C Language Introduction
- C Programming Language Standard
- Is it fine to write "void main()" or "main()" in C/C++?
- Implement your own itoa()
- Write a C program that does not terminate when Ctrl+C is pressed
- How to measure time taken by a function in C?
Improved By : Prashant Singh 24