Tuesday, April 5, 2011

Arithmetic operators in C

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 intbefore 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.

0 comments:

Post a Comment

Breaking News
Loading...
Quick Message
Press Esc to close
Copyright © 2013 Crack o Hack & tweak STORE All Right Reserved