Tuesday 20 November 2012

C Programming Operators:


C programming language provides several operators to perform different kind to operations. There are operators for assignment, arithmetic functions, logical functions and many more. These operators generally work on many types of variables or constants, though some are restricted to work on certain types. Most operators are binary, meaning they take two operands. A few are unary and only take one operand.
Operators can be classified based on the type of operations they perform.

C Arithmetic Operators

Arithmetic operators include the familiar addition (+), subtraction (-), multiplication (*) and division (/) operations. In addition there is the modulus operator (%) which gives the remainder left over from a division operation. Let us look at some examples:
Sample Code
  1.  #include <stdio.h>
  2.  
  3.  void main()
  4.  {
  5.          int a = 100;
  6.          int b = 3;
  7.          int c;
  8.  
  9.          c = a + b;
  10.          printf( "a + b = %dn", c );
  11.  
  12.          c = a - b;
  13.          printf( "a - b = %dn", c );
  14.  
  15.          /* multiplication performed before call to printf() */
  16.          printf( "a * b = %dn", a * b );
  17.  
  18.          c = a / b;
  19.          printf( "a / b = %dn", c );
  20.  
  21.          c = 100 % 3;
  22.          printf( "a % b = %dn", c );
  23.  }
Note – Though the usual definition of the main() function is int main(), few compilers allow the main() function to return void. The C standard allows for implementation defined versions of main() that do not return int. If your compiler does not allow that, change line 3 to int main() and put a return statement return 0; at the end just before line 23.
This program gives the following output:
a + b = 103
a - b = 97
a * b = 300
a / b = 33
a % b = 1

In this example you can see on line 16 that it is not always necessary to assign the result of an operation to a variable. The multiplication is performed first, then the result is passed to the printf() function. On line 21 we see an example of using an operator on constants, with the 100 and 3 replacing the variables a and b.
If the modulus operator on line 21 is new to you, it is the remainder left over when one integral number is divided by another. For example 45 % 6 is 3 since 6 * 7 is 42 and the remainder is 3. The modulus operator works only with integral types (char, short, int, etc.). If you try to use it with other types such as a float or double the compiler will give an error.
So far we have only used integers in our examples. When you use an operator on mixed types they will be implicitly converted into a common type before the operation is performed. The result of the operation will also be in the common type. The common type is derived using a few rules, but generally, a “smaller” operand is converted to the “larger” operand's type. If the result of the operation is assigned to another variable, the result is converted from the common type to the type of that variable. Let us look at some examples:

Sample Code
  1.  #include <stdio.h>
  2.  
  3.  void main()
  4.  {
  5.          int a = 65000;
  6.          char c = 120;
  7.          int iresult;
  8.          char cresult;
  9.  
  10.          iresult = a + c;
  11.          printf( "a + c = %dn", iresult );
  12.  
  13.          cresult = a + c;
  14.          printf( "a + c = %dn", cresult );
  15.  }
  16.  
The output is:
a + c = 65120
a + c = 96

On the system where this example was run, an int type is a signed 32 bit number, and a char type is a signed 8 bit number. When the a + c operation is performed, c is converted to an int and then added to a, resulting in an another int.
On line 10 this integer is assigned to iresult, which is also an int so no conversion is necessary.
On line 13 the result is assigned to a char, which means the int result must be converted into a char. The binary representation of 65120 is 1111111001100000. Truncating this to just the first 8 bits (since a char is 8 bits on this machine) gives 01100000 which is 96 in decimal.
Another example:
Sample Code
  1.  #include <stdio.h>
  2.  
  3.  void main()
  4.  {
  5.          int a = 4;
  6.          float b = 3.14159;
  7.          int iresult;
  8.          float fresult;
  9.  
  10.          fresult = a * b;
  11.          printf( "a * b = %fn", fresult );
  12.  
  13.          iresult = a * b;
  14.          printf( "a * b = %dn", iresult );
  15.  }
The output is:
a * b = 12.566360
a * b = 12

A similar process happens in this example. The integer a is converted to a float since a float is capable of holding integers but not vice-versa. The result of the multiplication is a float, which must be converted back to an int on line 13. This is done by truncating the fractional part of the float.
This conversion process happens for constants too.
Sample Code
  1.  #include <stdio.h>
  2.    
  3.    void main()
  4.    {
  5.            double d = 15 / 6;
  6.            printf( "15 / 6 is %fn", d );
  7.    
  8.            d = 15.0 / 6;
  9.            printf( "15 / 6 is %fn", d );
  10.   }

The output is:
15 / 6 is 2.000000
15 / 6 is 2.500000

On line 5 both the constants are integers, so an integer division is performed and then the result converted to a double. On line 8 the 15.0 is a double constant which forces the division to be done using double precision floating point numbers, and then the result assigned to d.

C Relational Operators

Relational operators compare operands and return 1 for true or 0 for false. The following relational operators are available:
Symbol Meaning
  <    Less than
  >    Greater than
  <=   Less than or equal to
  >=   Greater than or equal to
  ==   Equal to
  !=   Not equal to

Here is an example of how to use these operators. This program is a simple number guessing game:
Sample Code
  1. #include <stdio.h>
  2.  #include <stdlib.h>
  3.  #include <time.h>
  4.  
  5.  void main()
  6.  {
  7.          int mynum;
  8.          int guess = -1;
  9.          char buffer[64];
  10.  
  11.          srand( time(0) );
  12.          mynum = rand() % 100 + 1;
  13.  
  14.          printf( "I have picked a number between 1-100.n" );
  15.  
  16.          while( guess != mynum )
  17.          {
  18.                  printf("Enter your guess: ");
  19.                  if ( fgets( buffer, 64, stdin ) == NULL )
  20.                          break;
  21.                  guess = atoi( buffer );
  22.  
  23.                  if ( guess >= 101 || guess <= 0 )
  24.                  {
  25.                          printf("Your guess is out of bounds.n");
  26.                          continue;
  27.                  }
  28.  
  29.                  if ( mynum > guess )
  30.                          printf("Your guess is too low.n");
  31.                  else if ( mynum < guess )
  32.                          printf("Your guess is too high.n");
  33.          }
  34.  
  35.          if ( guess == mynum )
  36.                  printf( "You guessed correctly.n" );
  37.  }
The output from a typical run is shown here (user entered values in red):
I have picked a number between 1-100.
Enter your guess: 300
Your guess is out of bounds.
Enter your guess:
50
Your guess is too high.
Enter your guess:
25
Your guess is too low.
Enter your guess:
37
Your guess is too high.
Enter your guess:
31
Your guess is too high.
Enter your guess:
28
Your guess is too high.
Enter your guess:
26
You guessed correctly.

When the program is first run, the condition in the while loop on line 16 is satisfied because guess was initialized to -1 on line 8 and lines 11-12 initialize mynum with a random number between 1 and 100. Lines 18-21 tell the user to enter their guess and read the input from the user.
The if statement on line 23 uses the or operator || which will be covered later – it basically says if the user enters a number greater than or equal to 101 or less than or equal to 0 then tell the user the guess is invalid. The program will keep looping until the user guesses the right value or there is an error reading input from the user (the break statement on line 20 breaks out of the loop in that case).
You can compare values of different types. Just like with arithmetic operations, the operands are converted to a common type and then compared.
Sample Code
  1.  #include <stdio.h>
  2.  
  3.  void main()
  4.  {
  5.  double dnum = 5.1;
  6.  
  7.  if ( ( dnum > 5 ) == 1 )
  8.  printf( "%lf > 5n", dnum );
  9.  else
  10.  printf( "%lf <= 5n", dnum );
  11.  }



The output of this program is:
5.100000 > 5
The integer constant 5 on line 7 is converted to a double and compared with dnum. The comparison returns the integer 1 for true, which is then compared for equality with the integer 1. This is a convoluted example just to show comparison of different types and that the relational operators return an integer result. Line 7 could have been written simply as if ( dnum > 5 )

No comments:

Post a Comment