C Program to Print the ASCII Value of a Character - Input & Literal Examples

Print ASCII Value After User Input

#include <stdio.h>
int main() {
    char ch;
    printf("Enter a character: ");
    scanf(" %c", &ch);
    printf("ASCII value of %c = %d\n", ch, ch);
    return 0;
}
Enter a character: A
ASCII value of A = 65
        

This program reads a character and prints both the character and its ASCII code. The space before %c in the scanf() format string skips any leftover whitespace in the input buffer.

Print ASCII Value Using a Literal

#include <stdio.h>
int main() {
    char ch = 'Z';
    printf("Character: %c, ASCII value = %d\n", ch, ch);
    return 0;
}
Character: Z, ASCII value = 90
        

Assigning a character literal to a char variable implicitly stores its ASCII code. Printing the variable with %d reveals the numeric value, while %c displays the character itself.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗