Basics Lesson 5 of 15
C# Operators and the Math Class
Arithmetic, assignment, comparison and logical operators in C#, increment and decrement, the Math class (Pow, Sqrt, Round, Max), and random numbers with Random.
Operators do the calculations and comparisons in your programs. C# uses the same operators as Java, C and JavaScript, and adds the helpful Math class for everything else.
Arithmetic
int minutes = 135;
Console.WriteLine($"{minutes / 60} hr {minutes % 60} min");
int students = 43;
Console.WriteLine($"Groups of 5: {students / 5}, left over: {students % 5}");
double avg = (88 + 91 + 85) / 3.0;
Console.WriteLine($"Average: {avg:F2}");
Output
2 hr 15 min Groups of 5: 8, left over: 3 Average: 88.00
Assignment and increment
int score = 10;
score += 5;
score *= 2;
score--;
Console.WriteLine(score);
int a = 5;
int b = a++; // b = 5, then a = 6
int c = ++a; // a = 7, then c = 7
Console.WriteLine($"{a} {b} {c}");
Output
29 7 5 7
Comparison and logical operators
double average = 92.5;
int lowest = 83;
int age = 67;
Console.WriteLine(average >= 90 && lowest >= 85);
Console.WriteLine(age >= 60 || age < 18);
Console.WriteLine(!(age >= 60));
Console.WriteLine("Ana" == "Ana");
Output
False True False True
Unlike Java, comparing strings with == in C# compares their text, so it works as you'd expect.
The Math class
Console.WriteLine(Math.Pow(2, 10));
Console.WriteLine(Math.Sqrt(144));
Console.WriteLine(Math.Abs(-7));
Console.WriteLine(Math.Max(88, 95));
Console.WriteLine(Math.Min(88, 95));
Console.WriteLine(Math.Ceiling(41 / 5.0));
Console.WriteLine(Math.Floor(9.99));
Console.WriteLine(Math.Round(88.456, 2));
Console.WriteLine(Math.PI);
Output
1024 12 7 95 88 9 9 88.46 3.141592653589793
Rounding .5 values
Console.WriteLine(Math.Round(2.5));
Console.WriteLine(Math.Round(3.5));
Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero));
Output
2 4 3
Random numbers
int dice = Random.Shared.Next(1, 7); // 1 to 6 (upper bound excluded)
int classNo = Random.Shared.Next(1, 41); // 1 to 40
double chance = Random.Shared.NextDouble();
Console.WriteLine($"Dice: {dice}, recitation: #{classNo}, chance: {chance:F2}");
Output
Dice: 5, recitation: #23, chance: 0.71
Your numbers will differ. Random.Shared is available in .NET 6 and later; in older code you'll see var rand = new Random(); rand.Next(1, 7);.
The ternary operator and null operators
int grade = 79;
string remark = grade >= 75 ? "PASSED" : "FAILED";
Console.WriteLine(remark);
string? nickname = null;
Console.WriteLine(nickname ?? "Guest");
Console.WriteLine(nickname?.Length ?? 0);
Output
PASSED Guest 0
?. (null-conditional) only reads .Length if nickname isn't null; otherwise the whole expression is null, and ?? turns it into 0.
Precedence
From high to low: (), unary ! ++ --, * / %, + -, comparisons, == !=, &&, ||, ??, ?:, assignment. Use parentheses whenever it's unclear.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04