Table of contents
1.
Introduction
2.
Benefits of C functions
3.
Aspects of Function
4.
Syntax
5.
Parameters
6.
Return Value
7.
Various Characteristics of Invoking Functions
8.
Examples
8.1.
Example 1: Printing a single character
8.2.
Example 2: Printing ASCII values
8.3.
Example 3: Printing a string using putchar()
9.
Frequently Asked Questions
9.1.
Can putchar() be used to print multiple characters at once?
9.2.
Is it necessary to include the stdio.h header file to use putchar()?
9.3.
Can putchar() be used to print formatted output?
10.
Conclusion
Last Updated: Nov 30, 2024
Easy

Putchar() Function in C

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Putchar is a function in C programming that outputs a single character to a display. This simple function is part of the standard input/output library and plays a key role in displaying characters during programming tasks. 

Putchar() Function in C

In this article, we will discuss the putchar() function in detail, like its syntax, parameters, return value, and different examples to understand its implementation.

Benefits of C functions

C functions help us a lot by making our code more modular, reusable, and easier to understand. Let’s look at the few benefits you can get: 

1. Improve code readability: Functions allow you to divide your code into logical, manageable pieces. Each function can focus on a specific task, making your code easier to read & comprehend.

 

2. Enhance code reusability: Once you define a function, you can call it multiple times from different parts of your program. This reduces code duplication & makes your program more efficient.
 

3. Facilitate debugging: When you isolate specific functionality into functions, it becomes easier to test & debug your code. You can test each function independently, making it simpler to identify & fix issues.
 

4. Promote collaboration: Functions enable multiple programmers to work on different parts of a program simultaneously. Each programmer can write and test their functions separately, streamlining the development process.
 

5. Increase program modularity: Functions provide a way to break down complex problems into smaller, more manageable sub-problems. This modular approach makes your program more organized & maintainable.

Aspects of Function

1. Function declaration: Before you can use a function, you need to declare it. The declaration specifies the function's name, return type, and the types of its parameters (if any). It tells the compiler about the function's existence and its interface.
 

2. Function definition: The function definition is where you actually implement the function. It consists of the function header (which matches the declaration) and the function body (enclosed in curly braces). The function body contains the code that executes when the function is called.
 

3. Function parameters: Functions can accept input values, known as parameters or arguments. Parameters allow you to pass data from the calling code to the function. The function declaration and definition specify the types and names of the parameters.
 

4. Return value: Functions can also return a value back to the calling code. The return type in the function declaration and definition specifies the type of value the function will return. You use the `return` statement within the function body to send a value back to the caller.
 

5. Function call: To execute a function, you need to call it from your code. Function calls include the function name followed by parentheses. If the function expects arguments, you provide them within the parentheses, separated by commas.

Syntax

The syntax of putchar() is:

```c
int putchar(int character);
```

 

In this syntax: 

- `int`: The putchar() function returns an integer value. It returns the character written on success, or EOF (End-of-File) on error.
 

- `putchar`: The name of the function.
 

- `int character`: The character to be written to the standard output. It is passed as an integer value representing the character's ASCII code.
 

To use the putchar() function, you need to include the `stdio.h` header file in your C program. This header file contains the declaration of the putchar() function

For example: 

#include <stdio.h>

int main() {
    int ch = 'A';
    putchar(ch);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


In this example, the character 'A' is assigned to the variable `ch`. The putchar() function is then called with `ch` as the argument, which outputs the character 'A' to the standard output.

Parameters

The putchar() function takes a single parameter, which is the character to be written to the standard output. The parameter is of type int, but it is interpreted as an unsigned char.

Few important points to keep in mind regarding the parameter are:
 

1. ASCII value: The character passed to putchar() is represented by its ASCII value. For example, the ASCII value of 'A' is 65. So, you can pass either the character literal 'A' or the integer value 65 to putchar().
 

2. Integer promotion: When a character is passed as an argument to putchar(), it undergoes integer promotion. This means that the character is automatically converted to an int value. Therefore, you can pass a character literal, a variable of type char, or an integer value representing the character's ASCII code.
 

3. Casting: If you have a variable of a different type, such as an int or a float, you can cast it to a char before passing it to putchar(). This ensures that only the lowest byte of the value is used as the character.
 

For example: 
 

  • putchar('A');     // Output: A
     
  • putchar(65);      // Output: A
     
  • char ch = 'B';
     
  • putchar(ch);      // Output: B
     
  • int num = 67;
     
  • putchar((char)num);  // Output: C


In the above examples, we pass a character literal, an integer value, a char variable, and a casted int value to putchar(). In each case, the corresponding character is output to the standard output.

Return Value

The putchar() function returns an integer value indicating the success or failure of the character output operation. Let’s see what the return value represents:

1. Success: If the character is successfully written to the standard output, putchar() returns the same character that was passed as the argument. This means that if putchar() successfully outputs the character, it returns the ASCII value of that character.
 

2. Failure: If an error occurs during the output operation, putchar() returns the constant value EOF (End-of-File). EOF is typically defined as -1 in the stdio.h header file. It indicates that an error occurred and the character could not be written to the standard output.

It's important to note that the return value of putchar() is often ignored in simple programs since the function is primarily used for character output. However, checking the return value can be useful in more complex scenarios or when error handling is required.

Let’s look at an example that shows the checking the return value of putchar():

#include <stdio.h>
int main() {
    int result = putchar('A');
    if (result == EOF) {
        printf("Error occurred while writing the character.\n");
    } else {
        printf("Character written successfully.\n");
    }
    return 0;
}
You can also try this code with Online C Compiler
Run Code


In this example, we store the return value of putchar() in the `result` variable. We then check if the return value is equal to EOF. If it is, we print an error message indicating that an error occurred during the character output. Otherwise, we print a success message.

Various Characteristics of Invoking Functions

When invoking functions in C, there are many characteristics which we need to remember, like:

1. Function call: To invoke a function, you simply use its name followed by parentheses (). If the function requires arguments, you pass them within the parentheses, separated by commas. The function call transfers control to the function, and the program execution starts from the first statement inside the function.
 

2. Argument passing: When you pass arguments to a function, they are passed by value. This means that a copy of the argument's value is passed to the function, and any modifications made to the parameter inside the function do not affect the original argument in the calling code.
 

3. Return value: If a function has a return value, it is specified in the function declaration and definition using the appropriate data type. The return statement inside the function sends a value back to the calling code. The calling code can assign the returned value to a variable or use it directly in an expression.
 

4. Function prototype: In C, a function must be declared before being called. The function prototype provides information about the function's name, return type, and parameter types. It helps the compiler check for proper function usage and catch any discrepancies between the function call and its declaration.

 

5. Function scope: Variables declared inside a function have local scope, meaning they are accessible only within that function. They are created when the function is called and destroyed when the function ends. Variables declared outside any function have global scope and can be accessed from anywhere in the program.
 

6. Recursive function calls: C allows functions to call themselves recursively. Recursive function calls are useful for solving problems that can be broken down into smaller subproblems. However, it's important to define a base case to ensure that the recursion terminates at some point.

Examples

Example 1: Printing a single character

#include <stdio.h>


int main() {
    putchar('H');
    putchar('e');
    putchar('l');
    putchar('l');
    putchar('o');
    putchar('\n');
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

Hello

 

In this example, we use multiple putchar() function calls to print individual characters. Each character is passed as a character literal to putchar(). The newline character '\n' is used to move the cursor to the next line after printing "Hello".

Example 2: Printing ASCII values

#include <stdio.h>

int main() {
    for (int i = 65; i <= 90; i++) {
        putchar(i);
        putchar(' ');
    }
    putchar('\n');
    return 0;
}
You can also try this code with Online C Compiler
Run Code


Output:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z


In this example, we use a for loop to iterate over the ASCII values from 65 to 90, which represent the uppercase letters from 'A' to 'Z'. We pass each ASCII value to putchar() to print the corresponding character, followed by a space character ' ' to separate the letters.

Example 3: Printing a string using putchar()

#include <stdio.h>
#include <string.h>


int main() {
    char str[] = "Hello, World!";
    int len = strlen(str);
    for (int i = 0; i < len; i++) {
        putchar(str[i]);
    }
    putchar('\n');
    return 0;
}
You can also try this code with Online C Compiler
Run Code


Output:

Hello, World!


In this example, we have a string "Hello, World!" stored in the character array str. We use the strlen() function to get the length of the string. Then, we use a for loop to iterate over each character of the string and pass it to putchar() to print it. Finally, we print a newline character to move to the next line.

Frequently Asked Questions

Can putchar() be used to print multiple characters at once?

No, putchar() is designed to print a single character at a time. To print multiple characters, you need to call putchar() multiple times or use other functions like printf().

Is it necessary to include the stdio.h header file to use putchar()?

Yes, the stdio.h header file contains the declaration of the putchar() function. Without including this header file, the compiler will raise an error when using putchar().

Can putchar() be used to print formatted output?

No, putchar() is a simple function that only outputs a single character. For formatted output, you should use functions like printf() that provide formatting capabilities.

Conclusion

In this article, we discussed the putchar() function in C, which allows us to output a single character to the console. We explained the syntax, parameters, return value, and various examples. 

You can also check out our other blogs on Code360.

Live masterclass