Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Thursday 28 March 2019

Print a long int in C using putchar() only

Print a long int in C using putchar() only

C program:

#include <stdio.h>

void print(long n)
{
    /* If the number is smaller than 0, put a - sign and change number to positive */
    if (n < 0) {
        putchar('-');
        n = -n;
    }

    if (n/10)
        print(n/10);

    // Print the last digit
    putchar(n%10 + '0');
}

int main()
{
    long int n = 12045;
    print(n);
    return 0;
}

Output:

12045


0 comments:

Post a Comment