Monday, January 26, 2009

Arithmetic Operators in C Language

The arithmetic operators are the usual `+', `-', `*', and `/' (truncating integer division if the operands are both int), and the remainder or mod operator `%':
x = a%b;
sets x to the remainder after a is divided by b (i.e., a mod b). The results are machine dependent unless a and b are both positive.
In arithmetic, char variables can usually be treated like int variables. Arithmetic on characters is quite legal, and often makes sense:
c = c + 'A' - 'a';
converts a single lower case ascii character stored in c to upper case, making use of the fact that corresponding ascii letters are a fixed distance apart. The rule governing this arithmetic is that all chars are converted to int before the arithmetic is done. Beware that conversion may involve sign-extension if the leftmost bit of a character is 1, the resulting integer might be negative. (This doesn't happen with genuine characters on any current machine.)
So to convert a file into lower case:
main( )
{
char c;
while( (c=getchar( )) != '\0' )
if( 'A'<=c && c<='Z' )
putchar(c+'a'-'A');
else
putchar(c);
}
Characters have different sizes on different machines. Further, this code won't work on an IBM machine, because the letters in the ebcdic alphabet are not contiguous.

No comments:

Post a Comment