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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- putchar() function in C
- Is there any need of "long" data type in C and C++?
- Working of Keyword long in C programming
- How to write long strings in Multi-lines C/C++?
- Write your own strlen() for a long string padded with '\0's
- How to print a variable name in C?
- How to print % using printf()?
- Print 1 2 3 infinitely using threads in C
- How to Read and Print an Integer value in C
- Print 1 to 100 in C++, without loop and recursion
- Program to print last 10 lines
- How will you print numbers from 1 to 100 without using loop?
- Print "Even" or "Odd" without using conditional statement
- Condition To Print "HelloWord"
- Print calendar for a given year in C++
- How will you print numbers from 1 to 100 without using loop? | Set-2
- Print Hello World without semicolon in C/C++
- C Program to print Floyd's triangle
- C Program to print contents of file
- C Program to print environment variables
Improved By : Prashant__Singh