C Library - putchar() function



The C library putchar function is a part of the standard C library and is used to write a single character to the standard output, which is typically the console or terminal. It is a simple yet essential function for character output in C programming.

Syntax

Following is the C library syntax of the putchar() function −

putchar(int char);

Parameters

This function accepts only a single parameter −

  • char : The character to be written, which is passed as an int. This character is typically represented by its ASCII value.

Return Value

On success, putchar returns the character written as an unsigned char cast to an int. If an error occurs, it returns EOF (End Of File).

Example 1: Printing a String Character by Character

This example shows how to use putchar in a loop to print each character of a string individually until the null terminator is reached.

Below is the illustration of the C library putchar() function.

#include <stdio.h>

int main() {
    const char *str = "Hello, World!";
    while (*str) {
        putchar(*str++);
    }
    return 0;
}

Output

The above code produces following result−

Hello, World!

Example 2: Printing ASCII Values

This example uses putchar to print the characters corresponding to ASCII values 65 to 70, which are 'A' to 'F'. A space is also printed after each character for readability.

#include <stdio.h>

int main() {
    for (int i = 65; i <= 70; i++) {
        putchar(i);
		
		// Space for separation
        putchar(' ');  
    }
    return 0;
}

Output

After execution of above code, we get the following result

A B C D E F 
Advertisements