Operators and Math
Operators combine values into expressions. C# follows the usual math rules, with one surprise for beginners: dividing two integers drops the fraction.
How it works
Use arithmetic, assignment, comparison and logical operators in C#, plus the Math class.
17 / 5 is 3 because both operands are int; 17 / 5.0 keeps the decimals. Comparisons and && / || produce bool values, and Math offers Pow, Round, Sqrt and more.
Runnable C# example
Program.cs
using System;
class Program
{
static void Main()
{
int a = 17, b = 5;
Console.WriteLine($"a + b = {a + b}");
Console.WriteLine($"a - b = {a - b}");
Console.WriteLine($"a * b = {a * b}");
Console.WriteLine($"a / b = {a / b}"); // int / int drops the fraction
Console.WriteLine($"a % b = {a % b}"); // remainder
Console.WriteLine($"a / 5.0 = {a / 5.0}"); // a double operand keeps it
int total = 10;
total += 5;
total *= 2;
Console.WriteLine($"total = {total}");
int count = 0;
count++;
Console.WriteLine($"count = {count}");
// Comparison and logical operators produce bool values.
Console.WriteLine($"a > b: {a > b}, a == 17: {a == 17}");
Console.WriteLine($"a > 10 && b > 10: {a > 10 && b > 10}");
Console.WriteLine($"a > 10 || b > 10: {a > 10 || b > 10}");
// Math holds common functions.
Console.WriteLine($"Math.Pow(2, 10) = {Math.Pow(2, 10)}");
Console.WriteLine($"Math.Round(3.14159, 2) = {Math.Round(3.14159, 2)}");
}
}
a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
a / 5.0 = 3.4
total = 30
count = 1
a > b: True, a == 17: True
a > 10 && b > 10: False
a > 10 || b > 10: True
Math.Pow(2, 10) = 1024
Math.Round(3.14159, 2) = 3.14Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. Easy
- Simple Interest Find the total amount after simple interest. Easy