Find the ASCII value of a character

Problem Statement: Given a character, Find the ASCII value of the character.

Examples:

Example 1:
Input: c = ‘A’
Output: 65
Explanation: ASCII value of A is 65

Example 2:
Input: c = ‘e’
Output: 101
Explanation: ASCII value of e is 101

Solution

Disclaimer: Don’t jump directly to the solution, try it out yourself first.

Approach

  • Basically, we store the character value in an integer which gives us the ASCII value of the character.
  • When we put character value inside an integer the typecasting occurs which converts character value into integer which is ASCII value. 
  • And then we print the ASCII value.

Code:

C++ Code

#include <bits/stdc++.h>

using namespace std;

class ASCII {

  public:

    void value() {

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

  ASCII p1;
  p1.value();

  return 0;
}

Output:

The ASCII value of A is 65

Time Complexity: O(1)

Space Complexity: O(1)

Java Code

class Solution {

  public static void value() {

    char c = 'e';
    int ascii = c;
    System.out.println("The ASCII value of " + c + " is: " + ascii);
  }
  public static void main(String args[]) {

    value();
  }
}

Output:

The ASCII value of e is: 101

Time Complexity: O(1)

Space Complexity: O(1)

Special thanks to Rushikesh Adhav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article