C# Arithmetic Operators

Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division. They work with numeric types like int, double, and float.

Key Topics

Addition (+)

The addition operator + adds two numbers.

Example 1: Basic Addition

int a = 10;
int b = 20;
int sum = a + b;
Console.WriteLine($"Sum of {a} + {b} = {sum}");

Output:

Sum of 10 + 20 = 30

Example 2: Addition with Floating-Point Numbers

double x = 5.75;
double y = 3.25;
double result = x + y;
Console.WriteLine($"Result of adding {x} + {y} = {result}");

Output:

Result of adding 5.75 + 3.25 = 9.0

Subtraction (-)

The subtraction operator - subtracts the second operand from the first.

Example 1: Basic Subtraction

int a = 30;
int b = 15;
int difference = a - b;
Console.WriteLine($"Difference between {a} - {b} = {difference}");

Output:

Difference between 30 - 15 = 15

Multiplication (*)

The multiplication operator * multiplies two numbers.

Example: Multiplying Integers

int x = 5;
int y = 4;
int product = x * y;
Console.WriteLine($"Product of {x} * {y} = {product}");

Output:

Product of 5 * 4 = 20

Division (/)

The division operator / divides the first operand by the second. Be aware of integer division versus floating-point division.

Example 1: Integer Division

int a = 10;
int b = 3;
int result = a / b;
Console.WriteLine($"Integer division result of {a} / {b} = {result}");

Output:

Integer division result of 10 / 3 = 3

Example 2: Floating-Point Division

double a = 10.0;
double b = 3.0;
double result = a / b;
Console.WriteLine($"Floating-point division result of {a} / {b} = {result}");

Output:

Floating-point division result of 10.0 / 3.0 = 3.3333333333333335

Modulus (%)

The modulus operator % returns the remainder of division.

Example: Modulus Operator

int a = 10;
int b = 3;
int remainder = a % b;
Console.WriteLine($"Remainder of {a} % {b} = {remainder}");

Output:

Remainder of 10 % 3 = 1

Key Takeaways

  • +: Addition operator for numeric types.
  • -: Subtracts one value from another.
  • *: Multiplies two numbers.
  • /: Divides one number by another (beware of integer division).
  • %: Modulus operator returns the remainder of division.