Find ASCII Value of a Character in C++

What is ASCII value?

  • ASCII stands for American Standard Code for Information Interchange.
  • A character or special character holds ASCII value rather than the character itself.
  • The ASCI value is an integer value between 0 and 127
  • The ASCII character set consists of English letters from A-Z, a-z, numbers 0-9, and a few special characters like an exclamation mark (!), dollar sign ($), plus (+), an asterisk (*), etc.

How to find ASCII characters in C++

In C++ programming, the value contained in a character variable is the ASCII value, not the value itself.

For example, consider a char type variable “chr”:

chr = ‘A’

the chr contains ASCII value 65 which is the ASCII value of character A.

An example of finding ASCII value in C++

In the first program, we will find the ASCII value of a few characters. These include:

  • A
  • a
  • 0
  • 9
  • Z
  • z
  • ;
  • *

See the code and output:

#include <iostream>

using namespace std;

int main() {

 char c;

 cout << "ASCII Value of A = " << int('A') <<"\n";

 cout << "ASCII Value of a = " << int('a') <<"\n";

 cout << "ASCII Value of 0 = " << int('0') <<"\n";

 cout << "ASCII Value of 9 = " << int('9') <<"\n";

 cout << "ASCII Value of Z = " << int('Z') <<"\n";

 cout << "ASCII Value of z = " << int('z') <<"\n";

 cout << "ASCII Value of ; = " << int(';') <<"\n";

 cout << "ASCII Value of * = " << int('*') <<"\n";

 return 0;

}

Output:

CPP-ASCII

In the above program, the int() is used to convert a character to its ASCII value.

Getting 0-255 ASCII values character example

In this program, we will find all the characters for the corresponding ASCII value. For this, a for loop is used and it will iterate from 0 to 255 value.

In each iteration, the corresponding ASCII value to its character is displayed. Have a look:

#include <iostream>

using namespace std;

int main() {

 char chr;

for(int asc=0;asc<=255;asc++)  // for loop from 0-255

 {

    //For loop to iterate till 255 and displaying corresponding character

     chr = asc;

     cout << asc << " = " << chr <<endl;

 }




 return 0;

}

Output:

CPP-ASCII-all

 

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!