C++ Program To Print ASCII Value of a Character

Given a character, we need to print its ASCII value in C++. 

Examples:

Input:
Output: 97

Input: D
Output: 68

Using Type Conversion

Here int() is used to convert a character to its ASCII value. Below is the C++ program to implement the above approach: 

C++
// C++ program to print
// ASCII Value of Character
#include <iostream>
using namespace std;

// Driver code
int main()
{
    char c = 'A';
    cout << "The ASCII value of " << 
             c << " is " << int(c);
    return 0;
}

Output
The ASCII value of A is 65

Time complexity: O(1) since performing constant operations
Auxiliary Space: O(1)

ASCII Value For Each Character in a String

Below is the C++ program to print the ASCII value of each character in a string:

C++
// C++ program to print ASCII
// value of each character in a string
#include<iostream>
using namespace std;

// Driver code
int main()
{
    char ch, str[200] = "w3wiki";
    int i = 0, val;
    
    cout << "\nCharacter\tASCII Value\n";
    while(str[i])
    {
        ch = str[i];
        val = ch;
        cout << ch << "\t\t\t" << val << endl;
        i++;
    }
    cout << endl;
    return 0;
}

Output
Character    ASCII Value
G            71
e            101
e            101
k            107
s            115
f            102
o            111
r            114
G            71
e            101
e            101
k            107
s            115

ASCII Value of All Characters

Below is the C++ program to print the ASCII value of all the characters:

C++
// C++ program to print AS
#include <iostream>
using namespace std;

// Driver code
int main()
{
    char c;
    cout << "Character\tASCII Value\n";
    for(c = 'A'; c <= 'Z'; c++)
    {
        cout << c << "\t\t\t" << (int)c << endl;
    }
    return 0;
}

Output
Character    ASCII Value
A            65
B            66
C            67
D            68
E            69
F            70
G            71
H            72
I            73
J            74
K            75
L            76
M            77
N            78
O            79
P            80
Q            81
R            82
S            83
T            84
U            85
V            86
W            87
X            88
Y            89
Z        ...

Please refer complete article on Program to print ASCII Value of a character for more details!



Contact Us