C Program to Find ASCII Value of a Character
A character variable holds an ASCII value (an integer number between 0 and 127) rather than that character itself in C programming. That value is known as the ASCII value.
For example, the ASCII value of ‘A’ is 65.
This means that, if you assign ‘A’ to a character variable, 65 is stored in that variable rather than ‘A’ itself.
Program to Print ASCII Value
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
// Reads character input from the user
scanf("%c", &c);
// %d displays the integer value of a character
// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}
Output
Enter a character: G ASCII value of G = 71
In this program, the user is asked to enter a character stored in variable c. The ASCII value of that character is stored in variable c rather than that variable itself.
When the %d format string is used, 71 (ASCII value of ‘G’) is displayed.
When the %c format string is used, ‘G’ is displayed.
C program that prompts the user to enter a character and then displays its ASCII value on the console
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("ASCII value of %c is %d", ch, ch);
return 0;
}
In this program, we declare a variable called ch
of type char
to store the character entered by the user.
We then use the printf()
function to display a message asking the user to enter a character. We use the %c
format specifier to indicate that we expect a character input.
Next, we use the scanf()
function to read a character value from the user and store it in the ch
variable. Note that we use the &
operator to pass the address of the ch
variable to scanf()
so that it can update the value stored in that memory location.
Finally, we use another printf()
function call to display the ASCII value of the character entered by the user. We use the %d
format specifier to print the decimal representation of the ASCII value of the ch
variable. We also include the value of ch
as an argument to the printf()
function using the %c
format specifier, to display the character itself as well.