Read a number from the keyboard, and show its ASCII Equivalent symbol | Number to ASCII program in C
Program Introduction:
Write a C Program to Convert a Number to ASCII Symbol. The Program should take input a number from the user and then display the ASCII equivalent of it.
Here are couple of expected inputs and outputs.
Example 1:
Input:
1 |
65 |
Output:
The ASCII equivalent of 65 is Upper case ‘A’.
1 |
'A' |
Example 2:
Input:
1 |
97 |
Output:
1 |
'a' |
Example 3:
Input:
1 |
48 |
Output:
1 |
Example 4:
Input:
1 |
1200 |
Output:
1 |
Invalid Input. Please enter a number between 0 to 255 |
Number to ASCII Conversion Program logic:
We are going to take Numbers from 0 to 255 only. If user enters any other number, Then display the error message.
But only 127 ASCII characters are printable characters. To be exact the printable ASCII Characters from number 32 which is space to number 126 which is ESC. So our output might give undefined values after 127 Number.
The basic idea is to pass the integer value to printf function and use the character format specifier ( %c). So the printf function will cast the integer to ASCII character. and prints the ASCII Symbol output to the console.
📢 ASCII symbols for the numbers between 128 to 255 are non-printable, So we might get undefined output for numbers after 127.
Program: Number to ASCII Conversion:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include<stdio.h> int main() { int n; // Take input from the user printf("Enter any Number (0-255) : "); scanf("%d",&n); // Allow only numbers between 0-255 if((0 <= n) && (n <= 255) ) { // Take advantage of integer to character casting to convert the // Integer to ASCII symbol. printf("ASCII symbol of %d is %c \n", n, n); } else { // Display the Error message and usage info. printf("Invalid Input. Please enter a number between 0 to 255 \n"); } return 0; } |
Number to ASCII Program Output:
We are using the GCC compiler in Linux OS to compiler the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
$ gcc number-to-ascii.c venkey@venkey$ ./a.out Enter any Number (0-255) : 48 ASCII symbol of 48 is 0 venkey@venkey$ ./a.out Enter any Number (0-255) : 65 ASCII symbol of 65 is A venkey@venkey$ ./a.out Enter any Number (0-255) : 97 ASCII symbol of 97 is a venkey@venkey$ ./a.out Enter any Number (0-255) : 400 Invalid Input. Please enter a number between 0 to 255 venkey@venkey$ ./a.out Enter any Number (0-255) : 110 ASCII symbol of 110 is n venkey@venkey$ ./a.out Enter any Number (0-255) : -1 Invalid Input. Please enter a number between 0 to 255 venkey@venkey$ |
1 Response
[…] Now, To Toggle to the case of all characters, We will go through the all characters of the string using a For Loop, and based on the case of the string we either Add or Subtract the 32 from the character ASCII Value. […]