ASCII is the American Standard Code for information interchange is a character encoding scheme used for electronics communication. Each character or a special character is represented by some ASCII code, and each ascii code occupies 7 bits in memory.
A character variable in C does not contain a actual character value, rather it stores the ascii value of the character variable . The ascii value represents the character variable in numbers, and each character variable is assigned with some number range from 0 to 127.
Consider the below example
char ch = 'A';
The ascii value of 'A' is 65. In the above example, the ascii value of 65 will be stored in the character variable ch rather than 'A'.
Another example to display the ascii value of the character variable.
#include <stdio.h> int main() { char ch; // variable declaration printf("Enter a character"); scanf("%c",&ch); // user input printf("\n The ascii value of the ch variable is : %d", ch); return 0; }
In the above code, if we print the value of the 'ch' variable by using %c format specifier, then it will display 'A' because we have given the character input as 'A', and if we use the %d format specifier then its ascii value will be displayed, i.e., 65.
The below example will display the ascii value of all the characters. As the ascii value of all the characters starts from 0 and ends at 255, iterate the for loop from 0 to 255.
#include <stdio.h> int main() { int k; // variable declaration for(int k=0;k<=255;k++) // for loop from 0-255 { printf("\nThe ascii value of %c is %d", k,k); } return 0; }
The below example will sum the ascii value of a string by executing the while
loop which adds the ascii value of all the characters of a string and stores it in a 'sum' variable.
#include <stdio.h> int main() { int sum=0; // variable initialization char name[20]; // variable initialization int i=0; // variable initialization printf("Enter a name: "); scanf("%s", name); while(name[i]!='\0') // while loop { printf("\nThe ascii value of the character %c is %d", name[i],name[i]); sum=sum+name[i]; i++; } printf("\nSum of the ascii value of a string is : %d", sum); return 0; }
In the above code, we are taking user input as a string. After taking user input, we execute the while loop which adds the ascii value of all the characters of a string and stores it in a 'sum' variable.
Output
Below table is the ASCII chart.
|
|