Operators in C

Operators in C


The purpose of operators is to perform the manipulations with operands(variables)

Operators are following

1.Relational Operators - For comparing purpose , >,<,>=,<=,==,!=

2.Assignment operator - =

3.Arithmetic Operators - to perform mathematical operations +,-,*,/,%

4.Logical Operators - to compare with multiple conditions or opposition conditions 

                        &&(and),||(or),!(not)

5.Bitwise Operators - to perform the manipulations with binary data(1s and 0s)


   &(bitwise and),|(bitwise or),^(xor),<<(left shift operator),>>(right shift operator)

The following truth table explains how logical operators and xor operator gives the result. Let us take there are two inputs P and Q

  P      Q       P&&Q     P||Q     P^Q

  0      0            0            0        0
  0      1            0            1        1
  1      0            0            1        1
  1      1            1            1        0

Using bitwise & verifying the given number is even or odd

if you are using '&' between any number and 1 if the result is 0 then the number is even otherwise the number is odd

Example:

7 is even or odd

For 7 the binary number is 0111


  0111
  0001
&-----
  0001 ---> 7 is odd


  12 is even or odd

  For 12 the binary number is 1100


  1100
  0001
&-----
  0000 -----> 12 is even


Example : interchange two numbers by using ^(xor)

 n1=6   n2=8

For  6 binary number is - 0110
For  8 binary number is - 1000

n1=n1^n2

   0110
   1000
^-------
   1110

n2=n1^n2

   1110
   1000
^------
   0110 - 6

n1=n1^n2

   1110
   0110
^------
   1000 - 8


<<(left shift operator) - in this case bits can be moves towards left and ending can be filled with 0s.


    8<<2
    00001000<<2
    00100000 - power(2,5) - 32
    left shift operator represent multiplication
        8*power(2,2)=8*4=32

>>(right shift operator) - in this case the bits can be moves towards right and the beginning can filled with 0s.



      12>>3
      00001100>>3
      00000001 --> 1
      right shift operator represent division
      12/power(2,3)=12/8=1

6. Unary Operators

      - increment operator --- ++
      - decrement operator --- --
    int n=5;
    printf("%d",n++);  // 5
    printf("%d",++n);  //7
    printf("%d",n--);  //7
    printf("%d",n);    //6

   shortcut notations for arithmetic operators

   syntax
          variable operator=value
   Example

     int n=5;
        n+=10---->n=n+10---->5+10=15
        n*=2----> n=n*2---->15*2=30

7. Ternary or Question Mark or Conditional Operator

      Syntax
      (expression)?value1:value2
      int n1=16,n2=21
      printf("%d",(n1>n2)?n1:n2);

Comments

Popular posts from this blog

Functions

Example Programs for Control Flow Statements

SQL Operators