Wednesday 7 August 2013

Operator in C

C Programming Operators
Operators are the symbol which operates on value or a variable. For example: + is a operator to perform addition.
C programming language has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:
Operators in C programming
1. Arithmetic Operators
Operator
Meaning of Operator
+
addition or unary plus
-
subtraction or  unary minus
*
multiplication
/
division
%
remainder after division( modulo division)
Example of working of arithmetic operators

/* Program to demonstrate the working of arithmetic operators in C.  */
#include <stdio.h>
int main(){
    int a=9,b=4,c;
    c=a+b;
    printf("a+b=%d\n",c);
    c=a-b;
    printf("a-b=%d\n",c);
    c=a*b;
    printf("a*b=%d\n",c);
    c=a/b;
    printf("a/b=%d\n",c);
    c=a%b;
    printf("Remainder when a divided by b=%d\n",c);
    return 0;
}
}
a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1
Explanation
Here, the operators +, - and * performed normally as you expected. In normal calculation, 9/4 equals to 2.25. But, the output is 2 in this program. It is because, a and b are both integers. So, the output is also integer and the compiler neglects the term after decimal point and shows answer 2 instead of 2.25. And, finally a%b is 1,i.e. ,when a=9 is divided by b=4, remainder is 1.
Suppose a=5.0, b=2.0, c=5 and d=2
In C programming,
a/b=2.5   
a/d=2.5
c/b=2.5     
c/d=2
Note: % operator can only be used with integers.
2.Increment and decrement operators
In C, ++ and -- are called increment and decrement operators respectively. Both of these operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts 1 to operand respectively. For example:
Let a=5 and b=10
a++;  //a becomes 6
a--;  //a becomes 5
++a;  //a becomes 6
--a;  //a becomes 5
When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then only increment it. This can be demonstrated by an example:

#include <stdio.h>
int main(){
    int c=2,d=2;
    printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
    printf("%d",++c);   //this statement increments 1 to c then, only c is displayed.
    return 0;
}

Output
2
4
3.Assignment Operators
The most common assignment operator is =. This operator assigns the value in right side to the left side. For example:
var=5  //5 is assigned to var
a=c;   //value of c is assigned to a
5=c;   // Error! 5 is a constant.
Operator
Example
Same as
=
a=b
a=b
+=
a+=b
a=a+b
-=
a-=b
a=a-b
*=
a*=b
a=a*b
/=
a/=b
a=a/b
%=
a%=b
a=a%b
4. Relational Operator
Relational operators checks relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0. For example:
a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Relational operators are used in decision making and loops in C programming.
Operator
Meaning of Operator
Example
==
Equal to
5==3 returns false (0)
> 
Greater than
5>3 returns true (1)
< 
Less than
5<3 returns false (0)
!=
Not equal to
5!=3 returns true(1)
>=
Greater than or equal to
5>=3 returns true (1)
<=
Less than or equal to
5<=3 return false (0)
5.Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical operators:
Operator
Meaning of Operator
Example
&&
Logial AND 
If c=5 and d=2 then,((c==5) && (d>5)) returns false.
||
Logical OR
If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
!
Logical NOT
If c=5 then, !(c==5) returns false.
Explanation
For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false.
6.Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
7. Bitwise Operators
A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.
Operators
Meaning of operators
&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR
~
Bitwise complement
<< 
Shift left
>> 
Shift right
Bitwise operator is advance topic in programming . Learn more about bitwise operator in C programming.
8.           Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a,c=5,d;
The sizeof operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc. For example:

#include <stdio.h>
int main(){
    int a;
    float b;
    double c;
    char d;
    printf("Size of int=%d bytes\n",sizeof(a));
    printf("Size of float=%d bytes\n",sizeof(b));
    printf("Size of double=%d bytes\n",sizeof(c));
    printf("Size of char=%d byte\n",sizeof(d));
    return 0;
}
Output
Size of int=4 bytes
Size of float=4 bytes
Size of double=8 bytes
Size of char=1 byte
Conditional operators (?:)
Conditional operators are used in decision making in C programming, i.e, executes different statements according to test condition whether it is either true or false.
Syntax of conditional operators
conditional_expression?expression1:expression2
If the test condition is true, expression1 is returned and if false expression2 is returned.
Example of conditional operator
#include <stdio.h>
int main(){
   char feb;
   int days;
   printf("Enter l if the year is leap year otherwise enter 0: ");
   scanf("%c",&feb);
   days=(feb=='l')?29:28;
   /*If test condition (feb=='l') is true, days will be equal to 29. */
   /*If test condition (feb=='l') is false, days will be equal to 28. */
   printf("Number of days in February = %d",days);
   return 0;
}
Output
Enter l if the year is leap year otherwise enter n: l
Number of days in February = 29
Other operators such as &(reference operator), *(dereference operator) and ->(member selection) operator will be discussed in pointer chapter.
- See more at: http://www.programiz.com/c-programming/c-operators#relational

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