C# - Arithmetic Operators
C# - Arithmetic Operators
Section titled “C# - Arithmetic Operators”What Are Arithmetic Operators?
Section titled “What Are Arithmetic Operators?”Arithmetic operators are fundamental symbols used to perform mathematical calculations on numeric types like int, double, and decimal. They form the basis of most numerical computations in C#.
Core Arithmetic Operators
Section titled “Core Arithmetic Operators”The following table lists the binary arithmetic operators in C#. Let’s assume int a = 10; and int b = 20;.
| Operator | Symbol | Description | Example |
|---|---|---|---|
| Addition | + | Adds two operands | a + b is 30 |
| Subtraction | - | Subtracts the second operand from the first | b - a is 10 |
| Multiplication | * | Multiplies both operands | a * b is 200 |
| Division | / | Divides the first operand by the second | b / a is 2 |
| Modulus (Remainder) | % | Returns the remainder of an integer division | 10 % 3 is 1 |
Increment and Decrement Operators
Section titled “Increment and Decrement Operators”These are unary operators that modify a variable by adding or subtracting 1. They come in two forms: prefix and postfix.
- Increment (
++): Increases an integer value by one. - Decrement (
--): Decreases an integer value by one.
Prefix vs. Postfix
Section titled “Prefix vs. Postfix”The position of the ++ or -- operator matters when used in an expression:
- Prefix (
++variable): The variable is incremented first, and the new value is used in the expression. - Postfix (
variable++): The original value of the variable is used in the expression, and then the variable is incremented.
int x = 5;// Prefix: Increment x to 6, then assign 6 to y.int y = ++x;// At this point, x is 6 and y is 6.Console.WriteLine($"Prefix: x = {x}, y = {y}");
int a = 5;// Postfix: Assign the original value of a (5) to b, then increment a to 6.int b = a++;// At this point, a is 6 and b is 5.Console.WriteLine($"Postfix: a = {a}, b = {b}");
/** Expected Output:* Prefix: x = 6, y = 6* Postfix: a = 6, b = 5*/Code Examples
Section titled “Code Examples”Example 1: Basic Operations
Section titled “Example 1: Basic Operations”A simple demonstration of all the core arithmetic operators.
int a = 11;int b = 5;
Console.WriteLine($"a = {a}, b = {b}");Console.WriteLine($"Addition: {a + b}"); // Output: 16Console.WriteLine($"Subtraction: {a - b}"); // Output: 6Console.WriteLine($"Multiplication: {a * b}"); // Output: 55Console.WriteLine($"Division: {a / b}"); // Output: 2 (Integer division)Console.WriteLine($"Modulus: {a % b}"); // Output: 1 (Remainder of 11 / 5)Example 2: Integer vs. Floating-Point Division
Section titled “Example 2: Integer vs. Floating-Point Division”The / operator behaves differently depending on the data types of the operands. When both operands are integers, it performs integer division, which truncates any fractional part.
int intA = 7, intB = 2;double doubleA = 7.0, doubleB = 2.0;
// Integer division discards the remainder.Console.WriteLine($"Integer Division (7 / 2): {intA / intB}"); // Output: 3
// To get a precise result, at least one operand must be a floating-point type.Console.WriteLine($"Floating-Point Division (7.0 / 2.0): {doubleA / doubleB}"); // Output: 3.5Console.WriteLine($"Mixed-Type Division (7 / 2.0): {intA / doubleB}"); // Output: 3.5Practical Use Cases
Section titled “Practical Use Cases”Arithmetic operators are used everywhere in programming.
Use Case 1: Calculating the Area of a Circle
Section titled “Use Case 1: Calculating the Area of a Circle”// Use the Math.PI constant for better precision.const double radius = 5.5;double area = Math.PI * radius * radius;
Console.WriteLine($"Circle Area: {area:F4}"); // :F4 formats to 4 decimal places// Expected Output: Circle Area: 95.0332Use Case 2: Converting Temperature
Section titled “Use Case 2: Converting Temperature”double celsius = 30;// The formula is (Celsius * 9/5) + 32.// Note: Using 9.0/5.0 to ensure floating-point division.double fahrenheit = (celsius * 9.0 / 5.0) + 32;
Console.WriteLine($"{celsius}°C is equal to {fahrenheit}°F");// Expected Output: 30°C is equal to 86°FBest Practices and Considerations
Section titled “Best Practices and Considerations”- Precision: For financial or scientific calculations requiring high precision, use the
decimaltype instead ofdoubleto avoid small rounding errors. - Division by Zero: Dividing an integer by zero throws a
DivideByZeroException. Dividing a floating-point number (doubleorfloat) by zero results inInfinity,-Infinity, orNaN(Not a Number) without throwing an exception. Always check for zero before dividing if you are not sure of the divisor’s value. - Operator Precedence: Multiplication (
*), division (/), and modulus (%) have higher precedence than addition (+) and subtraction (-). Use parentheses()to enforce a specific order of operations, which also improves code readability. - Numeric Overflow: Arithmetic operations on integral types (like
int) can overflow if the result exceeds the type’s maximum value. For critical calculations, use thecheckedkeyword to force anOverflowExceptionto be thrown.
int max = int.MaxValue;try{ // This code is in a 'checked' context. int overflow = checked(max + 1);}catch (OverflowException ex){ Console.WriteLine("Caught expected overflow!");}