putchar() in C - Source Code Example

In this source code example, we will see how to use the putchar() function in C programming with an example.

putchar() Function Overview

The putchar() function in C is used to write a single character to the standard output, typically the console or terminal screen.

Source Code Example

#include <stdio.h>

int main() {
    char ch = 'A';

    // Displaying a character using putchar
    putchar(ch);
    putchar('\n');

    // Using putchar in a loop to print characters
    for (int i = 0; i < 5; i++) {
        putchar('B');
    }
    putchar('\n');

    printf("Enter any character to display: ");
    ch = getchar();  // Reading a character using getchar
    putchar(ch);     // Displaying the character using putchar

    return 0;
}

Output

A
BBBBB
Enter any character to display: C
C

Explanation

1. We begin by displaying a character 'A' using putchar.

2. We then use a for-loop to display the character 'B' five times in a row.

3. We prompt the user to enter any character.

4. We read the user input using getchar().

5. The entered character is then displayed using putchar.


Comments