Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print a long int in C using putchar() only
Here we will see how to print long int value using the putchar() function in C. We can easily print the value of some variables using printf() in C, but here the restriction is, we cannot use any other function except putchar().
As we know that the putchar() is used to print only characters. We can use this function to print each digit of the number. When one numeric value is passed, we have to add character '0' with it to get the ASCII form.
Syntax
void print_long(long value); int putchar(int character);
Example
The following program demonstrates how to print a long integer using only putchar() function −
#include <stdio.h>
void print_long(long value) {
if(value < 0) {
putchar('-');
value = -value;
}
if(value != 0) {
print_long(value/10);
putchar((value%10) + '0');
}
}
int main() {
long a = 84571;
long b = -12345;
printf("Positive number: ");
print_long(a);
putchar('<br>');
printf("Negative number: ");
print_long(b);
putchar('<br>');
return 0;
}
Positive number: 84571 Negative number: -12345
How It Works
- The function uses recursion to extract digits from right to left
- Each digit is converted to its ASCII character by adding '0'
- Negative numbers are handled by printing '-' first and making the value positive
- The recursion ensures digits are printed in correct order (most significant first)
Key Points
- putchar() can only print one character at a time
- Adding '0' to a digit converts it to its ASCII representation
- Recursive approach naturally handles digit ordering
- Special handling needed for negative numbers and zero
Conclusion
Using putchar() to print long integers requires recursive digit extraction and ASCII conversion. This technique demonstrates how character-based output can handle numeric data effectively.
