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.
A:
/* C program to print a long int number using putchar() only*/
#include <stdio.h>
void print(long n)
{
// If number is smaller than 0, put a - sign and
// change number to positive
if (n < 0) {
putchar('-');
n = -n;
}
// If number is 0
if (n == 0)
putchar('0');
// Remove the last digit and recur
if (n/10)
print(n/10);
// Print the last digit
putchar(n%10 + '0');
}
No comments:
Post a Comment