Chapter 4: Basic Math - Operators, Arithmetic, and Precedence
Theoretical Foundations
In the previous chapter, you learned how to store information in variables and display it to the user. You learned that a variable is like a labeled box that holds a specific piece of data, such as a number or a sentence. You also learned how to glue strings together using concatenation (+) and how to insert variables into strings using String Interpolation ($"").
Now, we are going to learn how to do math with those variables.
Computers are, at their heart, giant calculators. Before they could write poetry or generate images, they were built to crunch numbers. In this section, we will explore the basic arithmetic operators that allow C# to perform calculations. We will look at how to add, subtract, multiply, and divide the numbers stored in your variables.
The Real-World Analogy: The Grocery List
Imagine you are at the grocery store with a calculator. You have a list of items you need to buy, and you want to keep a running total of how much you are spending.
- Addition (
+): You pick up a carton of eggs for $4.00. You add this to your current total. - Subtraction (
-): You have a coupon for $2.00 off. You subtract this from your total. - Multiplication (
*): You need to buy 3 cans of soup that cost $1.50 each. Instead of adding $1.50 three times, you multiply the price by the quantity. - Division (
/): You have $10.00 left, and you want to split it equally between two bags of chips. You divide the money to see how much each bag can cost.
In C#, the variables holding your numbers are the pieces of paper where you write down the prices. The arithmetic operators are the buttons on your calculator.
The Arithmetic Operators
C# provides five primary operators for performing mathematical calculations on numeric types (like int and double).
1. Addition (+) and Subtraction (-)
These are the most intuitive operators. The + operator sums two numbers, and the - operator subtracts the second number from the first.
Let's look at some code. We will declare two variables, apples and oranges, and then calculate a total.
using System;
int apples = 5;
int oranges = 3;
// We use the + operator to find the total number of fruits
int totalFruits = apples + oranges;
// We use the - operator to see how many more apples we have than oranges
int difference = apples - oranges;
Console.WriteLine($"Total fruits: {totalFruits}"); // Output: Total fruits: 8
Console.WriteLine($"Difference: {difference}"); // Output: Difference: 2
The Concept of "Integers" vs "Doubles":
You will notice we used int variables here. int stands for Integer, which is a whole number (no decimals). If you try to divide two integers, C# might give you a surprising result, which we will discuss in the "Division" section.
2. Multiplication (*)
The asterisk (*) is used for multiplication. It calculates the product of two numbers.
Imagine you are calculating the area of a rectangle. You have a length of 10 and a width of 5.
using System;
int length = 10;
int width = 5;
// Calculate area using multiplication
int area = length * width;
Console.WriteLine($"The area is: {area}"); // Output: The area is: 50
3. Division (/)
The forward slash (/) is the division operator. It divides the number on the left (the numerator) by the number on the right (the denominator).
This is where we must be very careful about the Type System you learned in Chapter 2.
Scenario A: Dividing Integers
If you divide an int by an int, C# performs Integer Division. This means it calculates the result and throws away any remainder or decimal part. It essentially rounds down to the nearest whole number.
using System;
int totalSlices = 10;
int people = 4;
// 10 divided by 4 is 2.5.
// But because we are using integers, C# drops the .5.
int slicesPerPerson = totalSlices / people;
Console.WriteLine($"Each person gets: {slicesPerPerson} slices.");
// Output: Each person gets: 2 slices. (The 0.5 is lost!)
Scenario B: Using Doubles
To get a precise answer with decimals, at least one of the numbers must be a double (or another floating-point type).
using System;
double totalSlices = 10.0; // Note the .0 to make it a double
int people = 4;
// Because totalSlices is a double, C# performs Floating-Point Division.
double slicesPerPerson = totalSlices / people;
Console.WriteLine($"Each person gets: {slicesPerPerson} slices.");
// Output: Each person gets: 2.5 slices.
4. The Modulus Operator (%)
The percent sign is called the Modulus Operator. It does not calculate a percentage. Instead, it calculates the remainder of a division.
Returning to our pizza example: 10 slices divided by 4 people gives 2 slices per person, with 2 slices left over. The modulus operator finds that leftover number.
using System;
int totalSlices = 10;
int people = 4;
// We want to know what is left over after division
int remainder = totalSlices % people;
Console.WriteLine($"Leftover slices: {remainder}"); // Output: Leftover slices: 2
This operator is incredibly useful in programming logic (even though we aren't covering logic statements yet) for tasks like determining if a number is even or odd. If a number % 2 equals 0, the number is even.
Operator Precedence: The Order of Operations
What happens if you write a complex expression like 5 + 2 * 3? Do you add 5 and 2 first to get 7, and then multiply by 3 to get 21? Or do you multiply 2 and 3 first to get 6, and then add 5 to get 11?
Just like in standard mathematics, C# follows a strict set of rules called Precedence.
- Multiplication (
*), Division (/), and Modulus (%) have higher precedence. They are calculated first. - Addition (
+) and Subtraction (-) have lower precedence. They are calculated last.
If operators have the same precedence (like + and -), C# evaluates them from left to right.
The Math Stack:
When C# sees 5 + 2 * 3, it looks at the * first because it has higher precedence.
- Calculate
2 * 3(Result: 6). - Calculate
5 + 6(Result: 11).
Using Parentheses ()
You can override precedence by using parentheses, just like in math. Anything inside parentheses is calculated first.
using System;
// Now we force the addition to happen first
int result = (5 + 2) * 3;
Console.WriteLine($"Result: {result}"); // Output: Result: 21
Compound Assignment Operators
In programming, you will often need to update the value of a variable based on its current value.
For example, imagine you have a variable score and you want to add 10 points to it.
The Long Way:
The Short Way (Compound Assignment): C# provides shorthand operators for this exact pattern.
You can do this for all arithmetic operators:
score -= 10(Subtract 10 from score)score *= 2(Multiply score by 2)score /= 2(Divide score by 2)score %= 3(Update score to be the remainder of score divided by 3)
The Increment Operator (++)
There is one specific operator that is extremely common: the increment operator (++). This operator adds exactly 1 to a variable.
This is simply a shortcut for counter = counter + 1.
Prefix vs. Postfix (A Critical Nuance)
You can put the ++ before the variable name (++counter) or after (counter++). Both add 1, but they behave differently if you use them inside a larger expression at the same time.
- Postfix (
counter++): Use the current value of the variable in the expression, then add 1. - Prefix (
++counter): Add 1 to the variable first, then use the new value in the expression.
using System;
int a = 5;
int b = a++; // b gets 5 (the old value), then a becomes 6
int x = 5;
int y = ++x; // x becomes 6 (first), then y gets 6 (the new value)
Console.WriteLine($"Postfix: a={a}, b={b}"); // Output: a=6, b=5
Console.WriteLine($"Prefix: x={x}, y={y}"); // Output: x=6, y=6
Note: As a beginner, it is often safer to keep increment operators on their own line to avoid confusion.
Visualizing the Math Flow
The following diagram shows how C# evaluates an expression like int result = (10 + 2) * 5 / 2;. It highlights how parentheses force an action to the top of the "stack" of operations.
Why Does This Matter for AI?
While this might seem like basic calculator math, these operators are the atomic building blocks of Artificial Intelligence.
- Neural Networks: At the absolute core of a neural network (the engine behind modern AI), there is a mathematical function called an "activation function." It involves massive amounts of multiplication and addition. The weights (importance) of data are updated using formulas that look like
weight = weight + (error * learning_rate). This is just addition and multiplication! - Normalization: When feeding data into an AI model, you often have to normalize numbers (e.g., scaling a pixel value from 0-255 down to 0.0-1.0). This is done using division.
- Vector Math: High-performance AI libraries (like those used to run models locally) use vector math. While we haven't covered arrays or lists yet, just know that under the hood, they are performing billions of
+,-,*, and/operations per second.
Understanding these operators ensures that when you eventually build an AI application, you understand the fundamental math that drives the intelligence.
Basic Code Example
Here is a simple code example demonstrating basic arithmetic operations in C#.
using System;
class BasicMathExample
{
static void Main()
{
// 1. Define variables to hold our numbers.
int firstNumber = 10;
int secondNumber = 3;
// 2. Perform basic arithmetic operations.
int sum = firstNumber + secondNumber;
int difference = firstNumber - secondNumber;
int product = firstNumber * secondNumber;
int quotient = firstNumber / secondNumber; // Integer division
int remainder = firstNumber % secondNumber; // Modulo operator
// 3. Print the results to the console.
Console.WriteLine($"First Number: {firstNumber}");
Console.WriteLine($"Second Number: {secondNumber}");
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Difference: {difference}");
Console.WriteLine($"Product: {product}");
Console.WriteLine($"Quotient: {quotient}");
Console.WriteLine($"Remainder: {remainder}");
// 4. Demonstrate increment operator.
int counter = 5;
Console.WriteLine($"Counter before increment: {counter}");
counter++; // Adds 1 to the variable
Console.WriteLine($"Counter after increment: {counter}");
}
}
Explanation
This code solves a fundamental problem in programming: performing calculations on data and presenting the results. Imagine you are building a simple shopping calculator. You have the price of an item (firstNumber) and the quantity you want to buy (secondNumber). You need to calculate the total cost (product), apply a discount (difference), or split the cost into payments (division).
Here is the step-by-step breakdown of the code:
-
Variable Declaration: We declare two integer variables,
firstNumberandsecondNumber. We assign them the values10and3respectively. These act as our operands for the mathematical operations. -
Arithmetic Operations: We perform the four basic arithmetic operations:
- Addition (
+): Calculates the sum of the two numbers. - Subtraction (
-): Calculates the difference between the two numbers. - Multiplication (
*): Calculates the product of the two numbers. - Division (
/): Calculates the quotient. Note: Since both variables are integers, C# performs integer division. It divides the numbers and discards any fractional part. \(10 / 3\) equals \(3\), not \(3.33\). - Modulo (
%): Calculates the remainder of the division. \(10 \% 3\) equals \(1\) because 3 goes into 10 three times with 1 left over.
- Addition (
-
Output: We use
Console.WriteLinecombined with string interpolation ($"...") to display the original numbers and the calculated results to the console. -
Increment Operator: We introduce a new variable
counterinitialized to5. The++operator is a shorthand for adding 1 to a variable. It is equivalent to writingcounter = counter + 1. We print the value before and after the operation to show the change.
Visualizing the Flow
The flow of data in this program is linear. Data enters via variable assignment, flows through mathematical operators, and exits to the console.
Common Pitfalls
Integer Division Truncation
A very common mistake for beginners is expecting a decimal result when dividing two integers. In C#, if you divide an integer by an integer (int / int), the result is always an integer. The fractional part is simply discarded (truncated), not rounded.
- Example:
int result = 5 / 2; - Expectation:
2.5 - Actual Result:
2
To get a decimal result, at least one of the numbers must be a floating-point type (like double or float). For example: double result = 5.0 / 2; would yield 2.5.
The chapter continues with advanced code, exercises and solutions with analysis, you can find them on the ebook on Leanpub.com or Amazon
Code License: All code examples are released under the MIT License. Github repo.
Content Copyright: Copyright © 2026 Edgar Milvus | Privacy & Cookie Policy. All rights reserved.
All textual explanations, original diagrams, and illustrations are the intellectual property of the author. To support the maintenance of this site via AdSense, please read this content exclusively online. Copying, redistribution, or reproduction is strictly prohibited.