putchar function in C Programming

putchar function

putchar function displays a single character on the screen.

prototype: putchar(int c);

The following program illustrates the use of putchar function.

The `putchar()` function in C is used to write a single character to the standard output (usually the console). It is part of the standard input-output library `stdio.h`.

Syntax:

int putchar(int character);

Parameters:

  • - `character`: An integer representing the character to be written to the standard output. It is typically an ASCII value, but it can accept any integer value.

Return Value:

  • Returns the character written if successful.
  • Returns `EOF` (defined in `stdio.h`) if an error occurs.

Example Usage:

#include <stdio.h>

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

    putchar(ch); // Outputs the character 'A'
    putchar('\n'); // Outputs a newline character

    return 0;
}

Important Notes:

  • `putchar()` writes a single character to the standard output.
  • It does not add a newline character by default. You need to explicitly use `putchar('\n')` or `puts()` to add a newline.
  • It is a very basic function and is typically used for simple character output. For formatted output or more complex operations, `printf()` is more commonly used.
  • Since `putchar()` is a simple function, it's often used in educational contexts or in cases where simplicity and efficiency are more important than advanced formatting options.

Alternatives:

  • `printf()`: The more versatile and commonly used function for formatted output in C. It can handle various data types and provides extensive formatting options.
  • `fputc()`: Similar to `putchar()`, but allows writing characters to a specified file stream instead of the standard output.

Overall, `putchar()` is a simple and straightforward function for writing individual characters to the standard output. It's useful for basic console output operations and can be handy in situations where simplicity is preferred over more advanced formatting features.

Ready to get started?

Ready to embark on your journey into the world of C programming? Our comprehensive course provides the perfect starting point for learners of all levels. With engaging lessons, hands-on exercises, and expert guidance, you'll gain the skills and confidence needed to excel in this fundamental programming language. Let's dive in and unlock the endless possibilities of C programming together!