putchar() Function
The putchar() function in C writes a single character to the standard output (stdout). It is used to display characters, and it serves as a fundamental tool for basic output operations in C programming.
Syntax of putchar()
int putchar(int character);
Parameters
| Parameter | Description |
|---|---|
character | The int promotion of the character to be written. This value is internally converted to an unsigned char before writing. |
This function is equivalent to calling putc with stdout as the stream, providing a straightforward method to output individual characters.
Return Value
On success, putchar() returns the character written. If a writing error occurs, it returns EOF and the error indicator for stdout is set.
Examples for putchar()
Example 1: Writing a Single Character to Standard Output
This example demonstrates the basic usage of putchar() to output a single character to stdout.
Program
#include <stdio.h>
int main() {
putchar('A');
putchar('\n');
return 0;
}
Explanation:
- The program calls
putchar()to write the character'A'to stdout. - A newline character (
\n) is then printed to move the cursor to the next line. - This example illustrates the simplicity of printing a single character using
putchar().
Program Output:
A
Example 2: Outputting a String Character by Character
This example demonstrates how to output an entire string by iterating through each character and printing it with putchar().
Program
#include <stdio.h>
int main() {
char *str = "Hello, World!";
int i = 0;
while (str[i] != '\0') {
putchar(str[i]);
i++;
}
putchar('\n');
return 0;
}
Explanation:
- A string
"Hello, World!"is defined. - The program iterates through the string using a while loop.
- Each character is printed individually using
putchar(). - A newline character is printed after the loop to complete the output.
Program Output:
Hello, World!
Example 3: Handling Special Characters Using putchar()
This example shows how putchar() can be used to output special characters such as newline and tab, along with regular characters.
Program
#include <stdio.h>
int main() {
putchar('H');
putchar('e');
putchar('l');
putchar('l');
putchar('o');
putchar('\n'); // Newline
putchar('\t'); // Tab
putchar('W');
putchar('o');
putchar('r');
putchar('l');
putchar('d');
putchar('\n');
return 0;
}
Explanation:
- The program prints each character individually using
putchar(). - Special characters like newline (
\n) and tab (\t) are used to format the output. - This example demonstrates that
putchar()correctly handles both regular and special characters.
Program Output:
Hello
World
