#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter a character: ";
cin >> ch;
cout << "ASCII value of '" << ch << "' is: " << (int)ch << endl;
return 0;
}Output
Enter a character: A ASCII value of 'A' is: 65
ASCII Value of a Character in C++
This program teaches how characters are stored and handled inside the computer. Every character you type—like A, a, 5, #, !, or space—has its own unique number called an ASCII value. This program takes a single character from the user and prints its ASCII number.
1. Characters and ASCII Values
Computers do not store characters directly.
Instead, every character is converted into a number.
These numbers are part of a standard system called ## ASCII (American Standard Code for Information Interchange).
Examples:
- 'A' → 65
- 'a' → 97
- '0' → 48
- '@' → 64
So when you type a character, the computer stores it as a number internally.
2. Header File
#include <iostream>
This header gives access to cout (for printing messages) and cin (for taking user input).
3. Declaring the char Variable
The program declares:
char ch;
char is a data type used to store a single character such as 'A', 'b', '3', or '$'.
It always stores exactly ## 1 byte of memory.
4. Taking Character Input
The program asks the user:
cout << "Enter a character: ";
cin >> ch;
Here's what happens:
- cout shows the message.
- cin waits for the user to type a character.
- The typed character is stored in the variable ch.
If you type A, then ch holds 'A'.
If you type $, then ch holds '$'.
5. Converting char to int (Type Casting)
To print the ASCII number, the program uses:
(int)ch
This is called ## type casting.
It means: "Treat ch as an integer instead of a character."
Normally:
- cout << ch; prints the character itself (like A)
- cout << (int)ch; prints the ASCII value (like 65)
Type casting changes how the value is shown, not how it is stored.
6. Displaying the ASCII Value
The program prints:
cout << "ASCII value of '" << ch << "' is: " << (int)ch << endl;
If ch = 'A', the output will be:
ASCII value of 'A' is: 65
If ch = 'b', output will be:
ASCII value of 'b' is: 98
7. return 0;
This ends the program and tells the computer everything worked fine.
Summary
- Characters in C++ are stored as ASCII numbers.
- char stores one character.
- Type casting (int) converts a character to its ASCII number.
- This program helps beginners understand how character data works internally.
Once you understand ASCII values, you'll be ready for more advanced topics like character functions, strings, and encryption basics.