SlideShare a Scribd company logo
1 of 11
Download to read offline
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                                        Email: mukeshtekwani@hotmail.com
//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.



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




 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                                           Email: mukeshtekwani@hotmail.com
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).




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

 Operators and Expressions                                                                    Page 5 of 11
Generated by Foxit PDF Creator © Foxit Software
                                                   http://www.foxitsoftware.com For evaluation only.




Prof. Mukesh N. Tekwani                                           Email: mukeshtekwani@hotmail.com
//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 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 ->    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;



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

                                                                                       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           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();
          }
     }
}

 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}      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?

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("      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();
         }
    }
}

Operators and Expressions                                                                 Page 11 of 11

More Related Content

What's hot

Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++Praveen M Jigajinni
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++Online
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming Kamal Acharya
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++Neeru Mittal
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++sanya6900
 
Variables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailVariables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailgourav kottawar
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operatorsAnuja Lad
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programmingprogramming9
 
Logical and Conditional Operator In C language
Logical and Conditional Operator In C languageLogical and Conditional Operator In C language
Logical and Conditional Operator In C languageAbdul Rehman
 
02 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_0202 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_02Pooja Gupta
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++Neeru Mittal
 
Conditional operators
Conditional operatorsConditional operators
Conditional operatorsBU
 
Operators in c language
Operators in c languageOperators in c language
Operators in c languageAmit Singh
 

What's hot (20)

Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Variables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailVariables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detail
 
Basics of c++
Basics of c++ Basics of c++
Basics of c++
 
C operator and expression
C operator and expressionC operator and expression
C operator and expression
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operators
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Logical and Conditional Operator In C language
Logical and Conditional Operator In C languageLogical and Conditional Operator In C language
Logical and Conditional Operator In C language
 
02 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_0202 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_02
 
Theory3
Theory3Theory3
Theory3
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Conditional operators
Conditional operatorsConditional operators
Conditional operators
 
Operators in c language
Operators in c languageOperators in c language
Operators in c language
 
07 ruby operators
07 ruby operators07 ruby operators
07 ruby operators
 

Viewers also liked (20)

C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
 
Pl sql-ch1
Pl sql-ch1Pl sql-ch1
Pl sql-ch1
 
Css
CssCss
Css
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Sql ch 4
Sql ch 4Sql ch 4
Sql ch 4
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
 
Pl sql-ch3
Pl sql-ch3Pl sql-ch3
Pl sql-ch3
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Pl sql-ch2
Pl sql-ch2Pl sql-ch2
Pl sql-ch2
 
Sql ch 9 - data integrity
Sql ch 9 - data integritySql ch 9 - data integrity
Sql ch 9 - data integrity
 
Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
OSI Model
OSI ModelOSI Model
OSI Model
 
Java misc1
Java misc1Java misc1
Java misc1
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQ
 
Chap 2 network models
Chap 2 network modelsChap 2 network models
Chap 2 network models
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
 
Ajax chap 4
Ajax chap 4Ajax chap 4
Ajax chap 4
 

Similar to C sharp chap3

Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptxrinkugupta37
 
Programming presentation
Programming presentationProgramming presentation
Programming presentationFiaz Khokhar
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tourSwarup Boro
 
Python tutorials for beginners | IQ Online Training
Python tutorials for beginners | IQ Online TrainingPython tutorials for beginners | IQ Online Training
Python tutorials for beginners | IQ Online TrainingRahul Tandale
 
Computer programming chapter ( 4 )
Computer programming chapter ( 4 ) Computer programming chapter ( 4 )
Computer programming chapter ( 4 ) Ibrahim Elewah
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)It Academy
 
Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Deepak Singh
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
Operators expressions-and-statements
Operators expressions-and-statementsOperators expressions-and-statements
Operators expressions-and-statementsCtOlaf
 
Operators and Expressions in C#
Operators and Expressions in C#Operators and Expressions in C#
Operators and Expressions in C#Simplilearn
 
Operators-computer programming and utilzation
Operators-computer programming and utilzationOperators-computer programming and utilzation
Operators-computer programming and utilzationKaushal Patel
 

Similar to C sharp chap3 (20)

6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
Report on c
Report on cReport on c
Report on c
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Programming C Part 02
Programming C Part 02Programming C Part 02
Programming C Part 02
 
Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptx
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
 
cprogrammingoperator.ppt
cprogrammingoperator.pptcprogrammingoperator.ppt
cprogrammingoperator.ppt
 
C program
C programC program
C program
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Python tutorials for beginners | IQ Online Training
Python tutorials for beginners | IQ Online TrainingPython tutorials for beginners | IQ Online Training
Python tutorials for beginners | IQ Online Training
 
Computer programming chapter ( 4 )
Computer programming chapter ( 4 ) Computer programming chapter ( 4 )
Computer programming chapter ( 4 )
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Chapter 5 - Operators in C++
Chapter 5 - Operators in C++
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Operators expressions-and-statements
Operators expressions-and-statementsOperators expressions-and-statements
Operators expressions-and-statements
 
Operators
OperatorsOperators
Operators
 
Operators and it's type
Operators and it's type Operators and it's type
Operators and it's type
 
Operators and Expressions in C#
Operators and Expressions in C#Operators and Expressions in C#
Operators and Expressions in C#
 
Operators-computer programming and utilzation
Operators-computer programming and utilzationOperators-computer programming and utilzation
Operators-computer programming and utilzation
 

More from Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

More from Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

C sharp chap3

  • 1. 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
  • 2. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com //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. Page 2 of 11 Operators and Expressions
  • 3. 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 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’; Operators and Expressions Page 3 of 11
  • 4. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com 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). Page 4 of 11 Operators and Expressions
  • 5. 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 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. Operators and Expressions Page 5 of 11
  • 6. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com //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 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
  • 7. 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 -> 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; Operators and Expressions Page 7 of 11
  • 8. 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 -> 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 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 -> 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 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
  • 9. 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 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(); } } } Operators and Expressions Page 9 of 11
  • 10. 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} 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? Page 10 of 11 Operators and Expressions
  • 11. 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(" 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(); } } } Operators and Expressions Page 11 of 11