You are on page 1of 11

# Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

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.

Page 1 of 11

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

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

Email: mukeshtekwani@hotmail.com

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

Page 2 of 11

Operators and Expressions

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

3. Programming in C# 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 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

Logical Operator && || ! & | ^

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’;

Operators and Expressions

Page 3 of 11

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

Prof. Mukesh N. Tekwani Truth table for AND ( && ) operator: Condition C1 False True False True Truth table for OR ( || ) operator: Condition C1 False True False True Condition C2 False False True True Condition C2 False False True True

Email: mukeshtekwani@hotmail.com

Result of C1 && C2 False False False True

Result of C1 || C2 False 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).

Page 4 of 11

Operators and Expressions

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

3. Programming in C#

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 & | ^ ~ (tilde character) << >> 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. Operators and Expressions Page 5 of 11 Meaning Bitwise AND Bitwise OR Bitwise XOR One’s complement Left shift Right shift

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

Prof. Mukesh N. Tekwani
//Program: BitAndOp.cs //Author: Mukesh N Tekwani

Email: mukeshtekwani@hotmail.com

// 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 5 th 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 th Thus, the 5 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.

Page 6 of 11

Operators and Expressions

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

3. Programming in C# 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 -> (187)10 = (4)10 = OR (| ) 7 1 0 1 6 0 0 0 5 1 0 1 4 1 0 1 3 1 0 1 2 0 1 1 1 1 0 1 0 1 0 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.

Operators and Expressions

Page 7 of 11

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

Prof. Mukesh N. Tekwani

Email: mukeshtekwani@hotmail.com

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 -> (8)10 = 8 << 1 7 0 0 6 0 0 5 0 0 4 0 1 3 1 0 2 0 0 1 0 0 0 0 0

Bit lost after left shift (overflow bit)

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 -> (8)10 = 8 >> 1 7 0 0 6 0 0 5 0 0 4 0 0 3 1 0 2 0 1 1 0 0 0 0 0 Bit lost 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. Page 8 of 11 Operators and Expressions

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

3. Programming in C#

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 Console.WriteLine("The Console.WriteLine("The Console.WriteLine("The Console.ReadLine(); } } }

size size size size

of of of of

byte is {0}", sizeof(byte)); short is {0}", sizeof(short)); int is {0}", sizeof(int)); long is {0}", sizeof(long));

Operators and Expressions

Page 9 of 11

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

Prof. Mukesh N. Tekwani

Email: mukeshtekwani@hotmail.com

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} x = 10; y = 10; result = x & y; Console.WriteLine("{0} Console.ReadLine(); } } } AND {1} Result : {2}", x, y, result); AND {1} Result :{2}", x, y, result);

2. In the above example, replace the AND operator (&) with the OR operator (|). What is the output? Page 10 of 11 Operators and Expressions

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

3. Programming in C# 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(" Console.WriteLine(" Console.WriteLine(" Console.WriteLine(" Console.ReadLine(); } } } x x x x = = = = {0}, {0}, {0}, {0}, y y y y = = = = {1}", {1}", {1}", {1}", x, y); ++x, y++); ++x, y++); ++x, y++);

Operators and Expressions

Page 11 of 11