How to Use Arithmetic Operators in C# - Simple Guide
In C#, you use
+, -, *, /, and % as arithmetic operators to perform addition, subtraction, multiplication, division, and modulus operations. These operators work with numeric types like int and double to calculate values in expressions.Syntax
Arithmetic operators in C# are used between two numeric values or variables to perform calculations. Here are the common operators:
+: Adds two numbers.-: Subtracts the right number from the left.*: Multiplies two numbers./: Divides the left number by the right.%: Gives the remainder of division (modulus).
Example syntax: result = a + b;
csharp
int a = 10; int b = 3; int sum = a + b; // 13 int diff = a - b; // 7 int product = a * b; // 30 int quotient = a / b; // 3 (integer division) int remainder = a % b; // 1
Example
This example shows how to use arithmetic operators with integers and doubles, and prints the results.
csharp
using System; class Program { static void Main() { int x = 15; int y = 4; Console.WriteLine($"x + y = {x + y}"); Console.WriteLine($"x - y = {x - y}"); Console.WriteLine($"x * y = {x * y}"); Console.WriteLine($"x / y = {x / y}"); Console.WriteLine($"x % y = {x % y}"); double a = 15.0; double b = 4.0; Console.WriteLine($"a / b = {a / b}"); } }
Output
x + y = 19
x - y = 11
x * y = 60
x / y = 3
x % y = 3
a / b = 3.75
Common Pitfalls
One common mistake is using integer division when you want a decimal result. Dividing two integers truncates the decimal part.
Also, dividing by zero causes a runtime error.
csharp
int a = 7; int b = 2; // Wrong: integer division truncates decimal int resultWrong = a / b; // resultWrong is 3 // Right: use double to get decimal result double resultRight = (double)a / b; // resultRight is 3.5 // Division by zero example (will cause error) // int error = a / 0;
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 5 / 3 | 1 (int), 1.666... (double) |
| % | Modulus (remainder) | 5 % 3 | 2 |
Key Takeaways
Use +, -, *, /, and % to perform basic math operations in C#.
Integer division truncates decimals; cast to double for precise division.
Avoid dividing by zero to prevent runtime errors.
Arithmetic operators work with numeric types like int and double.
Use modulus % to find the remainder after division.