C Program to Print ASCII Value of a Character
In C programming, a character variable holds its ASCII value (an integer between 0 and 127) rather than the character itself. This program demonstrates how to reveal that underlying integer value.
Concept Overview
ASCII (American Standard Code for Information Interchange) is a character encoding standard. When you use the %d format specifier with a char variable in printf(), C prints the numeric ASCII code associated with that character.
Program
C
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
// %c displays the actual character
// %d displays the integer ASCII value
printf("ASCII Value of the character is: %d\n", ch);
return 0;
}
Sample Output
Enter a character: A ASCII Value of the character is: 65
Explanation
- The variable `ch` is declared as a `char` type to store the user's input.
- The `scanf("%c", &ch)` function captures a single character from the keyboard.
- Inside the `printf` function, we use the `%d` format specifier. This tells C to treat the character as an integer.
- Every character has a unique code; for example, 'A' is 65, 'a' is 97, and '0' is 48.
Note: Note: Even space and special symbols like '@' or '#' have specific ASCII values that this program can display.
Codecrown