Tuesday, September 11, 2012

Operators in C

Operators are used to perform mathematical operations.
When we use a variable in a program then we have to mention the type of data. This can be handled using data type in C.
Followings are the most commonly used  operators in c

Operator Name Operators
Assignment =
Arithmetic +, -, *, /, %
Logical &&, ||, !
Relational <, >, <=, >=, ==, !=
Shorthand +=, -=, *=, /=, %=
Increment & Decrement ++, --
Conditional ()?:;
Bitwise &, |, ^, <<, >>, ~

 Assignment operators:
Operators which are used to assign the result of an expression to a variable are known as assignment operators.Consider an example,  x  +=  (y+1) .The operator += means ‘add y+1 to x’ or ‘increment x by y+1’. For y=2, the above statement results,   x  +=  3, that is (x = x + 3)

Operator Operation Performed
= Simple assignment
*= Multiplication assignment
/= Division assignment
%= Remainder assignment
+= Addition assignment
-= Subtraction assignment
<<= Left-shift assignment
<<= Left-shift assignment
>>= Right-shift assignment
&= Bitwise-AND assignment
^= Bitwise-exclusive-OR assignment
|= Bitwise-inclusive-OR assignment

Example program :
1.
#include <stdio.h>
void main()
{
	int a,b;
	clrscr();
	a = 53;
	printf("\n\t Value of A : %d",a);       // 53
	b = a;	// Interchange of value using assignment
	printf("\n\n\t Value of B : %d",b);    // 53
	getch();
}
2.
#include <stdio.h>
main()
{
      int a = 2,b;
      b = a++;
      printf("%d", b);
      getch();
      }
Arithmetic operators :
The arithmetic operators are +, -, *, /. They work the same way as they do in other languages. There are three types of arithmetic operators
 (a) Integer arithmetic : Here operands are integer. For a=14 and b=4,a/b=3(decimal part)  a%b=2(remainder of division)
(b) Real arithmetic : Here, operands are only real number. Such as, if a=6.0 and b=7.0 then a/b=0.857143
 (c)Mixed model arithmetic : Here, one operand is real and another is integer. Such as15/10.0=1.5 Whereas, 15/10=1

Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
	int a,b,c,d,e,f,g;
	clrscr();
	printf("\n\t Enter First Number :");   
	scanf("%d",&a);
	printf("\n\t Enter Second Number :");   
	scanf("%d",&b);
	c = a + b;
	printf("\n\n\t Addition is : %d",c);  
	d = a - b;
	printf("\n\n\t Subtraction is : %d",d);  
	e = a * b;
	printf("\n\n\t Multiplication is : %d",e);  
	f = a / b;
	printf("\n\n\t Division is : %d",f); 
	g = a % b;
	printf("\n\n\t Modulus is : %d",g); 
	getch();
} 
this program perform simple arithmetic operations.
Logical operators : 
Operators which are used to combine two or more relational expressions are known as logical operators. There are three logical operators. They are,
          &&              meaning logical             AND
           ||                    meaning logical             OR
           !                    meaning logical             NOT

Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
	int no1=2, no2=5;
	clrscr();
	printf("\n\n %d",(no1 &&no2));   // returns 1
	printf("\n\n %d",(no1 || no2));   // returns 1
	getch();
}
Relational operators :
The operators which are used to compare two numbers and take decision depending on their relation are called relational operators. Some relational operators are

Operator        Meaning      
<                   Is less than      
<=                 Is less than or equal      
>                   Is greater than      
>=                 Is greater than or equal      
==                 Is equal to      
!=                  Is not equal to    

Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
	int a=6, b=2;
	clrscr();
	printf("\n\n A<=B : %d",(a<=b)); // 0 - False
	printf("\n\n A>B : %d",(a>b)); // 1 - True
	printf("\n\n A!=B : %d",(a!=b)); // 1 - True
	getch();
}

Shorthand operators :
C has special shorthand that simplifies coding of certain type of assignment statements.
Example
a = a + 2;
can be written as
a + =2;     compound assignment statement
This operator  += tells the compiler that a is assigned the value of  a+2.
This shorthand works for all binary operators  in C.
General form:
<variable><operator>= <variable/constant/expression>

operator       example       meaning     
+=                  a+=2        a=a+2     
-=                   a-=2         a=a-2     
*=                   a*=2        a=a*2     
/=                    a/=2         a=a/2     
%=                  a%=2       a=a%2     
&&=               a&&=c     a=a&&c     
||=                     a||=c         a=a||c    

Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
	int a,b;
	clrscr();
	a = 18;
	b = 4;
	printf("\n\t Value of A : %d",a);  // 18
	printf("\n\t Using of B : %d",b);  // 4
	b += a ;  // b = b + a
	printf("\n\n\t Using += (i.e b=b+a): %d",b); // 22
	// Change the operator as -=, *=, /=, %=
	getch();
}

Increment and decrement operators :
 C allows two very useful operators not generally found in other languages. These are the increment and decrement operators, respectively ++ and --. The operator ++ adds 1 to the operand, while -- subtracts 1.
Rules for ++ and – operators :
i)       Increment (++) and decrement (--) operators are unary operators and they require variable as their operands.
ii)     When postfix ++ (or --) is used with a variable in an expression, the expression is evaluated first using the original value of the variable and then the variable is incremented (or decremented) by one.
iii)   When prefix ++ (or --) is used in an expression, the variable is incremented (or decremented) first and then the expression is evaluated using the new value of the variable.

Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
int a=4, b;
clrscr();
printf("\n\n Value of A : %d",a); // 4
a++; // Post
printf("\n\n Value of A : %d",a); // 5
	++a; // Pre
printf("\n\n Value of A : %d",a); // 6
b=--a;
printf("\n\n Value of A : %d",a); // 5
printf("\n\n Value of B : %d",b); // 5
b=a++;
printf("\n\n Value of A : %d",a); // 6
printf("\n\n Value of B : %d",b); // 5
b++;
printf("\n\n Value of B : %d",b); // 6
getch();
}

Conditional operators : 
 A ternary operator pair “ ? : ” is available in C to construct conditional expressions of the form exp1?exp2:exp3. The operator works as follows, exp1 is evaluated first. If it is nonzero (true) then the expression exp2 is evaluated and becomes the value of the expression. If exp1 is false, then exp3 is evaluated and becomes the value of the expression. For example, consider the following statements,
                             a=10;
                             b=15;
                             x=(a>b)?a:b;                                                                        
 In this example x will be assigned the value of b.
Example program :
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b=3;
a = 5;
printf("\n\n A is less than B ? ");
(a<b)?printf(“yes”):printf(“no”) // No
getch();
}


Bitwise operators :
 Operators which are used to manipulate data at their bit level are known as bitwise operators. Bitwise operators and their meanings are given below


Operators      Meaning      
|                    Bitwise OR      
^                   Bitwise exclusive OR      
<<                Shift left      
>>                Shift right      
&                 Bitwise AND

Operator precedence
In C, each and every operator has a special precedence which is associated with it. There are various levels of precedence. This precedence is especially used to determine to evaluation of expression which has more than one operator in it. The operators which has higher precedence are executed first and vice-verse. Operators which has same precedence level are evaluated from left to right. It is dependent on it's level. This feature is well known as 'Associativity of an operator.'

Associativity
Operator
Description
Left to Right () Function
[] Array
--> Pointer to member
. Structure
Right to left - Unary Minus
+ Unary Plus
++ / -- Increment/Decrement
~ One's Complement
& Address of
(type) Type casting
sizeof Size (in bytes)
! Logical Not
* Pointer reference
Left to Right * Multiplication
/ Division
% Modulus

Left to Right + Addition
- Subtraction



Left to Right << Left Shift
>> Right Shift



Left to Right < Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to



Left to Right == Equality
!= Not Equal to



Left to Right & Bitwise AND



Left to Right ^ Bitwise XOR



Left to Right | Bitwise OR



Left to Right && Logical AND



Left to Right || Logical OR



Left to Right ? : Conditional Operator



Right to Left =  *=  += Assignment



Left to Right , Comma

Typecasting:
Typecasting is a way to make a variable of one type, such as an int, act like another type, such as a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.
in  C language There are two ways of casting data types in C:
  • automatic (implicit)
  • given (explicit)

Implicit Casting (automatic transformation) works in a way that a variable (operand) of data type that is smaller in length (than data type of second variable) (operand), transforming internally to variable of data type with longer number length.

example
int a;
unsigned long b;
float f, g;
double d;
g = a + f; // a transforms to float
d = a + b; // a and b transform to unsigned long, adding
// is produced in unsigned long domain and then
// the result type unsigned long is transformed
// to double

Explicit Casting (given transformation) of data types has higher priority then automatic transformation. General declaration of explicit (given) cast (cast operator):
(data_type) operand
Operand can be variable or phrase.

Example:
a = (int) c;
b = (double)d + c;

For example, what if you want to create your own chart of all 128 ASCII characters. To do this, you will need to use to typecast to allow you to print out the integer as its character equivalent.


Example program :
#include <stdio.h>
#include <conio.h>
int main()
{
    for ( int x = 0; x < 128; x++ ) 
{
        printf( "%d = %c\n", x, (char)x );
    }
    getchar();

}
Consider another code:
int x=7, y=5 ;
float z;
z=x/y;    /*Here the value of z is 1*/
If we want to get the exact value of 7/5 then we need explicit casting from int to float:
int x=7, y=5;
float z;
z = (float)x/(float)y;    /*Here the value of z is 1.4*/

Some important questions:

Q. How we can add two numbers without using + symbol?

#include <stdio.h>
#include <conio.h>
main()
{
int a,b, res;
scanf("%d",&a);
scanf("%d",&b);

if(a == b)
res = a*2;
else 
res = (a*a - b*b ) / (a -b);
printf("%d",res);

}
Q. Which bitwise operator is suitable for checking whether a particular bit is ON or OFF?

Ans. Bitwise AND operator.
Suppose in byte that has a value 10101101 . We wish to check whether bit number 3 is ON (1) or OFF (0) . Since we want to check the bit number 3, the second operand for AND operation we choose is binary  00001000, which is equal to 8 in decimal.
Explanation:
ANDing  operation : 
   
         10101101       original bit pattern
         00001000       AND mask

         00001000       resulting bit pattern


No comments:

Post a Comment