737 views

Uploaded by mukeshnt

Lecture notes on programming language c#, (c sharp). Notes developed by Prof Mukesh N Tekwani, Mumbai. These notes are as per the latest syllabus of University of Mumbai , for B.Sc (IT) - Sem VI

save

- Output
- C# - Chap 2
- 13.cpp
- Practical Assignment No 1 to 9
- C# - Chap 4
- 2015Sp-CS61C-L03-kavs-C2
- Advanced Pointer
- Lab05
- C# Balaguruswamy Solved Programs
- C# - Chap 1
- 53233495-c-PROGRAM-1
- C#
- Bank Management
- Mistral
- Bitwise Operators
- Structures, Unions & Bitwise.docx
- System Information
- Var Array
- Ibm
- C Interview Questions and Answers
- Test Your C-Skills[Yashwant Kanitkar]
- CNLAB
- Computer Networks Lab Manual
- ch1-1
- Warp Verilog Reference
- 09. C Structures, Unions, Bit Manipulation and Enumerations
- 19 Eltp Campus Ps & Pd Using c Part-1
- Data Types
- Object-Oriented Programming in ANSI C (csitebooks.blogspot.in)
- CEB
- IGCSE Physics - Moments and Centre of Mass
- Jee Main 2014 Solution Physics (2)
- Maths-329490-2019-syllabus
- FYBSc Computer Science 2015-16 Syllabus
- Maths-414957-2020-2022-syllabus
- Maths-415060-2020-2022-syllabus
- Maths 423525 List of Formulae and Statistical Tables
- M. Sc Computer Science Sem I & II Syllabus - University of Mumbai
- Physics-164526-2016-2018-syllabus
- Physics-329533-2019-2021-syllabus
- Maths-203041-2017-2018-syllabus
- Programming In Ansi C_E. Balagurusamy.pdf
- Maths-329554-2019-syllabus
- Haptic Energy Conversion
- 72552568-IGCSE-Physics-Worksheet-Measurement.pdf
- Question Paper (Set - II)
- DSP Journal
- 09.Solutions to Concepts
- 04.Solutions to Concepts
- 03.Solutions to Concepts
- 10.Solutions to Concepts
- Question Paper (Set - I)
- Revised FY BMS Syll 1
- 11.Solutions to Concepts
- 4.113 f.y.b.com. a & f Sem i & II
- Maharashtra Rules for RTI
- Maths Formulas
- JEE_Main_bulletin_2014_19_12_13 (2)
- 05.Solutions to Concepts
- Ch - 5 Depreciation Accounting ( Cpt Oswal) Checked by Sdm

You are on page 1of 11

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

x = x ^ mask;

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

This bit is added

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

- OutputUploaded byTanuj Khandelwal
- C# - Chap 2Uploaded bymukeshnt
- 13.cppUploaded byAnudeep Reddy
- Practical Assignment No 1 to 9Uploaded byNishant Sonavane
- C# - Chap 4Uploaded bymukeshnt
- 2015Sp-CS61C-L03-kavs-C2Uploaded byMaiDung
- Advanced PointerUploaded byGanesh Arora
- Lab05Uploaded byvinayakagarwal
- C# Balaguruswamy Solved ProgramsUploaded byanushreesanikop
- C# - Chap 1Uploaded bymukeshnt
- 53233495-c-PROGRAM-1Uploaded byGurumurthy Kalyanasundaram
- C#Uploaded bySoumya Jyoti Bhattacharya
- Bank ManagementUploaded byDharam Shree
- MistralUploaded byPragadesh Kumar
- Bitwise OperatorsUploaded byhydownstar
- Structures, Unions & Bitwise.docxUploaded byKetan Fakeer
- System InformationUploaded bySala Soto
- Var ArrayUploaded byPrasad Mullappilly
- IbmUploaded bychirusagar
- C Interview Questions and AnswersUploaded byvengalmca
- Test Your C-Skills[Yashwant Kanitkar]Uploaded byKamlesh Kumar
- CNLABUploaded byPravin Pathak
- Computer Networks Lab ManualUploaded byBernice Samina
- ch1-1Uploaded bychunnan_hung
- Warp Verilog ReferenceUploaded byClaudiu Ionut
- 09. C Structures, Unions, Bit Manipulation and EnumerationsUploaded byAditya Kharisma Wicaksana
- 19 Eltp Campus Ps & Pd Using c Part-1Uploaded byAnonymous go4U5aCC
- Data TypesUploaded byMohd Abdul Rafay
- Object-Oriented Programming in ANSI C (csitebooks.blogspot.in)Uploaded byMohd Khushhal
- CEBUploaded bybishnu_barik

- IGCSE Physics - Moments and Centre of MassUploaded bymukeshnt
- Jee Main 2014 Solution Physics (2)Uploaded bymukeshnt
- Maths-329490-2019-syllabusUploaded bymukeshnt
- FYBSc Computer Science 2015-16 SyllabusUploaded bymukeshnt
- Maths-414957-2020-2022-syllabusUploaded bymukeshnt
- Maths-415060-2020-2022-syllabusUploaded bymukeshnt
- Maths 423525 List of Formulae and Statistical TablesUploaded bymukeshnt
- M. Sc Computer Science Sem I & II Syllabus - University of MumbaiUploaded bymukeshnt
- Physics-164526-2016-2018-syllabusUploaded bymukeshnt
- Physics-329533-2019-2021-syllabusUploaded bymukeshnt
- Maths-203041-2017-2018-syllabusUploaded bymukeshnt
- Programming In Ansi C_E. Balagurusamy.pdfUploaded bymukeshnt
- Maths-329554-2019-syllabusUploaded bymukeshnt
- Haptic Energy ConversionUploaded bymukeshnt
- 72552568-IGCSE-Physics-Worksheet-Measurement.pdfUploaded bymukeshnt
- Question Paper (Set - II)Uploaded bymukeshnt
- DSP JournalUploaded bymukeshnt
- 09.Solutions to ConceptsUploaded bymukeshnt
- 04.Solutions to ConceptsUploaded bymukeshnt
- 03.Solutions to ConceptsUploaded bymukeshnt
- 10.Solutions to ConceptsUploaded bymukeshnt
- Question Paper (Set - I)Uploaded bymukeshnt
- Revised FY BMS Syll 1Uploaded bymukeshnt
- 11.Solutions to ConceptsUploaded bymukeshnt
- 4.113 f.y.b.com. a & f Sem i & IIUploaded bymukeshnt
- Maharashtra Rules for RTIUploaded bymukeshnt
- Maths FormulasUploaded bymukeshnt
- JEE_Main_bulletin_2014_19_12_13 (2)Uploaded bymukeshnt
- 05.Solutions to ConceptsUploaded bymukeshnt
- Ch - 5 Depreciation Accounting ( Cpt Oswal) Checked by SdmUploaded bymukeshnt