UNIVERSITY OF AGRICULTURE, FAISALABAD
Department of Computer Science
LECTURE 3 · STUDENT NOTES
Arithmetic Operators, Precedence & Type Casting
CS-307 Programming Fundamentals · BSCS Semester 1
Week | Slides | Linked practical | Reference ID |
2 | Lecture3_Operators_Precedence_Casting.pptx | Practical 3 | N03 |
Learning Outcomes
SLO | By the end of this lecture you can… | Builds CLO | Bloom level |
|---|---|---|---|
SLO 3.1 | Evaluate arithmetic expressions using operator precedence and associativity | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 3.2 | Use compound assignment (+=, -= …) and increment/decrement (prefix and postfix) | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 3.3 | Explain implicit conversion and apply explicit casting with static_cast | CLO4: Describe the syntax and semantics of the C++ programming language. | C2 |
SLO 3.4 | Format output with fixed/setprecision and use cmath functions to solve real problems | CLO1: Identify the necessary properties of good problem-solving techniques. | C3 |
How to use these notes Read these notes after the lecture and before the practical. Section numbers (for example §3.2) are used in the question bank, so you can always find where an answer comes from. Type every code example yourself — do not copy-paste. |
1. Where We Are
In Lecture 2 we used + - * / % in simple programs. Today we learn the rules behind them: which operator runs first, quick shortcuts such as += and ++, how C++ converts one data type into another, and how to print money neatly. (Slides L03-S02, S03)
2. Expressions and Operator Precedence
2.1 Operands, operators and expressions
(Slide L03-S05)
Term | Simple meaning | In bill = price * qty + tax; |
|---|---|---|
Operand | The data an operator works on | price, qty, tax |
Operator | A symbol that does an action | = * + |
Expression | Operands and operators that give ONE value | price * qty + tax |
2.2 Precedence and associativity
Precedence (priority) decides which operator runs first. Associativity (direction) decides the order when two operators have the same priority. It works like BODMAS in maths. (Slide L03-S06)
Priority | Operators | Direction |
|---|---|---|
1 (highest) | ( ) | inside out |
2 | ++ -- unary - (cast) | right → left |
3 | * / % | left → right |
4 | + - | left → right |
5 (lowest) | = += -= *= /= %= | right → left |
Rule of thumb When you are not sure, use brackets. They cost nothing and make the code easy to read. |
2.3 Evaluating step by step
(Slide L03-S07) Example: 2 + 3 * 4 - 8 / 2 % 3
Step | Expression | What happened |
|---|---|---|
0 | 2 + 3 * 4 - 8 / 2 % 3 | start |
1 | 2 + 12 - 8 / 2 % 3 | 3 * 4 = 12 (* / % first, left to right) |
2 | 2 + 12 - 4 % 3 | 8 / 2 = 4 |
3 | 2 + 12 - 1 | 4 % 3 = 1 |
4 | 14 - 1 | 2 + 12 = 14 (now + and -, left to right) |
5 | 13 | answer |
2.4 Brackets change the answer
(Slide L03-S08) A very common bug is forgetting brackets when finding an average:
int a = 70, b = 80, c = 90; cout << a + b + c / 3; // 180 — only c is divided by 3! cout << (a + b + c) / 3; // 80 |
Expression | Value | Why |
|---|---|---|
2 + 3 * 4 | 14 | * runs before + |
(2 + 3) * 4 | 20 | brackets run first |
10 - 4 - 3 | 3 | left to right: (10 - 4) - 3 |
3. Shortcut Operators
3.1 Compound assignment
When a variable changes using its own value, C++ gives a shorter way to write it. (Slide L03-S09)
Shortcut | Same as | If x = 10, x becomes |
|---|---|---|
x += 5 | x = x + 5 | 15 |
x -= 4 | x = x - 4 | 6 |
x *= 2 | x = x * 2 | 20 |
x /= 3 | x = x / 3 | 3 (integer division) |
x %= 4 | x = x % 4 | 2 |
Real-world example: a mobile wallet balance += deposit; — money comes in. balance -= billAmount; — money goes out. |
3.2 Increment ++ and decrement --
x++ adds 1 to x; x-- subtracts 1. Counting is everywhere: people entering a hall (gate counter), runs in cricket, seats left on a bus. We will use ++ in every loop from Lecture 9. (Slide L03-S10)
3.3 Prefix vs postfix
The difference only matters when the value is used in the same statement. (Slide L03-S11)
Form | Rule | x = 5; then… | x | y |
|---|---|---|---|---|
Postfix x++ | use the OLD value, then add 1 | y = x++; | 6 | 5 |
Prefix ++x | add 1 first, then use the NEW value | y = ++x; | 6 | 6 |
Real-world example Postfix is like a token counter at a bank: the clerk serves token 5 (old value) and then the board moves to 6. Prefix is like pressing "next" first and then reading the new number. |
Never do this x++ + ++x changes x twice in one statement. The result is undefined (unpredictable) — different compilers give different answers. |
4. Type Conversion and Casting
4.1 Implicit conversion (type promotion)
Implicit means automatic. When two different types meet in an expression, C++ promotes (moves up) the smaller type to the bigger one so no data is lost: char → int → float → double. (Slide L03-S13)
Expression | Types | Result |
|---|---|---|
5 + 2.5 | int + double | 7.5 (double) |
7 / 2 | int / int | 3 (int — no promotion) |
7 / 2.0 | int / double | 3.5 (double) |
'A' + 1 | char + int | 66 (int) |
4.2 Assigning to a smaller type loses data
When a double is stored in an int, the decimal part is truncated (cut off) — it is not rounded. (Slide L03-S14)
int marks = 87.9; // marks = 87, not 88 double d = 7 / 2; // d = 3: the int division happens first, then 3 is stored |
To round properly use round(87.9) from <cmath>, which gives 88.
4.3 Explicit casting with static_cast
Explicit means done on purpose. static_cast<type>(value) tells C++ to treat a value as another type for this calculation only; the original variable does not change. (Slide L03-S15)
int total = 245, count = 3; double avg1 = static_cast<double>(total) / count; // 81.6667 ✓ double avg2 = static_cast<double>(total / count); // 81 ✗ cast is too late double avg3 = (double) total / count; // 81.6667 old C-style cast |
Where to put the cast Cast before dividing. In avg2 the int division 245 / 3 = 81 has already happened, so converting 81 to 81.0 cannot bring the decimals back. |
4.4 Characters are numbers inside (ASCII)
Every character is stored as a code number called its ASCII code (American Standard Code for Information Interchange). (Slide L03-S16)
Char | '0' | '9' | 'A' | 'B' | 'Z' | 'a' | space |
|---|---|---|---|---|---|---|---|
Code | 48 | 57 | 65 | 66 | 90 | 97 | 32 |
cout << 'A' + 1; // 66 (char + int → int) cout << static_cast<char>(66); // B char up = 'g' - 32; // 'G' lowercase to uppercase |
5. Formatting Output and the cmath Library
5.1 fixed, setprecision and setw
Add #include <iomanip> (input/output manipulators — tools that change how output looks). (Slide L03-S17)
Manipulator | Effect | Example → output |
|---|---|---|
fixed | Normal decimal notation, never e-notation | 1250000.00 instead of 1.25e+06 |
setprecision(n) | With fixed: n digits after the decimal point | cout << fixed << setprecision(2) << 1234.5; → 1234.50 |
setw(n) | Width of the NEXT item only (right-aligned) | cout << setw(8) << 42; → " 42" |
fixed and setprecision stay switched on for the rest of the program; setw affects only the next item.
5.2 Ready-made maths functions
Add #include <cmath>. A function is a ready-made tool: you give it values and it gives back an answer. (Slide L03-S18)
Function | Meaning | Example → result |
|---|---|---|
pow(x, y) | x to the power y | pow(2, 10) → 1024 |
sqrt(x) | square root | sqrt(81) → 9 |
abs(x) | remove the minus sign | abs(-7) → 7 |
ceil(x) | round UP | ceil(4.2) → 5 |
floor(x) | round DOWN | floor(4.8) → 4 |
round(x) | round to nearest | round(4.5) → 5 |
Warning: ^ is not power In C++, 2 ^ 3 gives 1, not 8 (^ is a bit operator you will meet later). Always use pow(2, 3) or 2 * 2 * 2. |
Real-world example: ceil 130 students go on a trip; each bus holds 50. Buses needed = ceil(130 / 50.0) = ceil(2.6) = 3. (130 / 50 would give 2 — and 30 students left behind!) |
5.3 Program: shop bill with GST
GST (General Sales Tax) in Pakistan is 18% on most goods. (Slide L03-S19)
gst.cpp #include <iostream> #include <iomanip> using namespace std;
int main() { const double GST_RATE = 0.18; // 18% sales tax double price; int qty;
cout << "Enter unit price (Rs.): "; cin >> price; cout << "Enter quantity: "; cin >> qty;
double subtotal = price * qty; double gst = subtotal * GST_RATE; double total = subtotal + gst;
cout << fixed << setprecision(2); cout << "Subtotal : Rs. " << subtotal << endl; cout << "GST 18% : Rs. " << gst << endl; cout << "Total : Rs. " << total << endl; return 0; } |
Output Enter unit price (Rs.): 249.99 Enter quantity: 4 Subtotal : Rs. 999.96 GST 18% : Rs. 179.99 Total : Rs. 1179.95 |
5.4 Program: length of a ladder (Pythagoras)
A ladder leans on a 6 m wall with its foot 2.5 m from the wall. Ladder length = √(6² + 2.5²) = 6.5 m. (Slide L03-S20)
ladder.cpp #include <iostream> #include <cmath> using namespace std;
int main() { double height, distance; cout << "Height of wall (m): "; cin >> height; cout << "Distance from wall (m): "; cin >> distance;
double ladder = sqrt(pow(height, 2) + pow(distance, 2)); cout << "Ladder length = " << ladder << " m" << endl; cout << "Buy a ladder of " << ceil(ladder) << " m" << endl; return 0; } |
Output Height of wall (m): 6 Distance from wall (m): 2.5 Ladder length = 6.5 m Buy a ladder of 7 m |
6. Common Mistakes
(Slide L03-S21)
Mistake | Wrong code | Correct code |
|---|---|---|
Missing brackets | avg = a + b / 2; | avg = (a + b) / 2.0; |
^ used as power | area = r ^ 2; | area = pow(r, 2); |
Cast in the wrong place | static_cast<double>(a / b) | static_cast<double>(a) / b |
Expecting rounding | int n = 4.9; // 4 | int n = round(4.9); // 5 |
Forgetting the header | sqrt(x) without <cmath> | #include <cmath> |
7. Word Bank (Key Terms)
Word | Simple meaning |
|---|---|
Operand | The data an operator works on |
Expression | A combination of operands and operators that gives one value |
Precedence | Priority: which operator runs first |
Associativity | Direction (left→right or right→left) for operators of equal priority |
Compound assignment | Shortcut such as x += 5 for x = x + 5 |
Increment / decrement | Add 1 / subtract 1 (++ / --) |
Prefix / postfix | ++x changes first then uses; x++ uses first then changes |
Implicit conversion | Automatic change of type done by C++ |
Promotion | Moving a smaller type up to a bigger type (int → double) |
Truncate | Cut off the decimal part without rounding |
Explicit cast | A type change you write yourself with static_cast |
ASCII | The code number of each character ('A' = 65) |
Manipulator | A tool from <iomanip> that changes how output looks |
Undefined behaviour | Code whose result C++ does not promise — avoid it |
8. Self-Check Questions
1. Evaluate 2 + 3 * 4 - 8 / 2 % 3 step by step.
2. Why does a + b + c / 3 not give the average of three numbers? Correct it.
3. If x = 5, give x and y after (a) y = x++; (b) y = ++x;.
4. What is printed by int n = 87.9; cout << n;? Why?
5. Why is static_cast<double>(total / count) wrong for an average?
6. Write C++ to print 2/3 with exactly two decimal places.
7. Why is 2 ^ 3 not 8 in C++? What should you write instead?
Answers are in §2.3, §2.4, §3.3, §4.2, §4.3, §5.1 and §5.2. Homework is on Slide L03-S23.