Wednesday, 7 August 2013

Operator in C

C Operators

o        what is operators
o        Logical operators
o        Bitwise operators
o        Arithmetic operators
o        Relational operators
o        Sizeof operators
o        Comma operators
o        Type cast operator
o        Ternary operators
o         
v C Operators

What is operators?
In simple word operators are those which operator anything like as data,maths,information etc i.e.. When we talking about C operators, i want to say you that C is very rich in operators. Operators tells to compiler that what do with data. There are mainly operators in c as following:
1.       Logical Operators
2.       Bitwise Operators
3.       Relational Operators
4.       Assignment Operators
5.       Sizeof Operators
6.       Increment and Decrement operators
7.       Comma operators
8.       Type cast operator
9.       Conditional operators or ternary operators
Sometime operators are divided according numbers of operands. So there are three types of operators as following : 
Operators
Unary
Binary
Ternary
operand
single
double
third
works
right to left
left to right
left to right
Example_1
++ , --
+, -, *, /
? :
Example_2
! , ~
&& , ||


1.Logical Operator

 

When we use if, for, while then use one condition at once time what happen if we examine condition more than one? In this case we use logical operators. So logical operators are used to combine two or more condition.
There are three types of  logical operators as following:
Operator symbol
Name
&&
Logical AND
||
Logical OR
!
Logical NOT

LOGICAL AND OPERATOR ( && )

The condition is true if and only if both two expression are true otherwise condition false. The truth table of logical AND operators end of this chapter.

LOGICAL OR OPERATOR ( || )
 The condition is true if one of expression is true and condition will be false only if both expression are false. See example of || operator at end of this chapter.

LOGICAL NOT OPERATOR ( ! )

It reverse the expression i.e if the expression evaluates   to a non-zero value, then applying ! operator to it results into a 0 and vice versa. The final result (after applying ! ) 0 or 1 is considered to be false or true respectively.

Example of above three operators :
//following table con = condition.
con 1
Con 2
con 1 && con 2
con 1 || con 2
! con 1
! con 2
False
False
False
False
True
True
False
True
False
True
True
False
True
False
False
True
False
True
True
True
True
True
False
False

Some numerical example :
if(10>5 && 1000<2001)  // True
while( ; num>=1 || num<=100  ; ) // if num=1  True

Now some discuss of  NOT operator when we write condition if( 1 ! = 0 ) what is mean it? It is mean "one is not equal to zero", so is condition TRUE or False? It is true.

Let's understand following example :

if(sex!='M')
  printf("Person is Female");
else
  printf("Person is Male");

In above example evaluate first printf if condition is false otherwise evaluate second printf.

!(x<22) it is also we write (x>=22) // both are equal.

Write a C Program by using Logical AND and OR Operator

Description: Logical Operators

Statement of C Program: This Program illustrates the logical ANDing and ORing operations: 

#include<stdio.h>
#include<conio.h>
void main()
{
int a , b , c;
clrscr();
a = 4 , b = 3;

c = a && b;
b = a||b||c;
a = a && b||c;
printf("%d" , a\n);
printf("%d" , b\n);
printf("%d" , c\n);
}

Output:
1
1
1

2.Bitwise operators

 

The smallest element in memory on which are able to operate is called byte; and the programming language are byte oriented. One of the c powerful features is a set of bit manipulation operators. There are various bitwise operators in C as following table; we learn all step by step :
Operators
Name
&
Bitwise AND
|
Bitwise OR
^
Bitwise XOR(exclusive OR)
>> 
Left shift
<< 
right shift
~
One's complement


These operators can operate upon ints and chars but not on floats and doubles. Bits are numbered from zero onwards, increasing from right to left as following figure:

7
6
5
4
3
2
1
0

8 bit Character


16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0

16 bit Integer


Bitwise AND Operator (&)

The & operator operates on a pair of bits to yield a resultant bit. The rules that decide the value of the resultant bit also called truth table are shown below:

Bit x
Bit y
x & y
0
0
0
0
1
0
1
0
0
1
1
1

The best use of the AND operator is to check whether a particular bit of an operand is ON or OFF. The meaning of ON means 1 and OFF means 0. The following program puts this logic clear:

 /*Example of bitwise AND operator*/

 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int x=45;
  int y=37;
  int z;
  clrscr();
  z = x & y;
  printf("\nValue of z=%d",z);
 }



 Output of above program:

 Value of z=37


In above program compiler first calculate the binary x and y which is 111101 and 100101 respectly. After this its work on bitwise operator and final result is 37 which binary code are 100101. The following table shown the result : 
Values
binary code
x = 45
111101
y = 37
100101
z = x & y
100101


Bitwise OR ( | )

Truth table for bitwise OR are as following :
x
y
z = x | y
0
0
0
0
1
1
1
0
1
1
1
1

Bitwise XOR ( ^ )

It is also called exclusive OR. If there are similar bit then its return 0 otherwise its return 1. Let watch truth table of  x^y :
x
y
z = x ^ y
0
0
0
0
1
1
1
0
1
1
1
0

Example of exclusive OR :
x = 75
y = 64
z = x ^ y

 x = 1 0 0 1 0 1 1
 y = 1 0 0 0 0 0 0
 z = 0 0 0 1 0 1 1

hence, the value of z=11

Bitwise right shift ( >> )

Right shift operator shifts each bit in its left operand to the right. The number of places the bits are shifted depends on the number following the operator i.e. its right operand.
In simple meaning of bitwise right shift as :

            insertion(zero)  >  deletation

Example of right shift operator :
x = 15
y = x >> 2

[x=15 before right shifting ]         0000  0000  0000  1111
[y = x >> 2 during right shifting]  000000  0000  0000  1111
[y = x >> 2 after right shifting]     0000  0000  0000  0011

so now value of y=3.

Left Shift operator ( << )

This is similar to the right shift operator, the only difference being that the bits are shifted to the left, and for each shifted, a 0 is added to the right of the number. Following structure shows it :

  deletatio   >  insertion(zero)  

Example of right shift operator :
x = 15
y = x << 2

[x=15 before right shifting ]            0000  0000  0000  1111
[y = x << 2 during right shifting]     0000  0000  0000  111100
[y = x << 2 after right shifting]        0000  0000  0011  1100


so now value of y=60.


One's complement ( ~ ) or Tilde

It is reverse the bit i.e. if bit is 0 then its return 1 and when bit is 1 it is return 0.
example of tilde:
x = 15
y = ~ x

(15)10 = 0000 0000 0000 1111
y = ~ x   1111 1111 1111 0000
hense, 65535 - 15 = 65520.
so the value of y is 65520. 

3.             Arithmetic Operator

 

Arithmetic operators are special mathematical symbol which do all arithmetical calculation of the programs. Following table display the operators and their works:
Name of operators
Symbol
works
example
Addition operator
+
Add the numbers
sum=7+8+1=16
Subtract operator
-
Subtraction of numbers
sub=100-50=50
Multiply operator
*
Multiple of numbers
muti=8*9=72
Modulus operator
%
Find the reminder of numbers
mod=45%40=5
Division operator
/
Find the division of numbers
div=45/40=1

4.Realational Operator

 

When we write program, many time we requirement to comparison of two or more data, in that case we uses relational operators. There are following relational operators as following : 

Operators    Name
    >      Greater than
    <      Less than
    =      Equals  to
    >=     Greater than equals to
    <=     Less than equals to
    !=     Not equals to

The syntax of relational expression as :

<data value 1>Relational operator<data value 2>

Example :

10 >= 5
-50 <= 1
0 != 0

5. Sizeof operator


Sizeof operator calculate the size of data i.e. how many bit a specific data having.

Syntax of sizeof operator :

printf("<format string>",sizeof<(data type variable)>);


 /*Program to sizeof operator*/
 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int x=10;
  clrscr();
  printf("\nSize of  x is %d",sizeof(x));
  getch();
 }


  Output of above program :

  Size of x is 2 


We read in data type chapter that an int allocate only 2 byte in memory,Hence, x = 2.


6.Increment and Decrement operators
Increment operators (++)

·                     Increment operators are increase the value of subsequent. value may be increase according to the programmer.
·                     Increment operator are two types as follows :
1.       Post increment
2.       Pre increment
 Decrement operators ( -- )
·                     decrement operators decrease the value to one, two and so on.
·                     As like Increment operators, decrement operators are also two type as :  
1.       Post decrement
2.       Pre decrement
Before we more discuss about increment and decrement operator, let understand some expression; that's are using in all operators.

Now some issues of pre and post increment and decrement, we will discuss after solve following programming :

 x = 5       x = 5     x = 5  
 x = x+1      ++x       x++     
 x = 6       x = 6      x=5        
In above program u notice that value of x increase to one in all three expression but after the increasing one, the final value of x in not same, third box result is differ to another two boxes. Now you know that c operators are mostly three types, ++ and -- operators are Unary operators.

Post increment or decrement are lowest precedence so it is solve at the end of program. Hence above program in third box first value of x is print i.e. 5 after, it is increase.


Unary operators are solve right to left.


Q.1 Solve the expression in C language compiler ,assuming x,z are integer variables:
z = x++ + x++
where x=7
Ans.
stepwise evaluation of this expression is shown below : 

 z = x++ + x++ + ++x
 //post increment of x=2
 z = x + x + ++x
 //++x increase the value of x one so x=8 
 /*Now all pre and post increment/decrement are  solved so we write the the expression in normal mathematical expression*/
 z = x + x + x
 //put the current value of x i.e. 8
 z = 8 + 8 8
 z = 24


syntax : x=current value-post increment/decrement
so x = 8 + 2
   x = 10

Q.2 Solve the following expression : 
z = ++x + y-- - ++y - x-- - x-- - ++y - x--
where   x = 7
        y = -3
Ans.
 z=++x  + y-- - ++y - x-- - x-- - ++y - x--
 /* post decrement of x=3 and
    post decrement of y=1 */
 z= ++x + y - ++y - x - x - ++y - x
 /* its unary operator so we solve it from
 right to left*/
 z=++x + y - ++y - x - x - y - x
 //now y=-3+1=-2
 z=++x + y - y - x - x - y - x
 //now y=-2+1=-1
 z=x + y - y - x - x - y - x
 //now x=7+1=8
 /*now all increment and decrement operators  
 all solved so we put the current value of x  
 and y.*/
 z= 8 + (-1) - (-1) -- 8 - (-1) - 8
 z= 8 + 1 - 8 + 1 - 8
 z= - 16 + 1
 z= -15
 x=8-3=5  
 y=-1-1=-2


Related some increment or decrement operators exercise:

Q.3  solve the following equations:

z = x++ 
+ ++y - x-- + --y

where x = 7 and
         y = 9

hint:(For your cross-checking, answer is x=7, y=9 and z=18).

Q.4 solve the following equations:

z = x++ 
* y++ / ++x - --y  % x++

where x = 5 and
         y = 2

hint:(For your cross-checking, answer is x=8, y=2 and z=0).

--------------------------------------------------------------------------------

Q.3 answer with explanation :

z = x++ 
+ ++y - x-- + --y


where x = 7 and
         y = 9

Ans:

post decrement of x = 1
post increment of x = 1

z = x 
+ ++y - + --y
z = x + ++y - x + y  
// now y = 9-1 = 8
z = x + y - x + y      
// now y = 8+1 = 9
// now put the value of x and y
z = 7 + 9 - 7 + 9
z = 9 + 9
z = 18

Hence, our final answer will be:

x = 7 - 1 + 1 = 7
y = 9
z = 18

7.Comma operator
Comma operator ( , )
·                     Evaluate of comma operator- Left to right.
·                     Uses of comma operator as following :
1.       Multiples declaration
2.       Multiples initialization
3.       Multiples variation
4.       Multiples statement 
·                     Example of comma operator
1.       int x=0,y=1,z=2;
2.       for(x=0 , y=1, z=2 ; condition1 ,condition2 ;increment/decrement)

8.Type-cast operator
The type cast operator is very important in C. Cast operator uses in convert one data type to another data types. Type casting may be two types:
1.       Implicit type cast
2.       Explicit type cast
Implicit type cast

In C, implicit type cast are automatically handled by compiler i.e. when two or more data types are getting execution then the final data-type will be that data type as it is declared, i.e it is not depend on conversion of data type.
It is clear understand by example as:

 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int i,j;
  float f;
  double d;
  i=d*f+f*j;
 }

what you think, what will be data type of i?
it is double!! No, right answer is int. You see in program that double has high priority or  precedence of float and int, so result of data type will be comes in double but when result is assign in i, it will be convert in int because i is declared as int. It is implicit type casting.

Explicit type cast

An explicit type cast is a cast that we should specify invoke with either the cast. The compiler does not automatically invoke to resolve the data type conversion.
Let's understand explicit with example:

/*A student marks of three subject as m1,m2,m3 and calculate percentage(per)*/
#include<stdio.h>
#include<conio.h>
void main()
{
 int m1=70,m2=70,m3=100,total;
 float per;
 total=m1+m2+m3;
 per=total/300*100;
 printf("%f",per);
}
output:- 0.000000

Surprise, let's explain to me, it is a common type cast mistake, look at per=total/300*100; statement. In this statement first of all total/300 will be solve so total(240) and 300 are int hence 240/300 will be produce a float value so result is 0.000000. These mistake may me solved by three ways as:

1. We mention type cast in above program as: 
 /*demonstration of type casting*/ 
 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int m1=70,m2=70,m3=100,total;
  float per;
  total=m1+m2+m3;
  per=(float)total/300*100;
  printf("%f",per);
 }

 output:- 80.000000


2. We used total as float variable.
 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int m1=70,m2=70,m3=100;
  float per,total;
  total=m1+m2+m3;
  per=total/300*100;
  printf("%f",per);
 }

 output:- 80.000000


3. we convert int to float to the 300 by adding decimal portion.
 #include<stdio.h> 
 #include<conio.h>
 void main()
 {
  int m1=70,m2=70,m3=100,total;
  float per;
  total=m1+m2+m3;
  per=total/300.0*100;
  printf("%f",per);
 }

 output:- 80.000000


9.Ternary operator
Main features of ternary operators as follows : 
·                     There are three operand.
·                     It works from left to right
·                     Example of ternary operator is conditional operator. Symbol of conditional operator : condition ? True_parts : False_parts 


No comments:

Post a Comment