Skip to main content

Operators in C#: Arithmetic Operators

Following our exploration of comments and documentation, this article dives into the world of arithmetic operators in C#. These are the fundamental building blocks for performing mathematical calculations in your code.


📚 Prerequisites

Before we begin, please ensure you have a solid grasp of the following concepts:

  • A good understanding of C#'s numeric data types (int, double, etc.).
  • Experience declaring and initializing variables.

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • Foundational Theory: The different types of arithmetic operators in C#.
  • Core Implementation: How to use the addition, subtraction, multiplication, division, and modulus operators.
  • Practical Application: Building a simple application to calculate the area of a rectangle.
  • Advanced Techniques: Understanding operator precedence and integer vs. floating-point division.
  • Best Practices & Anti-Patterns: Writing clean and readable mathematical expressions.

🧠 Section 1: The Core Concepts of Arithmetic Operators

Arithmetic operators are symbols that tell the compiler to perform a specific mathematical operation. C# supports the standard arithmetic operators you learned in math class, plus a few more.

Key Principles:

  • Operands: Arithmetic operators work on one or more operands. An operand is the value or variable that the operator acts upon.
  • Unary vs. Binary: Operators can be unary (acting on one operand, like the negation operator -) or binary (acting on two operands, like the addition operator +).
  • Operator Precedence: C# has a defined order of operations (like PEMDAS/BODMAS in math) to determine which operators are evaluated first in a complex expression.

💻 Section 2: Deep Dive - The Arithmetic Operators

2.1 - The Binary Operators

These operators work with two operands.

OperatorNameDescription
+AdditionAdds two operands.
-SubtractionSubtracts the second operand from the first.
*MultiplicationMultiplies two operands.
/DivisionDivides the first operand by the second.
%ModulusReturns the remainder of a division.
// BinaryOperatorsExample.cs
using System;

public class BinaryOperatorsExample
{
public static void Main(string[] args)
{
int a = 10;
int b = 3;

Console.WriteLine($"Addition: {a + b}"); // 13
Console.WriteLine($"Subtraction: {a - b}"); // 7
Console.WriteLine($"Multiplication: {a * b}"); // 30
Console.WriteLine($"Division: {a / b}"); // 3 (integer division)
Console.WriteLine($"Modulus: {a % b}"); // 1
}
}

2.2 - The Unary Operators

These operators work with a single operand.

OperatorNameDescription
++IncrementIncreases the value by 1.
--DecrementDecreases the value by 1.
+Unary PlusReturns the value of the operand.
-Unary MinusNegates the value of the operand.
// UnaryOperatorsExample.cs
using System;

public class UnaryOperatorsExample
{
public static void Main(string[] args)
{
int a = 5;
Console.WriteLine($"Original value: {a}");

a++; // Postfix increment
Console.WriteLine($"After postfix increment: {a}"); // 6

++a; // Prefix increment
Console.WriteLine($"After prefix increment: {a}"); // 7

int b = -a;
Console.WriteLine($"Negated value: {b}"); // -7
}
}

🛠️ Section 3: Project-Based Example: Area of a Rectangle

Let's create a simple console application that calculates the area of a rectangle based on user input.

// RectangleArea.cs
using System;

public class RectangleArea
{
public static void Main(string[] args)
{
Console.Write("Enter the width of the rectangle: ");
double width = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter the height of the rectangle: ");
double height = Convert.ToDouble(Console.ReadLine());

double area = width * height;

Console.WriteLine($"The area of the rectangle is: {area}");
}
}

Code Breakdown:

  • We prompt the user for the width and height.
  • We use Convert.ToDouble() to convert the user's input to double values.
  • We use the multiplication operator (*) to calculate the area.

🔬 Section 4: A Deeper Dive: Operator Precedence and Division

4.1 - Operator Precedence

C# evaluates expressions in a specific order. The precedence for arithmetic operators is:

  1. ++, -- (as postfix)
  2. ++, -- (as prefix), +, - (unary)
  3. *, /, %
  4. +, - (binary)

You can use parentheses () to override the default order.

int result = 5 + 2 * 3; // result is 11, not 21
int anotherResult = (5 + 2) * 3; // anotherResult is 21

4.2 - Integer vs. Floating-Point Division

The result of the division operator (/) depends on the types of the operands.

  • If both operands are integers, the result is an integer, and any remainder is discarded (truncated).
  • If at least one operand is a floating-point number (double, float, decimal), the result is a floating-point number.
int a = 10;
int b = 4;
Console.WriteLine(a / b); // Output: 2

double c = 10.0;
double d = 4.0;
Console.WriteLine(c / d); // Output: 2.5

✨ Section 5: Best Practices and Anti-Patterns in C#

Best Practices:

  • Use parentheses for clarity: Even if you know the operator precedence, using parentheses can make your code much easier to read and prevent subtle bugs.
  • Be mindful of data types: Ensure your variables are of the correct data type for the calculations you are performing.

Anti-Patterns:

  • Relying on implicit precedence in complex expressions: This can make your code hard to understand and maintain.
  • Forgetting about integer division: This is a common source of bugs when you expect a fractional result.

💡 Conclusion & Key Takeaways

You've now learned how to perform mathematical calculations in C# using arithmetic operators.

Let's summarize the key takeaways:

  • C# provides a full set of arithmetic operators for calculations.
  • Operator precedence determines the order of operations.
  • The type of the operands affects the result of division.

Challenge Yourself (.NET Edition): Write a console application that converts a temperature from Celsius to Fahrenheit. The formula is F = (C * 9/5) + 32. Be careful with integer division!


➡️ Next Steps

In the next article, "Operators: Comparison Operators", we will learn how to compare values in C#.

Happy coding!


Glossary (.NET/C# Terms)

  • Operator: A symbol that tells the compiler to perform a specific operation.
  • Operand: The value or variable that an operator acts upon.
  • Operator Precedence: The order in which operators are evaluated in an expression.
  • Modulus: The remainder of an integer division.

Further Reading (.NET Resources)