ASCII assigns a unique numeric code to characters, allowing computers to represent and process text using numbers. In C, a character can be converted to its corresponding ASCII value using integer conversion.
- ASCII values range from 0 to 127 in the standard ASCII character set.
- A character's numeric value can be printed directly using the %d format specifier or explicit typecasting.
Illustration
Character: A
ASCII Value: 65
Approaches to Find the ASCII Value of a Character
There are two common approaches:
1. Using the %d Format Specifier
The %d format specifier prints the integer value of a character. When a char is passed where an integer is expected, it undergoes integer promotion to an integer value.
#include <stdio.h>
int main() {
char c = 'k';
// %d displays the integer value of
// a character
// %c displays the actual character
printf("The ASCII value of %c is %d", c, c);
return 0;
}
Output
The ASCII value of k is 107
Explanation: The %c specifier prints the character, while %d prints its corresponding integer value after integer promotion.
2. Using Explicit Typecasting
The character can be explicitly converted to an integer using (int) and then printed.
#include <stdio.h>
int main() {
char ch = 'A';
// Find the ASCII value of a character using typecasting
int asciiValue = (int)ch;
printf("ASCII value of %c is %d\n", ch, asciiValue);
return 0;
}
Output
ASCII value of A is 65
Explanation: The expression (int)ch explicitly converts the character ch to an integer, which gives its corresponding character code.