As part of Frequently Asked Programs in Java , I will discuss a new program in this post.
Accept a letter from user and print position of input letter in alphabet.
Example: A has 1st position in alphabet. B has 2nd position in alphabet.
- We will use ASCII concept here.
- Every letters in alphabet (both upper and lower case) has unique ASCII value.
- We can retrieve ASCII value of any char by casting in to int.
- Convert input letter in to uniform case either in upper case or lower. I will convert in to lower case.
- Convert char in to ASCII value using toLowerCase() method of Character wrapper class.
- ASCII value for lower case alphabet stars from 97.
- To get the position, subtract 96 from ASCII value of input character. In case if you convert input letter in to upper case, you need to subtract 64 as ASCII value for upper case alphabet stars from 65.
If you have any other logic of solving above problem, please comment. It is always better to know more logic.
If you like my posts, please like, comment, share and subscribe.