Skip to main content

Using Operators in C#

Using Operators in C#

Operators

Expressions in C# comprise of one or more operators that performs some operations on variables. An operation is an action performed on single or multiple values stored in variables in order to modify them or to generate a new value. Therefore, an operation takes place with the help of minimum one symbol and a value. The symbol is called an operator and it determines the type of action to be performed on the value. The value on which the operation is to be performed is called an operand. An operand might be a complex expression. For example, (X * Y) + (X – Y) is a complex expression, where the + operator is used to join two operands.

Types of Operators

Operators are used to simplify expressions. In C#, there is a predefined set of operators used to perform various types of operations. C# operators are classified into six categories based on the action they perform on values.
These six categories of operators are as follows:
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Conditional Operators
  • Increment and Decrement Operators
  • Assignment Operators

Arithmetic Operators – Types

Arithmetic operators are binary operators because they work with two operands, with the operator being placed in between the operands. These operators allow you to perform computations on numeric or string data.
Table lists the arithmetic operators along with their descriptions and an example of each type.
22)
Code demonstrates how to use the arithmetic operators.
Code :
int valueOne = 10; 
int valueTwo = 2; 
int add = valueOne + valueTwo; 
int sub = valueOne - valueTwo; 
int mult = ValueOne * valueTwo; 
int div = valueOne / valueTwo; 
int modu = valueOne % valueTwo; 
Console.WriteLine(“Addition ” + add ); 
Console.WriteLine(“Subtraction ” + sub); 
Console.WriteLine(“Multiplication ” + mult); 
Console.WriteLine(“Division ” + div); 
Console.WriteLine(“Remainder ” + modu);
Output:
Addition 12
Subtraction 8
Multiplication 20
Division 5
Remainder 0

Relational Operators

Relational operators make a comparison between two operands and return a boolean value, true or false.
Table lists the relational operators along with their descriptions and an example of each type.
3
Code demonstrates how to use the relational operators.
Code :
int leftVal = 50; 
int rightVal = 100; 
Console.WriteLine(“Equal: ” + (leftVal == rightVal)); 
Console.WriteLine(“Not Equal: ” + (leftVal != rightVal)); 
Console.WriteLine(“Greater: ” + (leftVal > rightVal)); 
Console.WriteLine(“Lesser: ” + (leftVal < rightVal)); 
Console.WriteLine(“Greater or Equal: ” + (leftVal >= rightVal)); 
Console.WriteLine(“Lesser or Equal: ” + (leftVal <= rightVal));
Output:
Equal: False
Not Equal: True
Greater: False
Lesser: True
Greater or Equal: False
Lesser or Equal: True

Logical Operators

Logical operators are binary operators that perform logical operations on two operands and return a boolean value. C# supports two types of logical operators, boolean and bitwise.

Boolean Logical Operators

The boolean logical operators perform boolean logical operations on both the operands. They return a boolean value based on the logical operator used.
Table lists the boolean logical operators along with their descriptions and an example of each type.

4Code explains the use of the boolean inclusive OR operator.
Code :
if ((quantity > 2000) | (price < 10.5)) 
 {
 Console.WriteLine (“You can buy more goods at a lower price”); 
 }
In the code, the boolean inclusive OR operator checks both the expressions. If either one of them evaluates to true, the complete expression returns true and the statement within the block is executed.
Code explains the use of the boolean AND operator.
Code :
if ((quantity == 2000) & (price == 10.5))
{
 Console.WriteLine (“The goods are correctly priced”); 
 }
In the code, the boolean AND operator checks both the expressions. If both the expressions evaluate to true, the complete expression returns true and the statement within the block is executed.
Code explains the use of the boolean exclusive OR operator.
Code :
if ((quantity == 2000) ^ (price == 10.5)) 
 {
 Console.WriteLine (“You have to compromise between quantity and price”);
 }
In the code, the boolean exclusive OR operator checks both the expressions. If only one of them evaluates to true, the complete expression returns true and the statement within the block is executed. If both of them are true, the expression returns false.

Bitwise Logical Operators

The bitwise logical operators perform logical operations on the corresponding individual bits of two operands. Table lists the bitwise logical operators along with their descriptions and an example of each type.
5
Code explains the working of the bitwise AND operator.
Code :
result = 56 & 28; //(56 = 00111000 and 28 = 00011100) 
Console.WriteLine(result);
In Code , the bitwise AND operator compares the corresponding bits of the two operands. It returns 1 if both the bits in that position are 1 or else returns 0. This comparison is performed on each of the individual bits and the results of these comparisons form an 8-bit binary number. This number is automatically converted to integer, which is displayed as the output. The resultant output for the code is “24”.
Figure displays the bitwise logical operators.
6
Code explains the working of the bitwise inclusive OR operator.
Code :
result = 56 | 28; 
Console.WriteLine(result);
The bitwise inclusive OR operator compares the corresponding bits of the two operands. It returns 1 if either of the bits in that position is 1, else it returns 0. This comparison is performed on each of the individual bits and the results of these comparisons form an 8-bit binary number. This number is automatically converted to integer, which is displayed as the output. The resultant output for the code is 60.
Code explains the working of the bitwise exclusive OR operator.
Code :
result = 56 ^ 28; 
Console.WriteLine(result);
The bitwise exclusive OR operator compares the corresponding bits of the two operands. It returns 1 if only 1 of the bits in that position is 1, else it returns 0. This comparison is performed on each of the individual bits and the results of these comparisons form an 8-bit binary number. This number is automatically converted to integer, which is displayed as the output. The resultant output for the code is “36”.

Conditional Operators

There are two types of conditional operators, conditional AND (&&) and conditional OR (||). Conditional operators are similar to the boolean logical operators but has the following differences.
The conditional AND operator evaluates the second expression only if the first expression returns true. This is because this operator returns true only if both expressions are true. Thus, if the first expression itself evaluates to false, the result of the second expression is immaterial.
The conditional OR operator evaluates the second expression only if the first expression returns false. This is because this operator returns true if either of the expressions is true. Thus, if the first expression itself evaluates to true, the result of the second expression is immaterial. Figure displays the conditional operators.
7
Code displays the use of the conditional AND (&&) operator.
Code :
int num = 0;
 if (num >= 1 && num <= 10) 
{
 Console.WriteLine(“The number exists between 1 and 10”);
 }
 else {
 Console.WriteLine(“The number does not exist between 1 and 10”); 
}
In the code, the conditional AND operator checks the first expression. The first expression returns false, Therefore, the operator does not check the second expression. The whole expression evaluates to false, the statement in the else block is executed.
Output:
The number does not exist between 1 and 10
Code displays the use of the conditional OR (||) operator.
Code :
int num = -5;
 if (num < 0 || num > 10)
 {
 Console.WriteLine(“The number does not exist between 1 and 10”); 
} 
else {
 Console.WriteLine(“The number exists between 1 and 10”); 
}
In the code, the conditional OR operator checks the first expression. The first expression returns true, Therefore, the operator does not check the second expression. The whole expression evaluates to true, the statement in the if block is executed.
Output:
The number does not exist between 1 and 10 .

Increment and Decrement Operators

Two of the most common calculations performed in programming are increasing and decreasing the value of the variable by 1. In C#, the increment operator (++) is used to increase the value by 1 while the decrement operator (–) is used to decrease the value by 1.
If the operator is placed before the operand, the expression is called pre-increment or pre-decrement. If the operator is placed after the operand, the expression is called post-increment or post-decrement.
Table depicts the use of increment and decrement operators assuming the value of the variable valueOne is 5.
8

Assignment Operators – Types

Assignment operators are used to assign the value of the right side operand to the operand on the left side using the equal to operator (=). The assignment operators are divided into two categories in C#. These are as follows:
Simple assignment operators: The simple assignment operator is =, which is used to assign a value or result of an expression to a variable.
Compound assignment operators: The compound assignment operators are formed by combining the simple assignment operator with the arithmetic operators.
Table shows the use of assignment operators assuming the value of the variable valueOne is 10.
9
Code demonstrates how to use assignment operators.
Code :
int valueOne = 5; 
int valueTwo = 10; 
Console.WriteLine(“Value1 =” + valueOne); 
valueOne += 4; 
Console.WriteLine(“Value1 += 4= “ + valueOne); 
valueOne -= 8; 
Console.WriteLine(“Value1 -= 8= “ + valueOne); 
valueOne *= 7; 
Console.WriteLine(“Value1 *= 7= “ + valueOne); 
valueOne /= 2; 
Console.WriteLine(“Value1 /= 2= “ + valueOne); 
Console.WriteLine(“Value1 == Value2: {0}”, 
(valueOne == valueTwo));
Output:
Value1 =5
Value1 += 4= 9
Value1 -= 8= 1
Value1 *= 7= 7
Value1 /= 2= 3
Value1 == Value2: False
Note – The assignment operator is different from the equality operator (==). This is because the equality operator returns true if the values of both the operands are equal, else returns false.

Precedence and Associativity

Operators in C# have certain associated priority levels. The C# compiler executes operators in the sequence defined by the priority level of the operators. For example, the multiplication operator (*) has higher priority over the addition (+) operator. Thus, if an expression involves both the operators, the multiplication operation is carried out before the addition operation. In addition, the execution of the expression (associativity) is either from left to right or vice-versa depending upon the operators used.
Table lists the precedence of the operators, from the highest to the lowest precedence, their description and their associativity.
10
Code demonstrates how to use logical operators.
Code :
int valueOne = 10; 
Console.WriteLine((4 * 5 - 3 ) / 6 + 7 - 8 % 5); 
Console.WriteLine((32 < 4) || (8 == 8)); 
Console.WriteLine(((valueOne *= 6) > (valueOne += 5)) && ((valueOne /= 2) != (valueOne -= 5)));
In the code, the variable valueOne is initialized to the value 10. The next three statements display the results of the expressions. The expression given in the parentheses is solved first.
Output:
6
True
False

Shift Operators

The shift operators allow the programmer to perform shifting operations. The two shifting operators are the left shift (<<) and the right shift (>>) operators. The left shift operator allows shifting the bit positions towards the left side where the last bit is truncated and zero is added on the right. The right shift operator allows shifting the bit positions towards the right side and the zero is added on the left.
Code demonstrates the use of shift operators.
Code :
using System; 
class ShiftOperator
 {
 static void Main(string[] args) 
{
 uint num = 100; // 01100100 = 100 
uint result = num << 1; // 11001000 = 200 
Console.WriteLine(“Value before left shift : “ + num); 
Console.WriteLine(“Value after left shift “ + result); 
num = 80; // 10100000 =
 result = num >> 1; // 01010000 = 40 
Console.WriteLine(“\nValue before right shift : “ + num);
 Console.WriteLine(“Value after right shift : “ + result); 
 }
}
The output of Code is shown in figure.
11
In Code, the Main() method of the class ShiftOperator performs the shifting operations.
The Main() method initializes the variable num to 100. After shifting towards left, the value of num is doubled. Now, the variable num is initialized to 80. After shifting towards right, the value of num is halved.

String Concatenation Operator

The arithmetic operator (+) allows the programmer to add numerical values. However, if one or more operands are characters or binary strings, columns, or a combination of strings and column names into one expression, then the string concatenation operator concatenates them. In other words, the arithmetic operator (+) is overloaded for string values.
Code demonstrates the use of string concatenation operator.
Code :
using System;
 class Concatenation
 {
 static void Main(string[] args)
 {
 int num = 6;
 string msg = “”; 
if (num < 0) 
{
 msg = “The number “ + num + “ is negative”;
 }
 else if ((num % 2) == 0) 
{
 msg = “The number “ + num + “ is even”; 
}
 else
 {
 msg = “The number “ + num + “ is odd”; 
}
 if(msg != “”) 
Console.WriteLine(msg); 
 }
}
In Code, the Main() method of the class Concatenation uses the construct to check whether a number is even, odd or negative. Depending upon the condition, the code displays the output by using the string concatenation operator (+) to concatenate the strings with numbers.
The output of Code shows the use of string concatenation operator, as seen in figure.
12

Ternary or Conditional Operator

The ?: is referred to as the conditional operator. It is generally used to replace the if-else constructs. Since it requires three operands, it is also referred to as the ternary operator. The first expression returns a bool value, and depending on the value returned by the first expression, the second or third expression is evaluated. If the first expression returns a true value, the second expression is evaluated, whereas if the first expression returns a false value, the third expression is evaluated.
Syntax:
<Expression 1> ? <Expression 2>: <Expression 3>;
where,
Expression 1: Is a bool expression.
Expression 2: Is evaluated if expression 1 returns a true value.
Expression 3: Is evaluated if expression 1 returns a false value.
Code demonstrates the use of the ternary operator.
Code :
using System;
 class LargestNumber
 {
 public static void Main()
 {
 int numOne = 5;
 int numTwo = 25;
 int numThree = 15;
 int result = 0;
 if (numOne > numTwo)
 {
 result = (numOne > numThree) ? result = numOne : result = numThree;
 } 
else
 {
 result = (numTwo > numThree) ? result = numTwo : result = numThree; 
}
 if(result != 0) 
Console.WriteLine(“{0} is the largest number”, result);
 }
 }
In Code, the Main() method of the class LargestNumber checks and displays the largest of three numbers, numOne, numTwo, and numThree. This largest number is stored in the variable result. If numOne is greater than numTwo, then the ternary operator within the if loop is executed.
The ternary operator (?:) checks whether numOne is greater than numThree. If this condition is true, then the second expression of the ternary operator is executed, which will assign numOne to result. Otherwise, if numOne is not greater than numThree, then the third expression of the ternary operator is executed, which will assign numThree to result.
Similar operation is done for comparison of numOne and numTwo and the result variable will contain the larger value out of these two.
Figure shows the output of the example using ternary operator.
13

Comments

Popular posts from this blog

Introduction to PHP- Hypertext Preprocessor

PHP - Hypertext Preprocessor PHP is widely used a scripting language to develop various types of applications. This is mostly used to develop dynamic web applications. But it can also be used as batch processing scripts that can be executed from the cron job. In this section, we are giving many tutorials and example code of PHP programming language. PHP - Start with <html> <body>     <?php ?> </body> </html>

"Hello World" Program in PHP

Every language has it... the basic "Hello, World!" script. It is a simple script that only displays the words "Hello, World!". PHP - Words Display Script <html> <body> <?php Print "Hello World!"; ?>   <?php Echo "Hello World!"; ?> </body> </html> OUTPUT : Hello World