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()

</>
Copy
int putchar(int character);

Parameters

ParameterDescription
characterThe 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

</>
Copy
#include <stdio.h>

int main() {
    putchar('A');
    putchar('\n');
    return 0;
}

Explanation:

  1. The program calls putchar() to write the character 'A' to stdout.
  2. A newline character (\n) is then printed to move the cursor to the next line.
  3. 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

</>
Copy
#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:

  1. A string "Hello, World!" is defined.
  2. The program iterates through the string using a while loop.
  3. Each character is printed individually using putchar().
  4. 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

</>
Copy
#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:

  1. The program prints each character individually using putchar().
  2. Special characters like newline (\n) and tab (\t) are used to format the output.
  3. This example demonstrates that putchar() correctly handles both regular and special characters.

Program Output:

Hello
	World