print integer to stdout using write or putchar?
To print an integer to stdout in the C programming language, you can use either the write
or putchar
functions.
Using the write
function:
The write
function is a system call that writes data to a file descriptor. In this case, we will use file descriptor 1, which represents stdout. Here are the steps to print an integer using write
:
- Convert the integer to a string using the
sprintf
function. - Determine the length of the string using the
strlen
function. - Use the
write
function to write the string to stdout.
Here is an example code snippet that demonstrates this approach:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main() {
int num = 123;
char str[20];
sprintf(str, "%d", num);
int len = strlen(str);
write(1, str, len);
return 0;
}
Using the putchar
function:
The putchar
function is a standard library function that writes a character to stdout. To print an integer using putchar
, you need to convert each digit of the integer to a character and then write each character to stdout. Here are the steps:
- Initialize a variable
num
with the integer value. - Create a loop that extracts each digit of the integer.
- Convert each digit to a character using the ASCII representation.
- Use the
putchar
function to write each character to stdout.
Here is an example code snippet that demonstrates this approach:
#include <stdio.h>
void printInteger(int num) {
if (num < 0) {
putchar('-');
num = -num;
}
if (num / 10) {
printInteger(num / 10);
}
putchar(num % 10 + '0');
}
int main() {
int num = 123;
printInteger(num);
return 0;
}
These are two different approaches you can use to print an integer to stdout in the C programming language using the write
or putchar
functions.