C Program to Find ASCII Value of a Character

1. Introduction

The American Standard Code for Information Interchange, or ASCII, is a character encoding standard that represents text in electronic devices such as computers and mobile phones. Each character, whether it's a letter, a digit, or a symbol, has a unique ASCII value. In this guide, we will explore a C program that fetches the ASCII value of a given character.

2. Program Overview

Our program will:

1. Ask the user to input a character.

2. Calculate the ASCII value of the input character.

3. Display the ASCII value to the user.

3. Code Program

#include <stdio.h>  // Incorporate the Standard I/O library

int main() {  // Start the program

    char ch;  // Declare a character variable

    // Request the user to provide a character
    printf("Enter a character: ");
    scanf("%c", &ch);  // Read the input character

    // Print the ASCII value
    printf("ASCII value of %c = %d\n", ch, ch);  // Display the ASCII value

    return 0;  // Conclude the program successfully
}

Output:

Enter a character: A
ASCII value of A = 65

4. Step By Step Explanation

1. #include <stdio.h>: We include the standard input and output library, facilitating our I/O operations.

2. int main(): This is the primary entry point of our C program.

3. Variable Declaration:

  • ch: It's a variable that will store the character input by the user.

4. User Input:

  • We prompt the user to input a character.
  • We utilize scanf with the %c format specifier to read the character and store it in the variable ch.

5. ASCII Value Retrieval:

  • In C, characters are internally represented by their ASCII values. So, to get the ASCII value, we can simply use the variable as an integer.
  • We then use printf to show the character and its corresponding ASCII value. Notice how the variable ch is used twice: first with %c to print the character and then with %d to print its ASCII value.

6. Output: The program subsequently displays the ASCII value for the given character.

By using this approach, we can swiftly determine the ASCII values of characters, which is fundamental for various computing tasks, especially those involving character manipulation and evaluation.

Comments