Introduction
With a basics understanding of variables behind us, we’re ready to get into some deeper material: math. This math is all pretty easy the kid of stuff you learned in school. Basic arithmetic.
computers love math. In fact, it is basically all they can do. But they do it ridiculously fast
In this section we’ll cover how to do some basic arithmetic in C# starting with addition and subtraction, and move up through multiplication and division. a new operation called the modulus operator. positive and negative numbers, order of operations, and conclude with some compound assignment operators. which do math and assign a value all at once.
Addition, Subtraction, Multiplication and Division
Doing the basic operations of addition, subtraction, multiplication and division should be pretty straightforward, especially if you have done other programming before.
Addition
int x = 3;
int y = 2;
int z = x + y;
Console.WriteLine(" x = " + x); // x = 3
Console.WriteLine(" y = " + y); // y = 2
Console.WriteLine(" z = " + z); // z = 5
// more descriptive
int redCards = 3;
int blueCards = 2;
int totalCards = redCards + blueCards;
Console.WriteLine("Red Cards = " + redCards);
Console.WriteLine("Blue Cards = " + blueCards);
Console.WriteLine("You have " + totalCards + " total cards");
Console.WriteLine("Total = {0}" , totalCards); // we can also write like this.
Subtraction
int totalCards = 10;
int cardsTaken = 5;
int cardLeft = totalCards - cardsTaken;
Console.WriteLine( "you have " + cardLeft + " left");
Multiplication and division work in the exact same way, though there are a few tricks we need to watch out for if we do division with integers.
we’ll look at that more in a couple of tutorials, but for now, we’ll just use the float or double type for division instead of integers. The sign for multiplication in C# is the asterisk (*) and sign for division is forward slash (/)
**Multiplication(*)
int cookiesPerBag = 5;
int numberOfBags = 4;
// the computer calculates 5 * 4
int totalCookies = cookiesPerBag * numberOfBags;
Division (/)
This is where students often get confused. In C# the result of division depends on the Data Type
Integer Division
If you divide two whole number (int), C# throws away the remainder. It does not round; it simply cuts the decimal off (truncation).
int x = 15;
int y = 4;
int z = x/y; // 15/4 = 3
// Scenario: Three Friends are splitting a $25 dinner bill.
int bill = 25;
int friends = 3;
int costPerPerson = bill/friends; // 25/ 3 = 8.33
Console.WriteLine ( "Each Person pays: $" + costPerPerson); //output: $8
int division truncates the decimal. it doesn’t round up to 9; it just forgets the .33 existed
Decimal Division To get a precise answer, at least one number must be a double or decimal.
double accurateBill = 25.0;
double accurateFriends = 3.0;
double accurateCost = accurateBill / accurateFriends;
Console.WriteLine("The actual cost per person is: $" + accurateCost); // Output: $8.33333333333333
Double vs Float
in C# double is the default for decimal numbers. If you just type 25.5 in your code, the computer assumes it is a doublt
doubleuses 8 bytes of memory It is more accurate ( 15 - 17 digits)floatuses 4 bytes of memory It is less accurate ( 6-9 digits)
When do we need to use float?
You use float (“floating point”) when memory is tight or when you are doing high-performance graphics.
- Games : game engine use
floatbecause they have to calculate thousands of positions per seconds, using half the memory makes that game run faster. - sensors : tiny hardware devices might use float to save space
When you use decimal?
when working with money, like a store checkout or back app. you should actually use decimal
doubleandfloatare “Binary” decimals. They are fast but can sometimes have tiny rounding errors like8.3333334).decimalis “Base-0” it is 100% accurate for money.- Syntax: decimal price = 25.0m;
| Type | Code Example | Accuracy | Note |
|---|---|---|---|
| float | float x = 5.5f; | low | Needs f suffix. Fast. |
| double | double x = 5.5; | medium | The “Standard” choice. |
| decimal | decimal x = 5.5m; | high | Needs m suffix. Best for $$. |
this same apply for Addition subtraction and multiplication.
The Modulus Operator
remember how you first learned division as : 23 divided by 7 is 3, remainder 2?
In programming calculating the “leftover” amount is so important it has it’s own operator. It is called the Modulus operator ( “mod” for short). This symbol for this is the percentage sign (%)
important in C# % does not mean precent. it means give me the remainder.
// example - 3
int x = 10;
int y = 3;
int a = x / y; // 3
int b = x % y ; // 1
// example - 2
int x = 16;
int y = 4;
int a = x / y; // 4
int b = x % y; // 0
- what is 10 % 3 ? (Answer 1)
- what is 10 % 5 ? (Answer 0)
- what is 4 % 5 ? ( Answer : 4)
- what is 0 % 5 ? ( Answer : 0)
At first glance, it seems like an operator that’s not very useful, but if you know how to use it you will find lots of ways to use it.
Unary + and - Operators
1. Binary Operator Binary means “two”. These operators sit between two numbers to perform action. You cannot have a binary operator without a left-hand side and right-hand side.
- Syntax
Value A [operator] Value B - Example : 5 + 3 (Addition) , 10 /2 (Division) , 7%4 (Modulus)
2. Unary Operator Unary Means “One” These operators only need one value to work. They usually sit directly in front of a number to change or describe it’s state.
-
Unary Minus (
-) This is the most common unary operator. It negates the value. Exampleint debt = -50; Logic: It tells the computer: Take the number 50 and flip its sign to negative. -
Unary Plus (
+) This operator exists, but it is mostly “cosmetic” Example :int temperature = +25. Logic: Since number are positive by default in C#, this doesn’t actually change anything it is used occasionally to make code look symmetrical next to negative numbers.
advanced unary operator, ++ — ! (we’ll learn later)
int x = +2; // 2
int y = -2; // -2
inx z = 10 + -2; // 8
Order of Operators and Parentheses
PEMDAS Just like in your math class, C# doesn’t simply read an equation from left to right. It follows a specific hierarchy to decide which part of the math to do first. If you don’t follow these rules, you variables will end up with the wrong values!
The Hierarchy ( The Rank of Operators) C# follows the standard PEMDAS rules:
- Parentheses
()Always happens first. - Exponents (Note: C# uses
math.Pow()for this, there is no^symbol for math). - Multiplication
*and Division/These have equal rank and happen left-to-right. - Addition
+and Subtraction-These happen last. also left-to-right.
using parentheses for clarity Parentheses are your ‘control switch’ They allow you to force the computer to do addition before multiplication.
Example: The Trapezoid Area. To find the area, you must add the sides before dividing.
$$A = \frac{a + b}{2} \cdot h$$
double side1 = 5.5;
double side2 = 3.25;
double height = 4.6;
// correct:
double area = (side1 + side2) / 2 * height;
// inncorrect:
double wrongArea = side1 + side2 / 2 * height;
area of triangle
$$Area = \frac{1}{2} \times b \times h$$
double b = 10;
double h = 5;
double area = b * h / 2; // 2 / (b * h).
// for clearity.
double area = (b * h) / 2;
Why the = sign doesn’t mean Equals
This is one of the most important “mental shift” a student has to make when moving from Math class to Programming class. In Math = describe a state of balance in C#, = describes an action.
= sign is an “Assignment” Operator
In mathematics, x = 5 means that x is the same as 5. in C# = symbol is called the Assignment Operator If functions like an arrow pointing to the left.
The computer always looks at the Right side first, calculates the answer, and then pushes the answer into the variable on the Left Side
- Right Side : the “Source” (The calculation or value)
- Left Side: The “Destination” ( the variable/ storage box)
int x = 50;
double b = 10;
double h = 5;
double area = b * h / 2;
Think of the = sign as One-way gate Information only flows from Right to Left
Step 1: The Right side ( The calculation )
Before the variable area even knows what is happening, the computer looks at he expression on the right: b * h /2.
Calculate the values. and the right side is no longer an equation; it is just the single value: 25.
Step 2: The Assignment.
Now the computer has the number 25, it sees the = operator. This operator acts like an arrow.
- It takes the 25.
- It finds the memory location ( the box) labeled area.
- It places the 25 inside the box.
Compound Assignment Operators
Professional’s Shorthand they are designed to save you from typing the same variable name twice.
When you see +=, -= , *= , /=, %=, you are telling the computer to do two things in a single step ,
- Math
- Storage
in beginner math, we write the long way: a = a + 3
In professional C# we write the short way: a += 3
they do the exact same thing, but the compound version is cleaner and faster to read once you get used to it.
| Shorthand | What it means | The English Translation |
|---|---|---|
a += 3 | a = a + 3 | ”Add 3 to the current value of a.” |
a -= 3 | a = a - 3 | ”Subtract 3 from the current value of a.” |
a *= 5 | a = a * 5 | ”Multiply the current a by 5.” |
a /= 4 | a = a / 4 | ”Divide the current a by 4.” |
a %= 2 | a = a % 2 | ”Find the remainder of a divided by 2.” |
int playerExperience = 500;
int powerLevel = 10;
// 1. Player completes a quest (Add 150 exp)
// Long way: playerExperience = playerExperience + 150;
playerExperience += 150;
// 2. Player drinks a "Double Power" potion
// Long way: powerLevel = powerLevel * 2;
powerLevel *= 2;
Console.WriteLine("New Experience: " + playerExperience); // Output: 650
Console.WriteLine("New Power Level: " + powerLevel); // Output: 20