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.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...