0% found this document useful (0 votes)
53 views

Mod 3

The document discusses operators in C# programming. It defines what operators are and categorizes them into different types, including arithmetic, assignment, comparison, logical, and type conversion operators. It explains operator precedence and provides examples of using various operators to perform mathematical operations, concatenate strings, and evaluate logical expressions in C#.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Mod 3

The document discusses operators in C# programming. It defines what operators are and categorizes them into different types, including arithmetic, assignment, comparison, logical, and type conversion operators. It explains operator precedence and provides examples of using various operators to perform mathematical operations, concatenate strings, and evaluate logical expressions in C#.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Divine Word College of San Jose

San Jose, Occidental Mindoro

Bachelor of Science in Information Technology

Module 3
Lesson 1

1. Title: Computer Programming 2

2. Scope: Operators and Expressions

3. Overview: In this module we will get acquainted with the operators in C# and the actions
they can perform when used with the different data types. In the beginning, we will explain which
operators have higher priority and we will analyze the different types of operators, according to
the number of the arguments they can take and the actions they perform.

4. Objectives:

After studying this module, you should:

• Explain the C# operators


• Examine the conversion of data types
• Explain when and why it is needed to be done and how to work with different data types.
At the end of, we will pay special attention to the expressions and how we should work
with them.

5. Discussion of the topic

Operators

Every programming language uses operators, through which we can perform different actions on
the data. Let’s take a look at the operators in C# and see what they are for and how they are used.

What Is an Operator?

After we have learned how to declare and set a variable in the previous module, we will discuss
how to perform various operations with them. For this purpose we will get familiar with
operators. Operators allow processing of primitive data types and objects. They take as an input
one or more operands and return some value as a result.
Operators in C# are special characters (such as "+", ".", "^", etc.) and they perform
transformations on one, two or three operands. Examples of operators in C# are the signs for
adding, subtracting, multiplication and division from math (+, -, *, /) and the operations they
perform on the integers and the real numbers.

Operators in C#

Operators in C# can be separated in several different categories: - Arithmetic operators – they are
used to perform simple mathematical operations.

• Assignment operators – allow assigning values to variables.


• Comparison operators – allow comparison of two literals and/or variables.
• Logical operators – operators that work with Boolean data types and Boolean
expressions.
• Binary operators – used to perform operations on the binary representation of numerical
data.
• Type conversion operators – allow conversion of data from one type to another. Operator
Categories

Below is a list of the operators, separated into categories:

Types of Operators by Number of Arguments

Operators can be separated into different types according to the number of arguments they could
take:
All binary operators in C# are left-associative, i.e. the expressions are calculated from left to
right, except for the assignment operators. All assignment operators and conditional operators?:
and ?? are right associative, i.e. the expressions are calculated from right to left. The unary
operators are not associative.
Some of the operators in C# perform different operations on the different data types. For
example the operator +. When it is used on numeric data types (int, long, float, etc.), the operator
performs mathematical addition. However, when we use it on strings, the operator concatenates
(joins together) the content of the two variables/literals and returns the new string.

Operators – Example

Here is an example of using operators:

int a = 7 + 9;
Console.WriteLine(a); // 16
string firstName = "John"; string lastName = "Doe";
// Do not forget the space between them
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // John Doe

The example shows how, as explained above, when the operator + is used on numbers it returns a
numerical value, and when it is used on strings it returns concatenated strings.

Operator Precedence in C#

Some operators have precedence (priority) over others. For example, in math multiplication has
precedence over addition. The operators with a higher precedence are calculated before those with
lower. The operator () is used to change the precedence and like in math, it is calculated first.

The following table illustrates the precedence of the operators in C#:


The operators located upper in the table have higher precedence than those below them,
and respectively they have an advantage in the calculation of an expression. To change the
precedence of an operator we can use brackets.

When we write expressions that are more complex or have many operators, it is recommended to
use brackets to avoid difficulties in reading and understanding the code. For example:

// Ambiguous
x + y / 100
// Unambiguous, recommended
x + (y / 100)

Arithmetical Operators

The arithmetical operators in C# +, -, * are the same like the ones in math. They perform
addition, subtraction and multiplication on numerical values and the result is also a numerical
value.

The division operator / has different effect on integer and real numbers. When we divide
an integer by an integer (like int, long and sbyte) the returned value is an integer (no
rounding, the fractional part is cut). Such division is called an integer division. Example of
integer division: 7 / 3 = 2.

Integer division by 0 is not allowed and causes a runtime exception DivideByZeroException. The
remainder of integer division of integers can be obtained by the operator %. For example, 7 % 3 =
1, and –10 % 2 = 0.

When dividing two real numbers or two numbers, one of which is real (e.g. float, double,
etc.), a real division is done (not integer), and the result is a real number with a whole and a
fractional part. For example: 5.0 / 2 = 2.5. In the division of real numbers it is allowed to divide
by 0.0 and respectively the result is +∞ (Infinity), -∞ (-Infinity) or NaN (invalid value).

The operator for increasing by one (increment) ++ adds one unit to the value of the variable,
respectively the operator -- (decrement) subtracts one unit from the value. When we use the
operators ++ and -- as a prefix (when we place them immediately before the variable), the new
value is calculated first and then the result is returned. When we use the same operators as post-
fix (meaning when we place them immediately after the variable) the original value of the operand
is returned first, then the addition or subtraction is performed.

Arithmetical Operators – Example


Here are some examples of arithmetic operators and their effect:

int squarePerimeter = 17;


double squareSide = squarePerimeter / 4.0;
double squareArea = squareSide * squareSide;
Console.WriteLine(squareSide); // 4.25
Console.WriteLine(squareArea); // 18.0625
int a = 5; int
b = 4; Console.WriteLine(a + b); // 9
Console.WriteLine(a + (b++)); // 9
Console.WriteLine(a + b); // 10
Console.WriteLine(a + (++b)); // 11
Console.WriteLine(a + b); // 11
Console.WriteLine(14 / a); // 2
Console.WriteLine(14 % a); // 4
int one = 1;
int zero = 0;
// Console.WriteLine(one / zero); // DivideByZeroException
double dMinusOne = -1.0;
double dZero = 0.0;
Console.WriteLine(dMinusOne / zero); // -Infinity
Console.WriteLine(one / dZero); // Infinity

Logical Operators

Logical (Boolean) operators take Boolean values and return a Boolean result (true or false).
The basic Boolean operators are "AND" (&&), "OR" (||), "exclusive OR" (^) and logical negation
(!).

The following table contains the logical operators in C# and the operations that they
perform:

The table and the following example show that the logical "AND" (&&) returns true only
when both variables contain truth. Logical "OR" (||) returns true when at least one of the operands
is true. The logical negation operator (!) changes the value of the argument. For example, if the
operand has a value true and a negation operator is applied, the new value will be false. The
negation operator is a unary operator and it is placed before the argument. Exclusive "OR" (^)
returns true if only one of the two operands has the value true. If the two operands have different
values, exclusive "OR" will return the result true, if they have the same values it will return false.

Logical Operators – Example

The following example illustrates the usage of the logical operators and their actions:

bool a = true;
bool b = false;
Console.WriteLine(a && b); // False
Console.WriteLine(a || b); // True
Console.WriteLine(!b); // True
Console.WriteLine(b || true); // True
Console.WriteLine((5 > 7) ^ (a == b)); // False

Laws of De Morgan Logical operations fall under the laws of De Morgan from the mathematical
logic:

!(a && b) == (!a || !b)


!(a || b) == (!a && !b)

The first law states that the negation of the conjunction (logical AND) of two propositions is equal
to the disjunction (logical OR) of their negations.

The second law states that the negation of the disjunction of both statements is equivalent to the
conjunction of their negations.

Operator for Concatenation of Strings

The operator + is used to join strings (string). It concatenates (joins) two or more strings and returns
the result as a new string. If at least one of the arguments in the expression is of type string, and
there are other operands of type different from string, they will be automatically converted to type
string, which allows successful string concatenation.

Operator for Concatenation of Strings – Example

Here is an example, which shows concatenations of two strings and a string with a number:

string csharp = "C#";


string dotnet = ".NET";
string csharpDotNet = csharp + dotnet;
Console.WriteLine(csharpDotNet); // C#.NET
string csharpDotNet4 = csharpDotNet + " " + 5;
Console.WriteLine(csharpDotNet4); // C#.NET 5

In the example we initialize two variables of type string and assign them values. On the third and
fourth row we concatenate both strings and pass the results to the method Console.WriteLine() to
print it on the console. On the next line we join the resulting string with a space and the number 5.
We assign the returned value to the variable csharpDotNet5, which will automatically be converted
to type string. On the last row we print the result.

Comparison Operators

Comparison operators in C# are used to compare two or more operands. C# supports the following
comparison operators:

- greater than (>)


- less than (=)
- less than or equal to (<=)
- equality (==)
- difference (!=)
All comparison operators in C# are binary (take two operands) and the returned result is a Boolean
value (true or false). Comparison operators have lower priority than arithmetical operators but
higher than the assignment operators.
Comparison Operators – Example
The following example demonstrates the usage of comparison operators in C#:
int x = 10, y = 5;
Console.WriteLine("x > y : " + (x > y)); // True
Console.WriteLine("x < y : " + (x < y)); // False
Console.WriteLine("x >= y : " + (x >= y)); // True
Console.WriteLine("x <= y : " + (x <= y)); // False
Console.WriteLine("x == y : " + (x == y)); // False
Console.WriteLine("x != y : " + (x != y)); // True

In the example, first we create two variables x and y and we assign them the values 10 and 5. On
the next line we print on the console using the method Console.WriteLine(…) the result from
comparing the two variables x and y using the operator >. The returned value is true because x has
a greater value than y. Similarly, in the next rows the results from the other 5 comparison operators,
used to compare the variables x and y, are printed.

Assignment Operators
The operator for assigning value to a variable is "=" (the character for mathematical equation). The
syntax used for assigning value is as it follows:

operand1 = literal, expression or operand2;

Assignment Operators – Example


Here is an example to show the usage of the assignment operator:
int x = 6; string hello
string = "Hello string.";
int y = x;

In the example we assign value 6 to the variable x. On the second line we assign a text literal to
the variable helloString, and on the third line we copy the value of the variable x to the variable y.
Cascade Assignment
The assignment operator can be used in cascade (more than once in the same expression). In this
case assignments are carried out consecutively from right to left. Here’s an example:

int x, y, z;
x = y = z = 25;

On the first line in the example we initialize three variables and on the second line we assign them
the value 25.

Compound Assignment Operators

Except the assignment operator there are also compound assignment operators. They help to
reduce the volume of the code by typing two operations together with an operator: operation and
assignment. Compound operators have the following syntax:

operand1 operator = operand2;

The upper expression is like the following:

operand1 = operand1 operator operand2;

Here is an example of a compound operator for assignment:


int x = 2;
int y = 4;
x *= y; // Same as x = x * y;
Console.WriteLine(x); // 8

The most commonly used compound assignment operators are += (adds value of operand2 to
operand1), -= (subtracts the value of the right operand from the value of the left one).Other
compound assignment operators are *=, /= and %=.

The following example gives a good idea of how the compound assignment operators work:
int x = 6;
int y = 4;
Console.WriteLine(y *= 2); // 8
int z = y = 3; // y=3 and z=3
Console.WriteLine(z); // 3
Console.WriteLine(x |= 1); // 7
Console.WriteLine(x += 3); // 10
Console.WriteLine(x /= 2); // 5

Conversion to String
If it is necessary, we can convert any type of data, including the value null, to string. The
conversion of strings is done automatically whenever you use the concatenation operator (+) and
one of the arguments is not of type string. In this case the argument is converted to a string and the
operator returns a new string representing the concatenation of the two strings.

Another way to convert different objects to type string is to call the method ToString() of the
variable or the value. It is valid for all data types in .NET Framework. Even calling 3.ToString()
is fully valid in C# and the result will return the string "3".

Conversion to String – Example

Let’s take a look on several examples for converting different data types to

string:
int a = 5;
int b = 7;
string sum = "Sum = " + (a + b);
Console.WriteLine(sum);
string incorrect = "Sum = " + a + b;
Console.WriteLine(incorrect);
Console.WriteLine( "Perimeter = " + 2 * (a + b) + ". Area = " + (a * b) + ".");

The result from the example is as follows:


Sum = 12
Sum = 57
Perimeter = 24. Area = 35.

From the results it is obvious, that concatenating a number to a character string returns in result
the string followed by the text representation of the number. Note that the "+" for concatenating
strings can cause unpleasant effects on the addition of numbers, because it has equal priority with
the operator "+" for mathematical addition. Unless the priorities of the operations are changed by
placing the brackets, they will always be executed from left to right.

Expressions

Much of the program’s work is the calculation of expressions. Expressions are sequences of
operators, literals and variables that are calculated to a value of some type (number, string, object
or other type). Here are some examples of expressions:

int r = (150-20) / 2 + 5;
// Expression for calculating the surface of the circle
double surface = Math.PI * r * r;
// Expression for calculating the perimeter of the circle
double perimeter = 2 * Math.PI * r;
Console.WriteLine(r);
Console.WriteLine(surface);
Console.WriteLine(perimeter);
In the example three expressions are defined. The first expression calculates the radius of a circle.
The second calculates the area of a circle, and the last one finds the perimeter. Here is the result
from the fragment above:

70
15393.80400259
439.822971502571

6. Self-Check Test and Evaluation of Activities

Exercises

1. Write an expression that checks whether an integer is odd or even.


2. Write a Boolean expression that checks whether a given integer is divisible by both 5 and 7,
without a remainder.
3. Write an expression that looks for a given integer if its third digit (right to left) is 7.
4. Write an expression that checks whether the third bit in a given integer is 1 or 0.
5. Write an expression that calculates the area of a trapezoid by given sides a, b and height h.
6. Write a program that prints on the console the perimeter and the area of a rectangle by given
side and height entered by the user.

Grading System
Output =50%
Mid-Term/Final Examination =25%
Quizzes =15%
Attendance =10%
100%

*Final Rating = Midterm (50%) + Final Term (50%)

7. References

Doyle, Barbara (2012). C# Programming, Problem Analysis to Program Design, Cengage


Learning.
Sofia, (2013). Fundamentals of Computer Programming with C#. Nakov, Svetlin & Co.

www.tutorialspoint.com (2014). C# Programming, Object Oriented Programming.


Tutorials Point (I) Pvt. Ltd.

LORENA P. FLORITA
College Instructor

Noted:
MRS. ELVIE D. ARAGONES, PhD (cand.)
Program Chairperson

Approved by:

LUIS I. GANTE JR., PhD


Dean of College

You might also like