Operators & Expressions
Operators perform operations on variables and values. C# includes arithmetic, comparison, logical, and increment operators.
1 Arithmetic division and Operator precedence
Math evaluations match standard precedence rules. Modulus (`%`) yields the remainder of a division. Dividing two integers yields a truncated integer: `5 / 2` evaluates to `2`. Cast one to double to retain decimals: `(double)5 / 2` yields `2.5`.
2 Logical Short-Circuiting
C# uses logical operators: `&&` (AND), `||` (OR), and `!` (NOT). Short-circuiting skips evaluating the second condition if the first condition determines the outcome. Let's test these operators:
C# — Operators
▶ Run Code
using System;
class Program {
static void Main() {
int a = 10;
int b = 4;
Console.WriteLine("Truncated Division (10/4): " + (a / b));
Console.WriteLine("Double Cast Division: " + ((double)a / b));
// Increment postfix vs prefix
int x = 5;
int y = x++; // y gets 5, then x becomes 6
Console.WriteLine("Postfix: y=" + y + ", x=" + x);
int p = 5;
int q = ++p; // p becomes 6, then q gets 6
Console.WriteLine("Prefix: q=" + q + ", p=" + p);
}
}
3 Code Challenge
Challenge: Initialize `int score = 80`. Use comparison and logical operators to check if the score is greater than 50, less than or equal to 100, and is even. Print the result.