Showing posts with label Operators in C. Show all posts
Showing posts with label Operators in C. Show all posts

Saturday, 7 January 2012

Operators in C

C supports various operators to perform different kind of operations. 
With C operators, you can do arithmetic, compare data, modify variables, combine relationship logically... etc. C operators operates on one or more operands to produce a value.
Operators taking just one operand are called unary operators.
Operators requiring two operands are called binary opeartors.
Data itself is called as operands.
Types of operators are
1)Arithmetic Operators
supports almost common arithmetic operators such as +,-,* , / .     
            Continue reading.......
2)Modulus Operator
Modulus operator %.It is an unary operator..... 
              Continue reading.......
3)Unary Operators
Increment and Decrement Operators are called Unary Operators.....
.          Continue reading.......
4)Relational Operators
C provides you a list of relational opeartors to allows you to compare data. The relational operators enable you to check whethere two variables or expressions are equal, not equal, which one is greater or less than other......
             Continue reading.....
5)Logical Operators
C logical operators enable to combine relational operators or logical operators into one boolean result. C supports the negation (!), logical AND (&&), and logical OR (||).....
             Continue reading.....
6)Bitwise Operators
C provides you six bitwise operators including AND, inclusive OR, left shift, right shift and one's complement for bit manipulation.......
             Continue reading.....
7)Assignment Operators
C assignment operators are used to assigned the value of a variable or expression to a variable..... 
             Continue reading.....
8)Conditional Operator
C ternary operator is sometimes called conditional operator or trinary operator because it is a shorthand of combination of the if-else and return statement and has three operands........ 
             Continue Reading......

Conditional Operator

Conditional operator is sometimes called tenary operator or trinary operator because it is a shorthand of combination of the if-else and return statement and has three operands. 
The syntax of C ternary operator is as follows:
condition ? expression 1 : expression 2
C first evaluates the condition. Based on the return value of the condition the second or third operand is evaluated:
If the condition is evaluated to true (1), only the second operand (expresion 1) is evaluated. Then the operator return the value of the expression 1.
If the condtion is evaluated to false (0), only the third operand (expression 2) is evaluated. The value of the expression 2 is returned.
The ternary operator can be rewritten as the if-else and return statement as follows
if(condition)
   return expression1;
else
   return expression2;
Example of C Ternary Operator
In this example, we are going to write an inline function that uses C ternary operator to find the minimum number between two integers.
/*Purpose: A program demonstrates C ternary operator */
#include <stdio.h>
#include <stdlib.h>
/* Find min of two integers
   @param x
   @param y
   @return minimum value of x and y */
inline int min(int x, int y) { return x <= y ? x : y; }
int main(int argc, char** argv) 
{
    int x = 10;
    int y = 15;
    printf("x=%d,y=%d\n", x, y);
    printf("min(x,y)=%d\n", min(x, y));
    return (0);
}
x=10,y=15
min(x,y)=10

Assignment Operators

C assignment operators are used to assigned the value of a variable or expression to a variable. 
The syntax of assignment operators is:
var = expression;
var = var;
Beside = operator, C programming language supports other short hand format which acts the same assignment operator with additional operator such as +=, -=, *=, /=, %=.
var +=expression; //is same as
var = var + expression;
Each assignment operator has a priority and they are evaluated from right to left based on its priority. 
Here is assignment operator and its priority: =, +=, -=, *=, /=, %=.
A simple C program to demonstrate assignment operators:
#include <stdio.h>
/* a program demonstrates C assignment operator */
void main(){
    int x = 10;
    /* demonstrate = operator */
    int y = x;
    printf("y = %d\n",y);
    /* demonstrate += operator */
    y += 10;
    printf("y += 10;y = %d\n",y);
    /* demonstrate -= operator */
    y -=5;
    printf("y -=5;y = %d\n",y);
    /* demonstrate *= operator */
    y *=4;
    printf("y *=4;y = %d\n",y);
    /* demonstrate /= operator */
    y /=2;
    printf("y /=2;y = %d\n",y);
}
Here is the output:
y = 10
y += 10;y = 20
y -=5;y = 15
y *=4;y = 60
y /=2;y = 30

Bitwise Operators

C's bitwise operators work on the bits stored in integral types. They work similar to the logical operators except that instead of working on true and false values they work with ones and zeroes. There are several bitwise operators available:
Symbol      Meaning
  ~           Complement
  &           And
  |            Or
  ^           Exclusive-Or
  <<         Left shift
  >>         Right shift
The complement operator is a unary operator. 
The other bitwise operators are binary, taking two operands.
Bitwise operator works on bits and perform bit by bit operation.
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
The Bitwise operators supported by C language are
Operator
Description
Example
&
Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) will give 12 which is 0000 1100
|
Binary OR Operator copies a bit if it exists in eather operand.
(A | B) will give 61 which is 0011 1101
^
Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) will give 49 which is 0011 0001
~
Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.
(~A ) will give -60 which is 1100 0011
<< 
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
A << 2 will give 240 which is 1111 0000
>> 
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
A >> 2 will give 15 whi

Logical Operators

There are three logical operators in C language, they are,or,and,not. They are represented by &&, ||,! respectively.
These operators are refered to as logical and, logical or,logical not respectively.
The result of a logical and operation will be true only if both operands are true, whereas the result of a logical or operation will be true if either operand is true or if both operands are true.
The logical operators act upon operands that are themselves logical expressions.
(i) Logical AND (&&):-
It is a binary operator.
Syntax: op1 && op2
Table
op1         op2      op1&&op2
0               0            0
0               1            0
1               0            0
1               1            1
C language treats a non-zero value as true and 0 as false,But gives true as 1 and false as 0.
Example
main()
{
int a=7,b=13,C;
C=a&&b;
printf("%d",c);
}

(i) Logical OR (||):-
It is a binary operator.
Syntax: op1 && op2
Table
op1         op2      op1&&op2
0               0            0
0               1            1
1               0            1
1               1            1
C language treats a non-zero value as true and 0 as false,But gives true as 1 and false as 0.
It changes true and false to true.
Example
main()
{
int a=7,b=0,C;
C=a||b;
printf("%d",c);
}

i) Logical NOT (||):-(Negation Operator)
It is a unary operator.
Syntax: op1 && op2
Table
op         !op
1             0
0             1
C language treats a non-zero value as true and 0 as false,But gives true as 1 and false as 0.
It changes true to false and false to true.
Example
main()
{
int a=7,b;
b=!a|;
printf("%d",b);
}

Relational Operators

Relational operators are symbols that are used to test the relationship between two variables, or between a variable and a constant.
These operators are binary operators.
The test for equality, is made by means of two adjacent equal signs with no space separating them. 
‘C’ has six relational operators as follows:

>   greater than
<   less than
!=  not equal to
>= greater than or equal to
>= less than or equal to

These operators all fall within the same precedence group, which is lower than the unary and arithmetic operators. The associativity of these operators is left-to-right.

The equality operators ==and != fall into a separate precedence group. Their associativity is also from left-to-right.


Let us understand operations of these relational operaters with the help of an example: x=2, y=3, z=4.
x<y               true     1
(x+y) >=z     true     1
(y+z)>(x+7)  false    0
z!=4              false    0
y ==3            true    1
Here, true or false represents logical interpretation and they have values 1 and 0 respectively.
Example
main()
{
int a=5,b=7,c;
c=a<b;
printf("%d",c);

c=a<=b;
printf("%d",c);

c=a>b;
printf("%d",c);

c=a>=b;
printf("%d",c);

c=a==b;
printf("%d",c);

c=a!=b;
printf("%d",c);
}

Unary Operators

‘C’ includes a class of operators that act upon a single operand to produce a new value. Such operators are known as unary operators.
Unary operators usually precedes their single operands, though some unary operators are written after their operands.

The most common unary operator is unary minus, where a minus sign precedes a numerical constant, a variable or an expression.
e.g.
-5,-10, -20(numbers)
x=-y(variable)

Of all the arithmetic operators, the unary minus has the highest precedence level. Thus in an expression such as
y=x+z* -b;
evaluation commences with the unary minus, which negates the value of b. Then z is multiplied by –b, and finally the addition takes place.

Two other commonly used unary operators are increment operator, ++, & the decrement operator - -. 
The increment operator causes its operand to increased by one, whereas the decrement operator causes
its operand to be decreased by one. 
The operand used with each of these operators must be a single variable.
For example, x is an integer variable that has been assigned a value of 10. The expression ++ x, which is equivalent to writing x= x+1, causes the value of x to be creased to 11. 
Similarly the expression --x, which is equivalent to x=x-1, causes the original value of x to be decreased to 9.

The increment and decrement operators can each be utilized in two different ways, depending on whether the operator is written before or after the operand.
Another unary operator is the sizeof operator . This operator returns the size of its operand, in bytes. This operator always precedes its operand. The operand may be an expression, or it may be a cast.
e.g 
sizeof (x);
sizeof (y);

If x is of integer type variable and y is of floating point variable then
the result in bytes is 2 for integer type and 4 for floating point
variable.

Modulus Operator

% is called as Modulus Operator.
It is a binary Operator.
It gives the remainder of the supplied operands.
The modulus operator requires that both operands be integers & the second operand be nonzero.

Example
main()
{
int x;
x=5%2;
printf("d",x);
}
If numerator is less than denominator we get numerator as remainder.
main()
{
int x;
x=7%70;
printf("%d",x);
}
The sign of the result depends only on the sign of numerator but not on denominator.
main()
{
printf("%d\n",4%3); //gives 1
printf("%d\n",4%-3);//gives 1
printf("%d\n",-4%3);//gives -1
printf("%d\n",-4%-3);//gives -1
}
Modulus operator on float values is not applicable.

Arithmetic Operators

There are five main arithmetic operators in ‘C’. They are ‘+’ for additions,‘-' for subtraction, ‘*’ for multiplication, ‘/’ for division.
Operands can be integer quantities, floating-point quantities or characters.

The division operator (/) requires that the second operand be nonzero.


If division operation is carried out with two floating- point numbers, or with one floating point number. & one integer, the result will be a floating-point quotient.


If we take two variables say x and y and their values are 20 and 10
respectively, and apply operators like addition, subtraction, division,
multiplication and modulus on them then their resulted values will
be as follows:
x+y=30
x-y=10
x*y=200
x/y=2


If one or both operands represent negative values, then the addition, subtraction, multiplication and division operations will result in values whose signs are determined by the usual rules of algebra.


  • If one operand is a floating point type and the other is a char or an int, the char/int will be converted to the floating point type of the other operand and the result will be expressed as such.So, an operation between an int and a double will result in double.
  • If both operands are floating-point types with different precisions, the lower-precision operand will be converted to the precision of the other operand and the result will be expressed in this higher precision.

  1. Float & double -->double
  2. Float & long double -->long double
  3. Double & long double -->long double

  • If neither operand is a floating point type or a long int, then both operands will be converted to int & the result will be int.
  • If neither operand is a floating point type but one is a long int,the other will be converted to long int & the result will be long int.

The operator within C are grouped hierarchically according to their order of evaluation known as precedence.

Arithmetic operators *,/ and % are under one precedence group and +,- are under another precedence group. The operators *, / and % have higher precedence than + and -.
Example
main()
{
int a,b,c;
a=10;
b=20;
c=a+b;
printf("%d",c);
c=x-y;
printf("%d",c);

c=x*y;

printf("%d",c);


c=x/y;

printf("%d",c);

}
host gator coupon