#include<stdio.h>
#include<conio.h>
int main()
{
char c;
printf("\n Enter a char:");
c=getchar();
printf("a=%c",c);
getch();
}
/*In the above program a character variable c is declared.The getchar() reads a character through the
keyboard.The same is displayed by the printf() statement.
Syntax of the getchar() is as follows:-
Variable name=getchar();*/
The above program is a simple example of how to accept a character from the user using the getchar()
function.
The program starts with the declaration of a character variable c
. Then, a message “Enter a char:” is displayed on the screen using the printf()
function.
The getchar()
function reads a single character from the keyboard and stores it in the variable c
. The same character is then displayed on the screen using the printf()
function along with the message “a=”.
Finally, the getch()
function is used to hold the output screen until a key is pressed.
The syntax of the getchar()
function is: variable_name = getchar();
It is important to note that the getchar()
function reads a single character at a time and ignores any extra characters entered by the user. Also, the newline character ‘\n’ entered after pressing the Enter key is also considered as a character by getchar()
.
The printf statement in the program should include a newline character \n
for better formatting, like this:
printf("a=%c\n",c);
This will ensure that the output is printed on a new line.
Thanks