Showing posts with label operators and expressions. Show all posts
Showing posts with label operators and expressions. Show all posts

Wednesday, March 4, 2009

C#- Ch 3: Operators and Expressions

3. Operators and Expressions

An operator indicates the type of operation to be performed on operands in a given expression. There are 8 categories of operators in C#. These are:

1. Arithmetic operators (+, -, *, /, % )
2. Relational operators ( >, >=, <, <=, ==, != )
3. Logical operators (&&, ||, !, ~, &, | , ^ )
4. Assignment operators ( =, +=, -=, *=, /=, %= )
5. Increment and decrement operators ( ++, -- )
6. Conditional operator ( ? : )
7. Bitwise operators ( &, |, ~, ^ )
8. Shift operator ( <<, >> )
9. is operator
10. sizeof operator

Arithmetic Operators:

Modulo operator (%):

The “modulo” operator (%) is a binary operator. That is, it requires two operands. This operator gives remainder after the first operator is divided by the second. In C#, the modulo operator can be used with integer as well as real operands.

Case 1: Both operands are integers
If a and b are declared as integer variables, then
a % b = a – (a/b) * b
1) The sign of the first operand decides the sign of the result. If the first operand is positive, the result is positive. If the first operand is negative, the result is negative.
2) This operator can be used to check if a number is even or odd.
 If n % 2 is 0, then n is even, else n is odd.
3) This operator can be used to check whether a number a is divisible by another number b.
 If a % b is 0, then a is divisible by b, else a is not divisible by b.

Case 2: Both operands are real
If a and b are declared as real variables, then
a % b = a – n * b
where, n is the largest possible integer that is less than or equal to a/b.

The following example illustrates the use of modulo operator.

//Program: Ex-Modulo.cs
//Author: Mukesh N Tekwani

// This program illustrates the use of the modulo operator. In C#, modulo
// operator can be used with integer as well as real numbers.

using System;

namespace Ex_Modulo
{
class Modulo
{
static void Main()
{
int a, b, r;
float x, y, z;

// modulo division for both integers positive
a = 14;
b = 3;
r = a % b;
Console.WriteLine("a = {0}, b = {1}, r = {2}", a, b, r);

// modulo division for 1st operand -ve & 2nd operand +ve int
a = -14;
b = 3;
r = a % b;
Console.WriteLine("a = {0}, b = {1}, r = {2}", a, b, r);

// modulo division for 1st operand +ve and 2nd operand -ve int
a = 14;
b = -3;
r = a % b;
Console.WriteLine("a = {0}, b = {1}, r = {2}", a, b, r);

// modulo division for both operands positive floats
x = 100.5F;
y = 22.4F;
z = x % y;
Console.WriteLine("x = {0}, y = {1}, z = {2}", x, y, z);

Console.ReadLine();
}
}
}

Relational Operators:

C# supports six relational operators. These operators are used to compare two quantities. The result of comparison is either true or false.

Relational Operators
Relational Operator Meaning
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Is equal to
!= Is not equal to


Logical Operators:

C# supports 6 logical operators. These are:

Logical Operators
Logical Operator Meaning
&& Logical AND (all conditions must be true)
|| Logical OR (at least one condition must be true)
! Logical NOT
& Bitwise logical AND
| Bitwise logical OR
^ Bitwise logical exclusion

The logical operators && and || are used when we want to combine two or more conditions.
E.g., if we want to carry out an action only if both conditions are true, we will use the && (AND) operator as follows:
C1 && C2
If we want to carry out an action if at least one condition is true, we will use the || (OR) operator as follows:
C1 || C2

e.g., (1) if ( a > b && b > c)
max = a;

(2) if (a < 40 || B < 40)
result = ‘F’;



Truth table for AND ( && ) operator:

Condition C1 Condition C2 Result of C1 && C2
False False False
True False False
False True False
True True True

Truth table for OR ( || ) operator:

Condition C1 Condition C2 Result of C1 || C2
False False False
True False True
False True True
True True True


Increment and Decrement Operators:

The increment operator is ++ and decrement operator is --.
• Both these are unary operators.
• The increment operator adds 1 to the operand while the – operator subtracts 1 from the operand.
• These operators are very useful, especially in writing loops such as the for loop.
• If ++ is applied on a variable x, then ++x is equivalent to x = x + 1
• If -- is applied on a variable x, then --x is equivalent to x = x – 1
• If ++ or -- is used before an operand, it is called pre-increment or pre-decrement operator.
• If ++ or -- is used after an operand, it is called post-increment or post-decrement operator.

Example 1:

If x = 7, then y = ++x implies that y becomes 8. (First increase m and then use its value).

Example 2:

If x = 5, then z = x++ implies that z is first given the original value of x i.e. 5, and then x is increased by 1. (First use the existing value and then increase).



Conditional Operator / Ternary Operator:

The conditional operator in C# is ? :. It is used to construct a condition. E.g., consider the following if statement:
if ( a > b)
max = a;
else
max = b;
This can be written in a more concise way using the conditional operator as follows:

max = ( a > b) ? a : b;


Bitwise Operators:
There are 6 operators in C# that can be used for bit manipulation. These operators are :

Bitwise Operators
Bitwise Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ (tilde character) One’s complement
<< Left shift
>> Right shift

Bitwise AND operator (&) :

Use of & operator:
(1) This operator is used to check whether a particular bit in an integer is high or low. Consider the number 187. We want to check if the bit no. 5 is high or low. Bit 5 has a weight of 32 (since 25 = 32). Hence we use the & operator with these two numbers : 187 (the give no.) and 32.

Bit position -> 7 6 5 4 3 2 1 0
(187)10 = 1 0 1 1 1 0 1 1
(32)10 = 0 0 1 0 0 0 0 0
& 0 0 1 0 0 0 0 0
The resultant binary number in the last row is 0010 0000. This is the equivalent of 32. Thus, the only bit that remains in the result is bit at position 5.
The following program shows how we can test whether a particular bit is set in a number. The number to be tested is stored in x. We set y as 32 since we want to test the 5th bit of x. We know that 25 = 32.
//Program: BitAndOp.cs
//Author: Mukesh N Tekwani

// This program illustrates the use of the bitwise AND (&) operator.

using System;

namespace BitAndOp
{
class bitandop
{
static void Main()
{
int x, y, res;

//Check whether bit 5 is set in number 187
x = 187;
y = 32; // we have taken y as 32 since 2 raised to 5 is 32

res = x & y;

if (res > 0)
Console.WriteLine("Bit 5 is set in {0}", x);
else
Console.WriteLine("Bit 5 is not set in {0}", x);

//Now we check for bit 5 in another number, say 86
x = 86;

res = x & y;

if (res > 0)
Console.WriteLine("Bit 5 is set in {0}", x);
else
Console.WriteLine("Bit 5 is not set in {0}", x);

Console.ReadLine();
}
}
}

(2) Bitwise and (&) operator can also be used to clear bits in an integer value, i.e. set some bits to zero. E.g., suppose we want to clear the 5th bit of a number , i.e., we want to set the 5th bit to 0. We can do it as follows:
Bit position -> 7 6 5 4 3 2 1 0
(187)10 = 1 0 1 1 1 0 1 1
(223)10 = 1 1 0 1 1 1 1 1
& 1 0 0 1 1 0 1 1
Thus, the 5th bit is set to 0 in the result.
So the AND operator (&) is used to set a bit to 0 and leave all other bits unchanged.


Bitwise OR operator ( | ) :
The bitwise OR operator is used to set some bits in a number to 1.
E.g., suppose x = 187 and we want to set bit in position 2 to 1. The process is shown in this diagram:

Bit position -> 7 6 5 4 3 2 1 0
(187)10 = 1 0 1 1 1 0 1 1
(4)10 = 0 0 0 0 0 1 0 0
OR (| ) 1 0 1 1 1 1 1 1

The following program illustrates how we can mask (hide) a bit in a number:

//Program: BitOrOp.cs
//Author: Mukesh N Tekwani

// This program illustrates the use of the bitwise OR ( | ) operator for
// masking a bit

using System;

namespace BitOrOp
{
class bitorop
{
static void Main()
{
int x, mask, res;

//Check whether bit 5 is set in number 187
x = 187;
mask = 4; // we have taken mask as 4 since 2nd bit is to be masked and
// 2 raised to 2 is 4

res = x | mask;

Console.WriteLine("res = {0}", res);

Console.ReadLine();
}
}
}

So the OR operator ( | ) is used to set a bit to 1 and leave all other bits unchanged.

Bitwise XOR operator ( ^ ) :
The bitwise XOR operator (^) is used to toggle a bit. Toggling means that if the bit is 1, it is set to 0, and if the bit is 0, it is set to 1.

x = x ^ mask;
Bits that are set to 1 in the mask will be toggled in x. Bits that are set to 0 in the mask will be unchanged in x.

NOT operator ( ~ ) :
The ~ operator performs a bitwise complement operation on its operand. Each bit is reversed. That is, a high bit (1) becomes low (0) and vice-versa.
This is a unary operator.
When this operator is applied on a positive number, the result may be a negative number.

Left shift operator ( << ):

The left shift operator shifts the bits of a number to the left by a specified number of positions.
E.g., consider the number 8 whose binary equivalent is 0000 1000. This is to be shifted by 1 bit to the left.

Bit position -> 7 6 5 4 3 2 1 0
(8)10 =
0
0 0 0 1 0 0 0
8 << 1 0 0 0 1 0 0 0 0




The new number obtained after left shift by one bit is 16. This is the double of the original number. Thus the left shift operator can be used to multiply by 2 if bits are shifted by one.

This operator may be used on the int, uint, long, and ulong data types.

Right shift operator ( >> ):

The right shift operator shifts the bits of a number to the right by a specified number of positions.
E.g., consider the number 16 whose binary equivalent is 0001 0000. This is to be shifted by 1 bit to the right.

Bit position -> 7 6 5 4 3 2 1 0
(8)10 = 0
0 0 0 1 0 0 0

8 >> 1 0 0 0 0 0 1 0 0


Thus, the new number obtained is 4, which is half of the original number. Thus, the right shift operator can be used to half a given number. This operator may be used on the int, uint, long, and ulong data types.
The is operator :

The is operator checks a variable to see if it's a given type. If so, it returns true. Otherwise, it returns false. Here's an example.

using System;

namespace IsOp
{
class isop
{
static void Main()
{
int x = 0;

bool isTest = x is int;

if (isTest == true)
Console.WriteLine("x is an integer");
else
Console.WriteLine("x is a not an integer");

Console.ReadLine();
}
}
}


The sizeof operator:
The sizeof() operator is used to obtain the size in bytes for a value type.
Syntax: sizeof (type)
where, type is the value type for which the size is obtained.
• The sizeof operator can be applied only to value types, not reference types.
• The sizeof operator can only be used in the unsafe mode.
• The sizeof operator cannot be overloaded.

// Example to illustrate use of sizeof operator
using System;

namespace SizeOfOp
{
class sizeofop
{
static void Main()
{
Console.WriteLine("The size of byte is {0}", sizeof(byte));
Console.WriteLine("The size of short is {0}", sizeof(short));
Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of long is {0}", sizeof(long));

Console.ReadLine();
}
}
}
IMPORTANT QUESTIONS

1. What are the different categories of operators in C# ?
2. With the help of a suitable example, explain the “modulo” operator. Can this operator be used with real operands? Explain.
3. What are relational operators in C#? If relational operators are used in an expression, what values can the expression have?
4. Explain the use of the increment and decrement operators.
5. With reference to Boolean operators, explain the term “short-circuiting”.
6. Explain the bitwise operators in C#.
7. Explain the left shift and right shift operators. What is the use of these two operators?
8. What is meant by masking of bits? How is it achieved through bitwise operators in C#?
9. Explain the use of the left shift and the right shift operators with appropriate examples.
10. Illustrate the use of the is operator.
11. What is the use of the sizeof operator? Give suitable example.

PROGRAMMING EXERCISES

1. What is the output of the following program?

using System;

namespace test1
{
class test1
{
static void Main()
{
byte x = 10;
byte y = 20;

long result = x & y;

Console.WriteLine("{0} AND {1} Result :{2}", x, y, result);

x = 10;

y = 10;

result = x & y;

Console.WriteLine("{0} AND {1} Result : {2}", x, y, result);
Console.ReadLine();
}
}
}

2. In the above example, replace the AND operator (&) with the OR operator (|). What is the output?
3. What is the output of the following program?

using System;

namespace test2
{
class test2
{
static void Main()
{
int a = 1;
int b = 0;
int result;

result = (a == b) ? 1 : 0;

Console.WriteLine("Result is {0}", result);
Console.ReadLine();
}
}
}


4. State the output of the following program:

using System;
class Test
{
static void Main()
{
//33 = 1 0 0 0 0 1
Console.WriteLine(33 >> 3);

//15 = 1 1 1 1
Console.WriteLine(15 << 2);
Console.Read();
}
}


5. State the output of the following program:
using System;

namespace PrePostIncOps
{
class incops
{
static void Main()
{
int x = 0;
int y = 0;

Console.WriteLine(" x = {0}, y = {1}", x, y);
Console.WriteLine(" x = {0}, y = {1}", ++x, y++);
Console.WriteLine(" x = {0}, y = {1}", ++x, y++);
Console.WriteLine(" x = {0}, y = {1}", ++x, y++);

Console.ReadLine();
}
}
}