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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- putchar() function in C
- Difference between const int*, const int * const, and int const *
- Difference between "int main()" and "int main(void)" in C/C++?
- Difference between sizeof(int *) and sizeof(int) in C/C++
- Change/add only one character and print '*' exactly 20 times
- How to write long strings in Multi-lines C/C++?
- Write your own strlen() for a long string padded with '\0's
- Is there any need of "long" data type in C and C++?
- Working of Keyword long in C programming
- Implicit return type int in C
- What’s difference between “array” and “&array” for “int array” ?
- Assigning multiple characters in an int in C language
- int (1 sign bit + 31 data bits) keyword in C
- C/C++ program to find the size of int, float, double and char
- How to make a C++ class whose objects can only be dynamically allocated?
- Why only subtraction of addresses allowed and not division/addition/multiplication
- How will you print numbers from 1 to 100 without using loop?
- Write a C program to print "Geeks for Geeks" without using a semicolon
- How to print % using printf()?
- Print "Even" or "Odd" without using conditional statement
Improved By : Prashant__Singh