ASCII value of character

The term ASCII (American Standard Code for Information Interchange) refers to a defined character encoding. It assigns certain codes to characters such as letters, digits and punctuation marks. The ASCII code is used to specify how the characters are displayed by electronic devices – such as PCs or smartphones. This is an important part of many programming operations

Code Example

#include <iostream>
using namespace std;

int main () {
    char c;

    cout << "Please enter character: ";
    cin >> c;

    cout << "ASCII value of the character " << c << " is: " << int(c);
    
    return 0;
}

Output

Please enter character: u
ASCII value of the character u is: 117

Code Explanation

1. Variable Declaration and User Input:

char c;

cout << "Please enter character: ";
cin >> c;
  • Here, a variable c of type char is declared to store the character entered by the user.
  • The program prompts the user to enter a character. This is accomplished using cout, which outputs the prompt to the standard output. Following the prompt, cin is used to read the single character entered by the user and store it in the variable c.

2. Output the ASCII Value:

cout << "ASCII value of the character " << c << " is: " << int(c);
  • This line is responsible for outputting the ASCII value of the character stored in c. It constructs a message that includes the character and its ASCII value.
  • The expression int(c) is a type cast that converts the char value in c to its corresponding integer value, which is the ASCII code of the character.

3. Return Statement:

return 0;
  • The return 0; statement is used to indicate that the program has finished executing successfully. It returns an exit status of 0 to the operating system, signifying a successful completion.