Chapter 10
Contents
• 1 Expressions in C#
♦ 1.1 Introduction
♦ 1.2 Using Expressions
♦ 1.3 Arithmetical Expressions
◊ 1.3.1 Type Promotion
◊ 1.3.2 Precedence and Subexpressions
♦ 1.4 Boolean Expressions
◊ 1.4.1 Relational Operators
◊ 1.4.2 Logical Operators
⋅ 1.4.2.1 Truth Tables
♦ 1.5 if and switch Statements
♦ 1.6 Expressions with Side-effects
◊ 1.6.1 Assignment operators
◊ 1.6.2 Increment and Decrement Operators
⋅ 1.6.2.1 Prefix versus Postfix
♦ 1.7 Conditional operator
♦ 1.8 In-Lab Problems
Expressions in C#
A portion of this lab is to be done during the scheduled lab time. The take-home programming assignment is to be turned in before the next lab; see the
lab website. The in-lab portion is worth 40% of the lab credit; the programming assignment is worth the other 60%. See the website for details on how
the programming assignment will be graded. You are not responsible for user errors in input unless specified in the assignment. Feedback will be
provided explaining your grade on each assignment.
It is important that you complete each step before going on to the next, as the exercises build upon one another. You will find it helpful to diagram the
action of each method or function as you go along. If you have difficulty in some step, DO NOT proceed before resolving it; seek assistance from your
lab proctor. You will not be able to fully appreciate the remaining content of the lab and you are likely to compound the problem.
Introduction
This lab will explore the expressions available in C#. C# follows the syntax of the C programming language and has the same expression-rich features
and even more. We will only be looking at a fraction of the expressions available in C#, but what we examine are the most common expressions used in
programming.
Topics Covered in this Lab:
♦ Expression syntax and usage
♦ Operator precedence and subexpressions
♦ Arithmetic operators
♦ Relational and Logical operators
♦ Assignment operators
♦ Increment and Decrement operators
♦ The Conditional operator
♦ Boolean expressions and the conditional statements if and switch
Questions Answered in this Lab:
♦ What is an expression?
♦ How do you form expressions?
♦ What are the most common operators?
♦ How do you create subexpressions?
♦ How are expressions used with if and switch?
Demonstrable Skills Acquired in this Lab:
♦ Ability to write expressions and subexpressions.
♦ Ability to understand operator precedence.
♦ Ability to use different types of operators to form expressions.
♦ Ability to use if and switch statements.
Using Expressions
C# is an expression-rich programming language. An expression in the simplest form is an operator and one or more operands. The operands that are
simple are usually a literal, as 5 or "Z. Yang", a constant or variable, but for more complex expressions then it could be a subexpression. We will talk
about subexpressions a little later. Depending on the type of operator, whether it is unary, binary or ternary, it will have one, two or three operands,
respectively. Expressions also have a value depending on the types of the operands and the operation performed. The basic syntax of an expression
using a unary operator is:
<operator> <operand>
for a prefix operator, that is the <operator> that comes before the <operand> or for the postfix version of a unary operator which comes after, has
syntax:
<operand> <operator>
One of the simplest unary operators you have seen is the negation operator that changes the sign of a numerical value. For instance, if you have a
variable x with a value of -5, then the expression -x will have the value of 5. The negation operator, "-", is a prefix operator which negates the
numerical value of the variable. A binary operator has the basic syntax:
<operand1> <operator> <operand2>
We have already used the binary operators for arithmetic, such as, x+y, which will have a value of the sum of x and y. The ternary operator has three
operands and we have only one example of that in C# called the conditional operator and we will examine that more closely later. To start, we will
review the arithmetical expressions and the operators for creating arithmetical expressions.
Arithmetical Expressions
There are five arithmetic operators in C# that can be used in arithmetical expressions. These expressions are already familiar to you and behave as you
would expect from what you learned in Algebra classes. There is only one difference and that is the data types used on the computer. Recall there are
two commonly used numerical data types used in the computer, int and float. The int represents whole numbers without any fractional part, both
positive and negative numbers and zero. The float represents numbers with fractional parts. In C# there is also a numerical data type that has a
fractional part with more precision called double. The double is the default data type for numerical expressions using numbers with fractional parts.
One other distinction is the addition of the modulo operator, "%", which is used to determine the remainder after dividing on int value by another int
value. So, the operator for arithmetical expressions are as follows: (Here, we replace the <operand> with <expr> to denote the more general form of
the expression where the operands can be subexpressions.)
<expr1>
<expr1>
<expr1>
<expr1>
<expr1>
+
*
/
%
<expr2>
<expr2>
<expr2>
<expr2>
<expr2>
Examples:
These examples should be familiar to you and yield the results you would expect. Test your knowledge and determine the values of the expressions. If
you have any doubt, then ask your lab instructor for assistance. Assume i = 10, j = -1, x = 5.5, y = -100.0, z = 75.0, a = 3.67, and b = -11.0.
1. 3.2 + 100 * 3 / 4
2. i % 8 + j
3. -i + x * 2
4. 15 * a + y
5. b - y - i
Type Promotion
Now as we have described before when we discussed numerical types, we have to pay careful attention to the data types involved in the expressions
especially if we are assigning it to variables. The expression type is determined by the operands. In general, all the operands must be the same type, so
all must be int or all must be double. If all operands are of type int then the value of the expression is of type int. If any of the operands are of type
float then the value of the expression will be float, but none of the operands can be of type double for this to happen, because if there are double
operands then the value of the expression is of type double. This process is called type promotion, that is, if at least one of the operands is of type
double then all the operands are promoted to double and the value of the expression is of type double. If there are no double operands but at least
one operand is of type float then the other operands are promoted to float and again the value of the expression is of type float. Otherwise, if all
the operands are of type int then the expression is of type int. So for the above expressions, what are the types of the expression if the following are
the declarations for the variables in the expressions?
int i, j;
float x, y, z;
double a, b;
If you still don't understand then ask for assistance from your lab instructor.
Precedence and Subexpressions
As with all operators that are used to create expressions, some take precedence over others. As you learned with arithmetical expressions, you will
evaluate the operators from the left to the right, performing multiplication operators, * and / first (and in this case % is also done at this time), followed by
addition operators, + and -. The same is true for ALL operators in C#. There are rules for evaluation of the operators and some are evaluated before
others. This is called operator precedence. If you want to override the evaluation order then we create subexpressions. This is done by placing the
operator and it's operands in parentheses. Then the subexpression in parentheses will be evaluated first before the other operands are evaluated. For
example, the expression
100 * 3 + 2
means (100 * 3) + 2 and if you wish to override the order then you would write the expression as
100 * (3 + 2)
What are the values of the two expressions? So the order of evaluation is very important to the expression's value! You must be sure you understand
the precedence rules for the order of evaluation of the operators when writing expressions. If you are in doubt, then always use parentheses to ensure
the proper order of evaluation as you intended.
Boolean Expressions
Boolean expressions are any expression that has a value of either true or false. These expressions are great for use as conditions in if statements.
We can also use boolean expressions for the conditions controlling while, do-while, and for loops. We have already seen the use of these, but will
review them here for the sake of expressing them in C#.
Relational Operators
The relational operators allow comparison of two values of the same type. Remember for numerical types, then type promotion may take place for the
comparison to occur. The operators can be used on numerical types but some can also be used to test the equality (or inequality) of strings. The
operators, < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), == (equal to), and != (not equal to), have the syntax:
<expr1>
<expr1>
<expr1>
<expr1>
<expr1>
<expr1>
> <expr2>
< <expr2>
<= <expr2>
>= <expr2>
== <expr2>
!= <expr2>
Remember that these are often used as conditions in if statements and loops. Here are some examples:
1. x + y <= 100
2. y % 2 != z
3. s == "Y"
4. 100 * y + z > 300
What are the values of the above expressions if x = 98, y = 3, z = 1, and s = "y".
Logical Operators
The logical operators provide a way to construct more complex boolean expressions by using && (and), || (or), and ! (not) operators.
<expr1> && <expr2>
<expr1> || <expr2>
! <expr>
These operators are named after the mathematician George Boole, who first defined these logical operators mathematically and investigated their
properties in the mid-1800's. These act to combine boolean expressions together logically. C# even defines the bool data type. This type can only have
the values true and false. One of the ways to understand the logical operators is to look at truth tables. The values in the truth table reflect how these
expressions work mathematically but in fact, they also behave the same way when used in rhetorical statements. Philosophers have used these logical
operators for centuries before they were studied mathematically.
Truth Tables
Following is the truth table for && (and). This operator is used as you might expect when using it logically with making statements.
&&
false
true
false
false
false
true
false
true
The truth table for || (or) follows and operates as when you would make statements using a logical "or".
||
false
true
false
false
true
true
true
true
The logical negation operator, ! (not), is used to reverse the value of a logical statement.
!
false
true
true
false
Using this in a boolean expression will allow combining more than one relational expression together, such as:
1. (score >= 0) && (score <=100)
2. answer == "Y" || answer == "y"
3. ! (x == 0)
The last example is equivalent to x != 0, but here we use the logical negation to achieve the same thing.
if and switch Statements
Recall the syntax of the if statement
if ( <condition> )
<statement>
else
<statement>
where the else part of this statement is optional. The <condition> is a boolean expression as described above. The other conditional statement is
the switch statement which can be used in a similar way to the if statement. The syntax of the switch statement is
switch ( <expr> ) {
case <value1>:
<statements>
break;
case <value2>:
<statements>
break;
...
default:
<statements>
break;
}
evaluates <expr> and then compares the value with the values of each case until if finds a match. The type of the <expr> is either of type int or can
be a string type. For example,
Console.Write("Enter your selection > ");
i = int.Parse(Console.ReadLine());
switch ( i ) {
case 1:
Console.WriteLine("Menu item 1 selected");
<statements>
break;
case 2:
Console.WriteLine("Menu item 2 selected");
<statements>
break;
default:
Console.WriteLine("Error in selection");
break;
}
Expressions with Side-effects
Any expression which does more than just return a value has what are called side-effects. Expressions in C# that has side-effects is the assignment
expressions and any expression using the increment or decrement operators. The side-effect in these cases is the values of the variables are changed
when using an assignment expression.
Assignment operators
Assignment is unusual to think of as an expression. There are several assignment expressions in C#. Following is a list of all the operators with their
syntax.
<lvalue>
<lvalue>
<lvalue>
<lvalue>
<lvalue>
<lvalue>
= <expr>
*= <expr>
/= <expr>
%= <expr>
+= <expr>
-= <expr>
The <lvalue> represents anything that is valid for the left value of an assignment statement. Typically this means that the <lvalue> has to be a
variable because the <lvalue> has to have storage to store the value of the <expr>. There is the usual assignment as in
x = 100 * y;
but because this is an expression it returns a value. The value it returns is the final value of x. We get an interesting benefit when assignments are
expressions. We can write multiple assignment statements.
i = j = k = 0;
The above statement will assign i, j, and k the value of 0. The actual evaluation order can be understood by rewriting the statement as:
i = (j = (k = 0));
So, in this case k is assigned 0 first, followed by j and finally to i. The other assignments are of the form:
<lvalue> <operator>= <expr>
and is equivalent to the following:
<lvalue> = <lvalue> <operator> <expr>
For example the statement x *= 10 is equivalent to x = x * 10. The value of the assignment expression is the final value of the <lvalue> or the
value of <lvalue> <operator> <expr>. What do you think the following statement means? Rewrite it in a more understandable form.
a += b *= c -= 2;
If you need help for translation then see your lab administrator for assistance.
Increment and Decrement Operators
Increment and decrement operators create expressions with side-effects. There are two versions of these operators: prefix and postfix. Following is the
syntax for these expressions.
<expr>++
++<expr>
<expr>---<expr>
For the prefix increment operator, ++, the expression ++<expr> is
<expr> = <expr> + 1
Now for this to work, the <expr> must be a valid <lvalue>, which for us, this means a valid variable name. For instance, ++i will add one to the
variable i. Such an expression is really nice to use in for loops. For example,
for (int i = 0; i < 100; ++i)
Console.WriteLine("{0}", i);
will print 0 to 99, but the important thing to notice is the use of the increment operator which is common in for loops. The postfix increment operator has
the same side-effect which is to increment the variable. That means, ++i and i++ adds one to the variable i. The decrement operators subtract one
from the variable in the expression.
Prefix versus Postfix
The difference between the prefix and postfix versions of the increment and decrement operators is the value returned by the expression. Use of these
operators is common and the use of the value of the expression is also common, so understanding the difference can be very important. Consider the
following statement:
j = ++i;
this statement will add one to i, but what is the value of j? The equivalent statements are
i = i + 1;
j = i;
so, j has the value of i + 1 after the execution of the statement. But the postfix increment operator will behave differently when we consider the return
value of the expression, so considering the following statement
j = i++;
are equivalent to the statments
j = i;
i = i+1;
Notice that j gets the value of i before the increment. This is an important difference between the prefix and postfix versions of the increment operator.
The decrement operator can be described in a similar way but a decrement occurs instead of an increment.
Conditional operator
The conditional operator is an example of a ternary operator that uses three operands. It is the only operator in C# to use three operands. The
conditional operator behaves like an if statement except that it is an expression and not a statement. Here is the following syntax for a conditional
expression.
<expr1> ? <expr2> : <expr3>
For example, consider the following assignment statement using a conditional expression:
string s;
s = z >= 0 ? "z is non-negative" : "z is negative";
is equivalent to the following:
string s;
if ( z >= 0 )
s = "z is non-negative";
else
s = "z is negative";
but the conditional expression is more compact and works well for small conditions where assignment is needed. Note: <expr1> is a boolean
expression while <expr2> and <expr3> must have the same type as the <lvalue> when used in the assignment statement.
In-Lab Problems
With your lab instructor, work through the following example, step-by-step, making sure to refer back to the sections that are appropriate for
understanding the syntax for C#. Also, make sure you understand how C# executes the code. Once you are finished have the instructor check your
work to see you have completed the program correctly.
1. Write a program to calculate the cost-per-mile and miles-per-gallon for a user to drive a car. You only know the number of gallons used and the price
per gallon. Following is an example interaction:
Enter the number of miles you drove > 227
Enter the number of gallons you used > 17
Enter the cost per gallon > 2.23
Your miles-per-gallon is 13.353.
Your cost-per-mile is $0.167.
2. Write a program to determine if a number is prime. A number is prime if it is divisible by only 1 and itself. Following is a sample interaction with the
program.
Enter a number > 42
42 is not prime.
Do you want to try again? y
Enter a number > 7
7 is a prime.
Do you want to try again? n
Be sure you have shown your solutions to the lab instructor before you leave the lab!
FOR IN-LAB CREDIT: Upload the solution for each of the above lab steps in a file named Lab08.zip.
If you have questions concerning this assignment, be sure to consult with your lab instructor before leaving the lab.
© Copyright 2026 Paperzz