C program to print a long variable using putchar function only

  • C program to print a long variable using putchar function only, without using any standard library functions except putchar function.

Required knowledge: purchar function.
Algorithm to print a long variable using putchar function only.
  • Check if input number(N) is negative number. if N us negative them print '-' character.
  • If N is zero, then print '0' character.
  • Remove last digit of N using % operator (N%10) an pass the remaining numbers to recursive call. Repeat these steps, until N >= 0;

C program to print a long variable using putchar function only.

#include <stdio.h>

void my_putchar(long var) {
    
    /* print '-' for negative numbers */
    if (var < 0) {
        putchar('-');
        var = var * -1;
    }
 
    /* Print Zero */
    if (var == 0)
        putchar('0');
 
    /* First remove the last digit of number and print 
    the remaining digits using recursion, then print
    the last digit
 */ 
    if (var/10)
        my_putchar(var/10);
 
    putchar(var%10 + '0');
}
 
// Driver program to test abvoe function
int main() {
    long var;
    
    printf("Enter a long integer\n");
    scanf("%ld", &var);
    my_putchar(var);
    
    return 0;
}
Output
Enter a long integer
125368
125368