Saturday, 5 October 2013

Operators and Expressions in C


2.1       OPERATORS & EXPRESSIONS

An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. they usually form a part of the mathematical or logical expressions. C supports a number of operators, they can be classified as below:

1.       Arithmetic Operators (+, –, *, /, %)

2.       Relational Operators (<, >, <=, >=, ==, !=)

3.       Logical Operators (&&, ||, !)

4.       Assignment Operators (=, compound  assignment operators: +=, -=, *=, /=, %=)

5.       Increment & Decrement Operators (++, - - )

6.       Conditional Operators (…?... : …)

7.       Bitwise Operators (~, <<, >>, &, |, ^)

8.       Other Special Operators (sizeof)

 

1.      Arithmetic Operators

All the arithmetic operators provided by C are listed in the table:

Arithmetic Operators
Operator
Meaning
+
Addition / Unary plus
-
Subtraction / Unary minus
*
Multiplication
/
Division
%
Modulo division

 

·         The unary minus ‘-‘ in effect, multiplies its single operand by -1. Therefore, a number preceded by a minus sign changes its sign.

·         The modulo division operator ‘%’ produces the reminder of an integer division.

Behavior of ‘/’ operator-

Ex.      result = op1 / op2

DT of op1
DT of op2
Data type of result
int
int
int (fractional part truncated not rounded)
float
int
float
int
float
float
float
float
float

 

Example:

int a=10, b=3;

int v1 = a+b, v2 = a-b, v3 =  a*b;

       float v4 = (float)a/b;

       int  v5 = a%b, v6 = b%a, v7 = -a+b;

printf(“%d %d %d %f %d %d”, v1,v2,v3,v4,v5,v6,v7);      

 

Output:

10, 7, 30, 3.333333, 1, 3,  -7

 

·         ‘/’  can be used to check whether a number is completely divisible by another number or not.

Example:





int main()

{  int a, b;

   printf(“\nEnter tow numbers: “);

   scanf(“%d%d”,&a,&b);

   if (a == (a/b)*b);

       printf(“\n%d is completely divisible by %d”,a,b);

   else

       printf(“\n%d is not completely divisible by %d”,a,b);

   return 0;

}






 

·         /’ can be used to truncate last digit of a number by dividing the number by 10.

Example–





int main()

{   int a, digit;

    printf(“\nEnter a number of more than two digits: “);

    scanf(“%d”,&a);

    digit = a/10;

    printf(“\nThe remaining number is : %d”, a);

    return 0;

}




Behavior of Modulus operator (%) –

·         The property of modulus operator is used to generate numbers in a restricted range. The expression  a % b  will generate number ranging from 0 to b-1.

 

For example:

 x % 100 will generate numbers from 0 to 99 for any value of x.

 

·         The modulus operator is also used to extract last digit of a number. x%10 will always give the last digit of the number x.

 

For example: 

153 % 10 à 3, 

7842 % 10 à 2, 

98 % 10 à 8, 

4 % 10 à4.

 

Ø  Integer arithmeticWhen both operands in a single arithmetic expression are integer then expression is called integer expression and the operation is called integer arithmetic.

Ø  Real arithmeticWhen arithmetic expression has only real operands this it is called real arithmetic. A real operand may assume value either in decimal or exponential notation.

Ø  Mixed-mode arithmeticWhen one of the operand is real and the other is integer, the expression is called a mixed-mode arithmetic expression.

 

2.      Relational Operators

We often compare two quantities and depending on their relation, take certain decisions. The compression can be done with the help of relational operators. Relational operators check 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. C supports six relational operators as listed in below:

 

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)

 

·         The expression containing a relational operator is termed as a relational expression.
E.g.   a + b  >=  c + 5.

·         The value of a relational expression is either 0 (false) or 1 (true).
e.g. 
a = 10 < 20;                          then a = 1 
a = 10 > 20;                          then a = 0

·         A simple relational expression contains only one relational operator and takes the form:
AE-1 relational operator  AE-2,
where AE-1 and AE-2 are arithmetic expressions which may be simple constants, variables or combination of them.

Eg. (2+3) > (1+2);

·         When arithmetic expression are used on either side of a relational operator, the arithmetic expressions will be evaluated first and then the result is compared i.e. arithmetic operators have a higher priority over relational operator.

·         Relational expressions are used in decision statements such as if, while, for etc.

 

3.      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
int c=5;
!(c==5) returns false (0).

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.

 

The logical operator &&  and ||  are used when we want to test more than ore  condition and make decision e.g.   a > b  &&  x = = 10;

·         An expression which combines tow or more relational expressions  is known as logical expression or a compound relational expression.

·         Like the simple relational expressions, a logical expression also yields a value of 0 (false) or 1 (true), according to the truth table shown below, where a  and  b  are any relational expressions:            

a
b
a && b
a || b
!a
!b
0
0
0
0
1
1
0
1 (non-zero)
0
1
1
0
1 (non-zero)
0
0
1
0
1
1 (non-zero)
1 (non-zero)
1
1
0
0

Ex.          x=11, y=6, z=1

        Value = x > 9 && y!=3                     o/p:  Value = 1,

        Value = ! (x>9 && y!= 23)             o/p:  Value = 0

·         In expression with && operator if first part of expression has the value 0 then the second part will not checked, because in logical AND if first condition is false then whole expression will false, no need to check second part.

·         In expression with || operator if first part of expression has the value 1  then the second part will not checked, because in logical OR if first condition is true then whole expression will true, no need to check second part.

Examples– 

Open the parenthesis for the condition

(i)  !(a < b)                                                   Ans. ! (a) >=  ! (b)

(ii)  !(c1 && c2)                          Ans.  ! (c1) || ! (c2)


1.      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.

 

Compound Assignment Operators:

Operator
Example
Same as
+=
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

 

2.      Increment & 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.      Conditional Operators

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.

 

4.      Bitwise Operators

Bitwise operators are special types of operators that are used in programming the processor. In processor, mathematical operations like: addition, subtraction, addition and division are done using the bitwise operators which makes processing faster and saves power.

Operators
Meaning of operators
&
|
^
~
<< 
>> 

Bitwise AND operator in C programming.


The output of logical AND is 1 if both the corresponding bits of operand is 1. If either of bit is 0 or both bits are 0, the output will be 0. It is a binary operator(works on two operands) and indicated in C programming by & symbol. Let us suppose the bitwise AND operation of two integers 12 and 25.

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
 
Bit Operation of 12 and 25
  00001100
& 00011001
  ________
  00001000  = 8 (In decimal)

As, every bitwise operator works on each bit of data. The corresponding bits of two inputs are check and if both bits are 1 then only the output will be 1. In this case, both bits are 1 at only one position, i.e, fourth position from the right, hence the output bit of that position is 1 and all other bits are 0.


 

#include<stdio.h>

void main()

{

                int a=12,b=25;

                printf("Output=%d",a&b);           // Output=8

                getchar();

} 

Bitwise OR operator in C


The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1. In C Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
 
Bitwise OR Operation of 12 and 25
  00001100
| 00011001
  ________
  00011101  = 29 (In decimal)
 
Example:
 

#include<stdio.h>

void main()

{

                int a=12,b=25;

                printf("Output=%d",a&b);           // Output=8

                getchar();

} 

C Programming Bitwise XOR(exclusive OR) operator


The output of bitwise XOR operator is 1 if the corresponding bits of two operators are opposite(i.e., To get corresponding output bit 1; if corresponding bit of first operand is 0 then, corresponding bit of second operand should be 1 and vice-versa.). It is denoted by ^.

12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
 
Bitwise XOR Operation of 12 and 25
  00001100
| 00011001
  ________
  00010101  = 21 (In decimal)
 
Example: 

#include<stdio.h>

int main()

{   int a=12,b=25;

    printf("Output=%d",a^b);    // Output=21

    return 0;

}

 

Bitwise compliment operator


Bitwise compliment operator is an unary operator(works on one operand only). It changes the corresponding bit of the operand to opposite bit,i.e., 0 to 1 and 1 to 0. It is denoted by ~.

35=00100011 (In Binary)
 
Bitwise complement Operation of 35
~ 00100011 
  ________
  11011100  = 220 (In decimal)

Twist in bitwise complement operator in C Programming


Output of ~35 shown by compiler won't be 220, instead it shows -36. For any integer n, bitwise complement of n will be -(n+1). To understand this, you should understand the concept of 2's complement.

2's Complement


Two's complement is the operation on binary numbers which allows number to write it in different form. The 2's complement of number is equal to the complement of number plus 1. For example:

 Decimal              Binary                  2's complement

   0                           00000000             -(11111111+1) = -00000000 = -0(decimal)

   1                           00000001             -(11111110+1) = -11111111 = -256(decimal)

   12                        00001100             -(11110011+1) = -11110100 = -244(decimal)

   220                      11011100             -(00100011+1) = -00100100 = -36(decimal)

Note: Overflow is ignored while computing 2's complement.

If we consider the bitwise complement of 35, 220(in decimal) is converted into 2's complement which is -36. Thus, the output shown by computer will be -36 instead of 220.

How is bitwise complement of any number N=-(N+1)?


bitwise complement of N= ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)
 

#include<stdio.h>

int main()

{  

     printf("complement=%d\n",~35);  //-36

    printf("complement=%d\n",~-12); // 11

     getch();

    return 0;

} 

Shift Operator in C programming


There are two shift operators in C programming: Right shift operator and Left shift operator.

Right Shift Operator


Right shift operator moves the all bits towards the right by certain number of bits which can be specified. It is denoted by >>.

212 = 11010100 (In binary)

212>>2 = 00110101 (In binary) [Right shift by two bits]

212>>7 = 00000001 (In binary)

212>>8 = 00000000

212>>0 = 11010100 (No Shift)

Left Shift Operator


Left shift operator moves the all bits towards the left by certain number of bits which can be specified. It is denoted by <<.

212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)
 

#include <stdio.h>

int main()

{

    int num=212,i;

    for (i=0;i<=2;++i)

        printf("Right shift by %d: %d\n",i,num>>i);

    

     printf("\n");

 

    for (i=0;i<=2;++i)

        printf("Left shift by %d: %d\n",i,num<<i);   

   

     return 0;

}
Output:
 
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
 
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848

Interesting thing to note in Left and Right Shift


For any positive number, right shift is equal to integer division of that number by (shift bit plus one) and for any integer left shift is equal to the multiplication of that number by (shift bit plus one).

5.      Other Special Operators

 

(a)    sizeof – operator:

The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.

Syntax:

sizeof unary-expression 
sizeof ( type-name )

The operand is either an identifier that is a unary-expression, or a type-cast expression (that is, a type specifier enclosed in parentheses). The unary-expression cannot represent a bit-field object, an incomplete type, or a function designator. The result is an unsigned integral constant. The standard header STDDEF.H defines this type as size_t.

When you apply the sizeof operator to an array identifier, the result is the size of the entire array rather than the size of the pointer represented by the array identifier.

When you apply the sizeof operator to a structure or union type name, or to an identifier of structure or union type, the result is the number of bytes in the structure or union, including internal and trailing padding. This size may include internal and trailing padding used to align the members of the structure or union on memory boundaries. Thus, the result may not correspond to the size calculated by adding up the storage requirements of the individual members.

If an unsized array is the last element of a structure, the sizeof operator returns the size of the structure without the array.

buffer = calloc(100, sizeof (int) );

This example uses the sizeof operator to pass the size of an int, which varies among machines, as an argument to a run-time function named calloc. The value returned by the function is stored in buffer.

     static char *strings[] ={
          "this is string one",
          "this is string two",
          "this is string three",
         };
     const int string_no = ( sizeof strings ) / ( sizeof strings[0] ); 
In this example, strings is an array of pointers to char. The number of pointers is the number of elements in the array, but is not specified. It is easy to determine the number of pointers by using the sizeof operator to calculate the number of elements in the array. The const integer value string_no is initialized to this number. Because it is a const value, string_no cannot be modified.

 

No comments:

Post a Comment