Pages

Friday, September 25, 2009

Character Variables

While integer,float,long,double etc. are used for numerical values, sometimes there is a need to store an alphabetical value also. For this purpose we can use the char datatype. It can not only store alphbetical values but also symbols and digits. For instance - 'R','s','%','&','3' are all examples of valid characters. Pay special attention that a char can also store digits but they can not be used for arithmetic calculation.

Rules for creating character variables
  1. A character variable can not contain more than one character at a time. For example - 'E' is a valid character while 'Error' is not since it contains more than one character.
  2. Each character constant should be written inside a pair of single quoatations (' ')

Example

void main()
{
char alpha,beta,gamma;
alpha='G';
beta='4';
gamma='=';
printf("%c",alpha);
printf("%c",beta);
printf("%c",gamma);
}

Compile the above program using Ctrl+F9 and check the result using Alt+F5, you will see the following output
G4=

If you want to print all these character on seperate line put a '\n' inside all the printf() statements like, printf("\n%c",alpha);

Character and ASCII values
Observe the following code carefully.

void main()
{
char a='A';
printf("The character is %c",a);
printf("\nAscii value is %d",a);
}

The above program will print the following output
The character is A
Ascii value is 65

Why 'A' is printed is quite evident, because this is the value of the variable. If this same variable is printed using %d specifier it will print the ASCII(American Standard Code For Information Interchange) code of 'A' which is 65. This also proves that C treats all the characters as integers internally.

0 comments:

Post a Comment