We will demonstrate C programs for displaying the ASCII value(s) of a character or all characters within a string in this article.
How to Find the ASCII Value of a Character in C Programming?
There are two methods to find a character’s ASCII value in C programming:
Method 1: Using scanf() Function
In C Programming, you can easily find the ASCII value of a character using scanf() function, and the steps are given below:
Step 1: First you have to declare a character with the char data type.
Step 2: Then use the scanf() function to prompt us to enter a character with %c specifier.
Step 3: Then use the printf() function to output the ASCII value of the character with %d specifier.
Look at the following example and understand how we can print a character’s ASCII value in C.
The above program accepts a character from the user and then it finds and prints the ASCII value of that character. Because num is of the int type, it sets the ASCII value of a character which is stored in the c variable to num. As a result, the ASCII value of c is set to num.
Method 2: Using getchar() Function:
In C Programming, you can easily find the ASCII value of a character using getchar() function, and the steps are given below:
Step 1: First you have to declare a character with the char data type.
Step 2: Then use the getchar() function to determine the character’s ASCII value.
Step 3: Then use the printf() function to print the ASCII value of the character with %d specifier.
Take a look at the following example and understand how we can print a character’s ASCII value in C.
The above program accepts a character from the user and then it finds and prints the ASCII value of that character using getchar() function.
How to Determine the ASCII Value of All Characters in a String
If you have a string and are interested in finding the ASCII value of all characters, you can follow the below-given program.
The above program asks the user to enter the strings of characters and then uses the while loop to find and print the ASCII value of all the characters in the string.
Conclusion
In C programming, the ASCII value of a character can be found using the scanf() or getchar() functions. The ASCII value of each character is represented by a unique 7-bit code, and it can be represented in hexadecimal, octal, or decimal formats. The ASCII value of all characters in a string can also be found using a while loop. By following the steps outlined in this article and using the provided examples, programmers can easily find the ASCII value of characters in their C programs.