Bell Labs was the research arm of AT&T (founded
1925).
In the late 1960s, they needed an operating system to
manage computers for communication networks(manage = schedule programs, allocate CPU & memory,
control devices, share files).
1969–1971: Led to the creation of UNIX as a flexible
system for research and telecom needs.
History of C/C++
Early 1970s at Bell Labs (Dennis Ritchie)
System programming for UNIX
Why C?
Close to hardware, portable
Small runtime, fast compilation
Questions?
From Code to Machine
C Code
int totalCredits(int a, int b) {
return a + b;
}
Compiler
$ gcc -S totalCredits.c -o totalCredits.s
Translates C source into assembly
Assembly
totalCredits:
mov eax, edi ; a into eax
add eax, esi ; add b to eax
ret ; return result
x86-64 System V calling convention
Assembler
$ as totalCredits.s -o totalCredits.o
Assembles into machine code (object file)
Machine Code
55 ; push rbp
89 f8 ; mov eax, edi
01 f0 ; add eax, esi
5d ; pop rbp
c3 ; ret
Compiled with gcc -O1 on x86-64
Enroll Student (C Code)
#include <stdio.h>
// Enroll a student
void enroll_student() {
printf("Linking...\n");
printf("Enrolled!\n");
}
int main() {
enroll_student();
return 0;
}
Questions?
History of C++
History of C++
1980s: Bjarne Stroustrup
“C with Classes” → C++
C Is a Subset of C++
Every valid C program is (almost) valid C++
Why C++?
Object‑oriented programming
Performance with abstraction
Quick Check
Which is a subset of the other?
C++ is a subset of C
C is a subset of C++
They are unrelated
B. C is a subset of C++.
Questions?
I/O & Variables
Basic I/O
#include <iostream>
int main(){
int credits;
std::cout << "Credits enrolled? ";
std::cin >> credits;
std::cout << "You are enrolled in ";
std::cout << credits << "\n";
}
Quick Check
Which operator reads user input?
<< sends output
>> reads input
== compares values
B. cin >> reads input.
Variables
History of the Variable
1957: FORTRAN adds named data
1958: ALGOL adds := for it
Every language has kept it
Why Variables?
Store a value, reuse it
Give data a name
// No var, repeat
cout << 15;
cout << 15;
// Reuse the variable
int credits = 15;
cout << credits;
cout << credits;
What Is a Variable?
A named spot in memory
Holds one value at a time
The value can change
Anatomy of a Variable
Type: what kind of value
Name: how you refer to it
Value: what's stored now
int credits = 15;
// ^ ^ ^
// type name value
Word Origin: "Variable"
Latin: variare, to change
Math: an unknown quantity
1957: FORTRAN's named data
Declaring a Variable
Tells the compiler: this name
exists, and holds this type
No value yet
int credits;
// no value yet
Word Origin: "Declare"
Latin: declarare, make clear
You're telling the compiler
"this name will exist"
Code It: Declare a Variable
Declare an int named year
No value yet
How would you write it?
int year;
Initializing a Variable
Declare AND give a value
Happens in one statement
Best practice: always do this
int credits = 15;
// declared & set
Word Origin: "Initialize"
Latin: initium, a beginning
"Set the starting value"
Happens at declaration
Quick Check
What's the difference: declare vs. initialize?
No difference at all
Initialize also sets a value
Declare also sets a value
B. Initializing = declaring + giving it a starting value.
Code It: Initialize a Variable
Initialize gpa to 3.5
Type: double
How would you write it?
double gpa = 3.5;
Assigning a Value
= is the assignment operator
Stores a value in a variable
Variable must exist first
int credits;
credits = 15;
// after declare
Word Origin: "Assign"
Latin: assignare, mark out
1958: ALGOL's := operator
C++ shortens it to just =
Code It: Assign a Value
Declare age (int) first
Then assign it 20
How would you write it?
int age;
age = 20;
Reassigning a Variable
Change the stored value
Old value is overwritten
Same variable, new value
int credits = 15;
credits = 18;
// old value gone
Word Origin: "Reassign"
Latin: re-, again + assign
"Assign a new value again"
Same variable, new value
Quick Check
What happens when you reassign a variable?
A new variable is created
The old value is overwritten
Nothing, it's an error
B. Reassigning overwrites the old value in place.
Code It: Reassign a Variable
credits starts at 12
Reassign it to 16
How would you write it?
int credits = 12;
credits = 16;
Declare, Initialize, Assign, Reassign
int x; is declaring
int x = 5; is initializing
x = 9; is (re)assigning
int x; // declare
x = 5; // assign
int y = 5; // init
y = 9; // reassign
Types of Variables
Why Do Types Matter?
Type = what kind of data
Sets the size in memory
Sets what operations work
Word Origin: "Type"
Greek: typos, a mark/model
Defines a value's shape
int, double, char, bool...
Operators: + and -
+ adds two values
- subtracts two values
Work like in math class
int a = 10, b = 3;
int sum=a+b; // 13
int diff=a-b; // 7
Operators: * and /
* multiplies two values
/ divides two values
Division can drop decimals
int a = 10, b = 3;
int prod=a*b; // 30
int quot=a/b; // 3
Type: int
Whole numbers only
No decimal point
e.g., credits, a count
int credits = 15;
int year = 2026;
int in Practice
Most common numeric type
No fractions allowed
9/2 gives 4, not 4.5
int a = 9;
int b = 2;
int result = a / b;
cout << result; // 4
Quick Check
Which university variable fits int best?
unitsCompleted
cumulativeGPA
studentEmail
A. unitsCompleted is a whole number, no decimals.
Code It: Units Completed
Declare units
Set it to 45
How would you write it?
int units=45;
Type: double
Numbers with decimals
"Double precision" float
e.g., gpa, price, average
double gpa = 3.8;
double price = 19.99;
double in Practice
Keeps the decimal part
Use for any fraction
9.0 / 2 gives 4.5
double a = 9.0;
double b = 2.0;
double r = a / b;
cout << r; // 4.5
Higher or lower than 5? (1/2/3)
1) Higher 2) Lower 3) It is 5!
> 1
Higher or lower than 8? (1/2/3)
> 2
Higher or lower than 6? (1/2/3)
> 1
It must be 7!
Task 3: Draw the Flowchart
With your team, draw it
Show all 3 questions
Include the illegal-reply case
Lab 2 Deliverable
One flowchart per team
Covers all 3 questions
Ready when instructor checks
Answer Time
Answer: What Is an Algorithm?
A step-by-step set of
instructions to solve a
problem or finish a task
⚠️ Plan the algorithm before writing any code.
Answer: The Guessing Flowchart
Answer: The Code (First Question)
Uses only if and else
choice == 3 means correct
Pattern repeats for Q2, Q3
int choice;
cout << "Higher or lower than 5?";
cin >> choice;
if (choice == 3) {
cout << "It must be 5!";
}
else {
// same if/else again,// asking about 8 or 3
}
Answer: The Code (Second Question)
Second question, if Higher
choice == 3 means correct
Else: ask about 9 or 6
if (choice == 1) {
cout << "Higher or lower than 8?";
cin >> choice;
if (choice == 3) {
cout << "It must be 8!";
}
else {
// ask about 9 or 6 next
}
}
Answer: The Code (Third Question)
Third question, if Lower
Only 6 or 7 remain
choice == 3 means it's 6
cout << "Higher or lower than 6?";
cin >> choice;
if (choice == 3) {
cout << "It must be 6!";
}
else {
cout << "It must be 7!";
}
Lab 3: University Library
Scenario: Book Checkout
20 minutes, teams of two
copies: ask the class
Split screen: A left, B right
Team Roles
Partner A: left side of slide
Partner B: right side of slide
Switch sides each round
Plan Your Variables
Copies: a whole-number count
Pick from the 7 native types
float, int, or char?
// pick a type for copies
int copies; // a whole-number count
⚠️ float allows decimals; copies can't be 2.5.
Round 1: Split Tasks
Two jobs, one shared program:
Partner A: the condition
Ask: copies checked out?
Declare copies, fill a number
Write just the if line
int copies; // what do you recommend?// your if line goes here
Partner B: the messages
Don't rewrite the if line
Just the two cout lines
One for each outcome
// if true: available message?// if false: checked out message?
Answer: Round 1, Combined
Partner A + Partner B, one program:
int copies; // from the classif (copies > 0) {
cout << "Available";
}
else {
cout << "Checked out";
}
⚠️ copies > 0 excludes zero, not just negatives.
Round 2: Trace It Together
copies = 0 now
Predict the output
Confirm with your partner
int copies = 0;
if (copies > 0) {
cout << "Available";
}
else {
cout << "Checked out";
}
Answer: Round 2
Checked out
Round 3: Swap & Split
Roles swap, same idea:
Partner B: the condition
Ask: days late?
Declare daysLate, fill number
Write just the if line
int daysLate; // what do you recommend?// your if line goes here
Partner A: the messages
Don't rewrite the if line
Just the two cout lines
One for each outcome
// if true: fine message?// if false: no-fine message?
Answer: Round 3, Combined
Partner B + Partner A, one program:
int daysLate; // from the classif (daysLate > 0) {
cout << "Fine is owed";
}
else {
cout << "No fine due";
}
Round 4: Combine with &&
Two conditions, joined with &&:
Partner A
Ask: copies checked out?
Fill in a number
Your part: copies > 0
int copies; // what do you recommend?// your part
Partner B
Ask: membership active?
Fill in true or false
Your part: isActive
bool isActive; // what do you recommend?// your part
#include <cstdlib>#include <ctime>
srand(time(0)); // seed onceint roll = rand() % 6 + 1;
// roll is 1 to 6
Why Seed with time(0)?
No seed: same numbers
time(0) changes each run
Seed once, at the top
// BAD: same random numbers every runint roll = rand() % 6 + 1;
// FIX: seed once with time(0)
srand(time(0));
int roll = rand() % 6 + 1;
Rolling One Die
6 equally likely faces
rand() % 6 + 1 picks one
Same odds every time
Dice Roll Game
Goal: simulate n dice rolls
Roll n times in a loop
Each roll: rand() % 6 + 1
Print every roll
srand(time(0));
for (int i = 1; i <= n; i++) {
int roll = rand() % 6 + 1;
std::cout << i << ": " << roll << "\n";
}
Dice Roll: Sample Output
Four rolls, one per line
Numbers come from rand()
Your run will differ
Guess the Random Number
Goal: guess the hidden number
Target: rand() % 100 + 1
do-while: guess once first
Loop until correct
srand(time(0));
int target = rand() % 100 + 1;
int guess, tries = 0;
do {
std::cin >> guess;
tries++;
} while (guess != target);
Win Streak Game
Goal: land 3 heads in a row
Simulates repeated coin flips
Any tails resets the streak
No fixed round limit
srand(time(0));
int streak = 0;
while (streak < 3) {
int flip = rand() % 2;
if (flip == 1) streak++;
else streak = 0;
}
std::cout << "Got 3 heads!\n";
Stone, Scissors, Paper
Goal: win the most rounds
0=stone 1=scissors 2=paper
Best of 5 rounds
srand(time(0));
int wins = 0;
for (int i = 1; i <= 5; i++) {
int cpu = rand() % 3; // pick 0,1,2// if/else decides the winner// wins++ when you beat cpu
}
std::cout << "Wins: " << wins;
Games Recap: Loop Choices
Known count: use for
Unknown count: use while
Guess at least once: do-while
Practice Lab: Times Table
Read a number n
Print n times 1 up to 10
One product per line
// Read n
// Print n x 1 ... n x 10
// One line per row
Step 1: Read the Number
Declare an int n
Prompt the user
Read it with cin
int n;
std::cout << "Number: ";
std::cin >> n;
Step 2: Loop 1 to 10
A for loop, i from 1
Runs while i <= 10
i++ each pass
for (int i = 1; i <= 10; i++) {
// print this row
}
Step 3: Print n times i
Build the row text
n, then i, then n * i
End each with "\n"
for (int i = 1; i <= 10; i++) {
std::cout << n << " x " << i;
std::cout << " = " << n * i << "\n";
}
Deliverable
A working times_table.cpp
Uses one for loop
Works for any n
// times_table.cpp
// one for loop, 1..10
// n x i printed per line
Questions?
Practice Lab Part 2
What You'll Practice
Two more loop games
Password Attempts: while
Math Quiz: for loop
Same loops, new challenge
Password Attempts
Goal: unlock in 3 tries
PIN is fixed, tries limited
while loop, checks tries left
Stops early if correct
constint PIN = 4821;
int guess, tries = 0;
bool ok = false;
while (tries < 3 && !ok) {
std::cin >> guess;
tries++;
ok = (guess == PIN);
}
if (ok) std::cout << "Access OK\n";
elsestd::cout << "Locked out\n";
Math Quiz
Goal: answer 5 math problems
for loop, fixed 5 rounds
Random a + b each round
Tally correct answers
srand(time(0));
int score = 0;
for (int i = 1; i <= 5; i++) {
int a = rand() % 10 + 1;
int b = rand() % 10 + 1;
int ans;
std::cin >> ans;
if (ans == a + b) score++;
}
std::cout << "Score: " << score;
Questions?
Practice Quiz
Practice Quiz: Match the Term
Drag an answer from the outside onto the question it matches — one answer per question.
Write refuel(double& tank) that adds 5.0 to the caller's tank.
voidrefuel(double& tank) {
tank = tank + 5.0;
}
// refuel(t); t changes
Deliverable
Write all three functions
Add printLine and refuel
Run it, show the output
Questions?
Practice Lab Part 2
Minesweeper: The Game
A grid hides some mines
Reveal a cell: safe or boom
Numbers count nearby mines
The Rules
Click a cell to reveal it
A mine ends the game
A number: mines touching it
Win or Lose
Reveal a mine: you lose
Reveal all safe cells: you win
Numbers guide safe guesses
Plan Your Functions
Break the game into pieces
Each piece: one function
Functions call each other
Why Functions First?
Each function: one clear job
Loops and arrays live inside
main() calls them in order
Step 1: Board Constants
SIZE: the board is 6x6
A named constant, not 6
Used everywhere below
constint SIZE = 6;
Step 2: Declare the Arrays
board: {LT}0{GT} mines, count
revealed: has this cell shown?
Both sized SIZE x SIZE
int board[SIZE][SIZE];
bool revealed[SIZE][SIZE];
Step 3: Function Prototypes
Declared above main()
Bodies come after main()
One line per function
voidinitBoard(int b[SIZE][SIZE]);
voidplaceMines(int b[SIZE][SIZE], int n);
intcountAdjacent(int b[SIZE][SIZE],
int r, int c);
voidfillNumbers(int b[SIZE][SIZE]);
Check: Why Prototypes?
main() calls initBoard()
Its body is below main()
What goes wrong without one?
// Without a prototype, the// compiler has not seen// initBoard yet: build error.
Requirements: initBoard
Takes the board array
Every cell starts at 0
Runs once, before anything
Step 4: initBoard, the Loop
Outer loop: pick the row
Inner loop: pick the column
Nested: every cell, once
voidinitBoard(int b[SIZE][SIZE]) {
for (int r = 0; r < SIZE; r++) {
for (int c = 0; c < SIZE; c++) {
// fill this cell next
}
}
}
Step 5: initBoard, Fill It
b[r][c]: this exact cell
0 means no mine, no count
Same shape, every cell
voidinitBoard(int b[SIZE][SIZE]) {
for (int r = 0; r < SIZE; r++)
for (int c = 0; c < SIZE; c++)
b[r][c] = 0;
}
Check: How Many Cells Set?
SIZE is 6
The nested loop runs fully
How many cells get set to 0?
// 6 rows times 6 columns// = 36 cells, each set once
Requirements: placeMines
Takes the board and mine count
Picks random empty cells
Marks each as a mine: -1
Step 6: placeMines, Seed First
srand: makes rand() vary
time(0): a different seed
Call this once, in main()
// in main(), before placing:srand(time(0));
Step 7: placeMines, the Loop
placed: mines so far
Loop while placed < n
Stops once n mines are down
voidplaceMines(int b[SIZE][SIZE], int n) {
int placed = 0;
while (placed < n) {
// pick a cell next
}
}
⚠️ Skipping a used cell is what stops two mines landing in one spot.
Check: What Does -1 Mean?
A cell can be 0, 1-8, or -1
placeMines just set one to -1
What does that cell now hold?
// -1 marks a mine.// 0-8 will later mean:// mines touching that cell.
The 8 Neighbors
Center cell: (1,1)
Check all 8 cells around it
Skip the center itself
Requirements: countAdjacent
Takes the board, one row, col
Checks the 8 cells around it
Returns how many are mines
Step 10: countAdjacent, Setup
count: mines found so far
dr, dc range -1 to 1
That pair covers all 8 cells
intcountAdjacent(int b[SIZE][SIZE],
int r, int c) {
int count = 0;
for (int dr = -1; dr <= 1; dr++) {
// inner loop next
}
return count;
}
Step 11: countAdjacent, Inner Loop
dc also -1 to 1
nr, nc: the neighbor's spot
r+dr, c+dc: one of the 8
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
// check nr, nc next
}
Step 12: countAdjacent, Skip Self
dr==0 and dc==0: that's (r,c)
Not a neighbor of itself
continue: skip this pair
if (dr == 0&& dc == 0) {
continue;
}
Step 13: countAdjacent, Bounds Check
A neighbor may be off-grid
nr, nc must stay 0..SIZE-1
Off the grid: skip it too
if (nr < 0|| nr >= SIZE ||
nc < 0|| nc >= SIZE) {
continue;
}
⚠️ Skipping the bounds check crashes on edge and corner cells.
Step 14: countAdjacent, Tally It
b[nr][nc] == -1: a mine there
Found one: count goes up
After both loops: return count
if (b[nr][nc] == -1) {
count++;
}
Check: Trace a Corner Cell
(0,0) has only 3 neighbors
The other 5 pairs go off-grid
How many pairs get skipped?
// 5 of the 8 (dr, dc) pairs// point off the grid and get// skipped by the bounds check.
Requirements: fillNumbers
Runs after mines are placed
Every safe cell gets its count
Calls countAdjacent for each
Step 15: fillNumbers
Skip cells that are already -1
Otherwise: call countAdjacent
Store the result in that cell
voidfillNumbers(int b[SIZE][SIZE]) {
for (int r = 0; r < SIZE; r++)
for (int c = 0; c < SIZE; c++)
if (b[r][c] != -1)
b[r][c] = countAdjacent(b, r, c);
}
Check: Does Order Matter?
fillNumbers reads other cells
Must mines be placed first?
What if fillNumbers ran first?
// Yes: fillNumbers counts// existing -1 mines. Run it// too early: every count is 0.
Requirements: printBoard
Shows hidden cells as #
Shows revealed cells: number
Never shows an unrevealed mine
Step 16: printBoard, the Loop
Same nested-loop shape again
One character printed per cell
A newline after each row
voidprintBoard(int b[SIZE][SIZE],
bool rv[SIZE][SIZE]) {
for (int r = 0; r < SIZE; r++) {
for (int c = 0; c < SIZE; c++) {
// print one cell next
}
std::cout << "\\n";
}
}
Step 17: printBoard, Hidden Cells
rv[r][c] false: not revealed
Print a # instead of the value
Keeps mines a secret
if (!rv[r][c]) {
std::cout << '#';
}
Step 18: printBoard, Revealed Cells
rv[r][c] true: show the value
A 0 still prints as 0
A safe count like 3 too
else {
std::cout << b[r][c];
}
Check: What Prints First Turn?
No cell is revealed yet
rv is all false at the start
What does printBoard show?
// A full 6x6 grid of #,// since every rv[r][c]// still equals false.
Requirements: revealCell
Marks one cell as revealed
Returns true if it was a mine
main() reacts to that result
Step 19: revealCell
bool return: true means mine
Set revealed first, always
Then check what was under it
boolrevealCell(int b[SIZE][SIZE],
bool rv[SIZE][SIZE],
int r, int c) {
rv[r][c] = true;
return b[r][c] == -1;
}
Check: True or False?
b[2][2] holds a 3
You call revealCell(b,rv,2,2)
What does it return?
// false: b[2][2] is 3,// not -1, so it is not a// mine. The cell is revealed.
Requirements: isWon
Checks every non-mine cell
All revealed: the game is won
One hidden safe cell: not won
Step 20: isWon
Look for one hidden safe cell
Found one: return false
None found: the player won
boolisWon(int b[SIZE][SIZE],
bool rv[SIZE][SIZE]) {
for (int r = 0; r < SIZE; r++)
for (int c = 0; c < SIZE; c++)
if (b[r][c] != -1&&!rv[r][c])
returnfalse;
returntrue;
}
Check: One Cell Left
Every safe cell is revealed
Except one, still hidden
What does isWon return?
// false: that one hidden,// non-mine cell makes the// loop return false right away.
The campus shuttle office wants a simple program that helps riders check stops, distances, and delays. The class splits into 8 teams of one. Each team owns exactly one function. Once every function works on its own, the whole class merges them into a single program: CampusNav.
Student 1: isValidStop()
Signature:boolisValidStop(int stop, int total) Input: a stop index, and the total number of stops Output: true if stop is a real index (0 to total-1) Test cases: isValidStop(3, 5) → true isValidStop(5, 5) → false isValidStop(-1, 5) → false Only if. No loop needed.
boolisValidStop(int stop, int total) {
if (stop < 0) returnfalse;
if (stop >= total) returnfalse;
returntrue;
}
Student 2: nextStop()
Signature:intnextStop(int cur, int total) Input: the current stop index, and the total stops Output: the next stop; wraps to 0 after the last one Test cases: nextStop(2, 5) → 3 nextStop(4, 5) → 0 Only if. No loop needed.
intnextStop(int cur, int total) {
if (cur + 1 >= total) return0;
return cur + 1;
}
Student 3: stopType()
Signature:charstopType(int stop) Input: a stop index, 0 through 9 Output: 'B' for 0-2, 'T' for 3-5, 'W' for 6-9 Test cases: stopType(1) → 'B' stopType(4) → 'T' stopType(8) → 'W' Only if. No loop needed.
charstopType(int stop) {
if (stop < 3) return'B';
if (stop < 6) return'T';
return'W';
}
Student 4: isRushHour()
Signature:boolisRushHour(int hr) Input: the hour, 0 to 23 Output: true during 7-9 AM or 4-6 PM, else false Test cases: isRushHour(8) → true isRushHour(17) → true isRushHour(12) → false Only if. No loop needed.
Signature:inttotalDistance(int dist[], int n) Input: distances between consecutive stops, and n Output: the sum of all n distances Test cases: totalDistance({2,4,3}, 3) → 9 Only while. No if needed.
inttotalDistance(int dist[], int n) {
int sum = 0;
int i = 0;
while (i < n) {
sum += dist[i];
i++;
}
return sum;
}
Student 6: buildCumulative()
Signature:voidbuildCumulative(int dist[], int cum[], int n) Input: distances dist[], an empty array cum[], and n Output: none; cum[i] holds distance to reach stop i Test cases: dist = {2,4,3} → cum = {2,6,9} Only while. No if needed.
voidbuildCumulative(int dist[], int cum[],
int n) {
int i = 0;
int total = 0;
while (i < n) {
total += dist[i];
cum[i] = total;
i++;
}
}
Student 7: reverseRoute()
Signature:voidreverseRoute(int stops[], int n) Input: the route as an array of stop IDs, and n Output: none; reverses stops[] in place for the trip back Test cases: {1,2,3,4} → {4,3,2,1} Only while. No if needed.
voidreverseRoute(int stops[], int n) {
int left = 0, right = n - 1;
while (left < right) {
int temp = stops[left];
stops[left] = stops[right];
stops[right] = temp;
left++; right--;
}
}
Student 8: printCountdown()
Signature:voidprintCountdown(int left) Input: how many stops remain before arrival Output: none; prints a line per stop, down to 1 Test cases: printCountdown(3) prints 3, 2, 1 Only while. No if needed.
voidprintCountdown(int left) {
while (left > 0) {
std::cout << left
<< " stops left\n";
left--;
}
}
CampusNav: All Eight Merge
All 8 functions, one program
main() calls each in order
CampusNav is ready to ride
Deliverable
Write your one function
Test it against its cases
Merge and run CampusNav
Questions?
Practice Quiz
Practice Quiz: Match the Term
Drag an answer from the outside onto the question it matches — one answer per question.
Function
Parameter
Argument
Return Type
The type of value a function sends back
A function's signature declared before its body
Where in the code a variable can be used
Passing a variable so the function can change it
Return type meaning the function sends nothing back
double best = 0;
ifstream in("weather.json");
string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
int p = ln.find("high\": ") + 7;
int q = ln.find(",", p);
best = max(best, stod(ln.substr(p,q-p)));
}
cout << best;
Fast Q2: Coldest Low
Scan every line's low
Keep the smallest so far
No object, just one double
Fast Answer: Coldest Low
Output: 57.9
double best = 999;
ifstream in("weather.json");
string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
int p = ln.find("low\": ") + 6;
int q = ln.find(",", p);
best = min(best, stod(ln.substr(p,q-p)));
}
cout << best;
Fast Q3: Average High
Add up every high value
Divide by how many lines
Two running numbers
Fast Answer: Average High
Output: 93.47
double sum = 0; int n = 0;
ifstream in("weather.json");
string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
int p = ln.find("high\": ") + 7;
int q = ln.find(",", p);
sum += stod(ln.substr(p,q-p)); n++;
}
cout << sum / n;
Fast Q4: Average Low
Add up every low value
Divide by how many lines
Two running numbers
Fast Answer: Average Low
Output: 63.94
double sum = 0; int n = 0;
ifstream in("weather.json");
string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
int p = ln.find("low\": ") + 6;
int q = ln.find(",", p);
sum += stod(ln.substr(p,q-p)); n++;
}
cout << sum / n;
Fast Q5: Sunny Day Count
Check each line's text
Count the word Sunny
Just one counter
Fast Answer: Sunny Day Count
Output: 23
int count = 0;
ifstream in("weather.json");
string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
if (ln.find("Sunny") < ln.size()) count++;
}
cout << count;
Fast Q6: Days Over 95°F
Pull out each line's high
Count ones above 95
Just one counter
Fast Answer: Days Over 95°F
Output: 10
int count = 0;
ifstream in("weather.json");
string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
int p = ln.find("high\": ") + 7;
int q = ln.find(",", p);
if (stod(ln.substr(p,q-p)) > 95.0) count++;
}
cout << count;
Fast Q7: Biggest Swing
Pull high and low per line
Keep the biggest gap
Two finds, one pass
Fast Answer: Biggest Swing
Output: 32.9
double best = 0; ifstream in("weather.json");
string ln; while (getline(in, ln)) {
if (ln.size() < 20) continue;
int p = ln.find("high\": ") + 7;
int q = ln.find(",", p);
double h = stod(ln.substr(p,q-p));
p = ln.find("low\": ")+6; q=ln.find(",",p);
best = max(best, h-stod(ln.substr(p,q-p)));
}
cout << best;
Fast Q8: Mildest High
Scan every line's high
Keep the smallest so far
The opposite of Fast Q1
Fast Answer: Mildest High
Output: 83.5
double best = 999;
ifstream in("weather.json");
string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
int p = ln.find("high\": ") + 7;
int q = ln.find(",", p);
best = min(best, stod(ln.substr(p,q-p)));
}
cout << best;
Fast Q9: Distinct Conditions
Pull out each condition
A set keeps only uniques
No class needed for this
Fast Answer: Distinct Conditions
Output: 3
set<string> seen;
ifstream in("weather.json");
string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
int p = ln.find("condition\": \"") + 14;
int q = ln.find("\"", p);
seen.insert(ln.substr(p,q-p));
}
cout << seen.size();
Fast Q10: Month's Range
Track overall max and min
One pass finds both
high minus low at the end
Fast Answer: Month's Range
Output: 47.0
double hi = 0, lo = 999; int p, q;
ifstream in("weather.json"); string ln;
while (getline(in, ln)) {
if (ln.size() < 20) continue;
p=ln.find("high\": ")+7; q=ln.find(",",p);
hi = max(hi, stod(ln.substr(p,q-p)));
p=ln.find("low\": ")+6; q=ln.find(",",p);
lo = min(lo, stod(ln.substr(p,q-p)));
}
cout << hi - lo;
int main() {
vector<WeatherDay> days =
loadWeather("weather.json");
cout << "Loaded " << days.size()
<< " days" << endl;
// ... then answer each question
}
Q1: Hottest Day
Scan every day's high
Keep the largest so far
Report that day's date
Answer: Hottest Day
Output: 2026-07-11: 104.9
int best = 0;
for (int i = 1; i < days.size(); i++) {
if (days[i].high > days[best].high) {
best = i;
}
}
cout << days[best].date << ": "
<< days[best].high;
Q2: Coldest Night
Scan every day's low
Keep the smallest so far
Report that day's date
Answer: Coldest Night
Output: 2026-07-27: 57.9
int best = 0;
for (int i = 1; i < days.size(); i++) {
if (days[i].low < days[best].low) {
best = i;
}
}
cout << days[best].date << ": "
<< days[best].low;
Q3: Average High for the Month
Add up every high
Divide by the day count
sum / days.size()
Answer: Average High
Output: Avg high: 93.47
double sum = 0;
for (WeatherDay d : days) {
sum += d.high;
}
cout << "Avg high: "
<< sum / days.size();
Q4: Average Low for the Month
Same pattern as average high
Add up every low
Divide by the day count
Answer: Average Low
Output: Avg low: 63.94
double sum = 0;
for (WeatherDay d : days) {
sum += d.low;
}
cout << "Avg low: "
<< sum / days.size();
Q5: How Many Sunny Days?
Check each day's condition
Count only "Sunny"
Report the total
Answer: Sunny Day Count
Output: Sunny days: 23
int count = 0;
for (WeatherDay d : days) {
if (d.condition == "Sunny") {
count++;
}
}
cout << "Sunny days: " << count;
Q6: How Many Days Over 95°F?
Check each day's high
Count ones above 95
A simple threshold check
Answer: Hot Day Count
Output: Hot days: 10
int count = 0;
for (WeatherDay d : days) {
if (d.high > 95.0) {
count++;
}
}
cout << "Hot days: " << count;
Q7: Biggest Day/Night Swing
swing = high minus low
Keep the largest swing
Report that day's date
Answer: Biggest Swing
Output: 2026-07-11: 32.9
int best = 0;
double bestSwing = 0;
for (int i = 0; i < days.size(); i++) {
double s = days[i].high - days[i].low;
if (s > bestSwing) {
bestSwing = s;
best = i;
}
}
cout << days[best].date << ": " << bestSwing;
Q8: Mildest Daytime High
Scan every day's high
Keep the smallest so far
The opposite of Question 1
Answer: Mildest Daytime High
Output: 2026-07-17: 83.5
int best = 0;
for (int i = 1; i < days.size(); i++) {
if (days[i].high < days[best].high) {
best = i;
}
}
cout << days[best].date << ": "
<< days[best].high;
Q9: How Many Distinct Conditions?
Collect every condition seen
A set keeps only
one copy of each
Answer: Distinct Conditions
Output: Conditions: 3
set<string> seen;
for (WeatherDay d : days) {
seen.insert(d.condition);
}
cout << "Conditions: " << seen.size();
Q10: The Month's Full Range
Hottest high minus coldest low
Combines Q1 and Q2
One pass finds both
Answer: Month's Full Range
Output: Range: 47.0
double hi = days[0].high, lo = days[0].low;
for (WeatherDay d : days) {
hi = max(hi, d.high);
lo = min(lo, d.low);
}
cout << "Range: " << hi - lo;
The try block can now throw four custom types. Is there a way to catch any of them without four separate blocks?
Yes: catch (const std::exception&) catches any type derived from it, including all four, but you lose which one unless each what() message already says so.
Questions?
Project Part 3
Why One Project, Not Eleven?
Real code mixes every skill
Each module taught alone
This checks they fit together
Kept small on purpose
The Whole Course, One Vehicle
Use Case: Fleet Health Check
Dealership checks 5 cars
Same drive() call each time
Bad data caught, not crashed
The Vehicle Class
Two variables: speed, fuel
One function: drive()
Everything else calls it
Step 1: Declare the Class
Two variables, nothing else
No function defined yet
classVehicle {
public:
int speed;
int fuel;
};
Check: Why Only Two Variables?
A real car has dozens of details. Why does this class stop at just speed and fuel?
Staying small keeps the focus on how the pieces connect, not on how many fields a class can hold.
Why does C++ split "turn into object code" and "build the final program" into two steps?
It lets several .cpp files compile separately, then link together into one program.
Questions?
Branches: Check the Grid
Reading the Arrow Key
_getch() reads one keypress
An arrow key sends 2 codes
switch picks the direction
int key = _getch();
// 224 = arrow key prefix code
if (key == 224) key = _getch();
switch (key) {
case 72: carRow--; break; // Up
case 80: carRow++; break; // Down
case 75: carCol--; break; // Left
case 77: carCol++; break; // Right
}
Checking the Wall
if/else checks the new spot
Off the grid counts as a wall
Hit a wall? Game over
// off-grid first, then a wall
if (newRow < 0 || newRow >= SIZE ||
newCol < 0 || newCol >= SIZE) {
gameOver = true;
cout << "Crashed!";
} else if (grid[newRow][newCol]=='#') {
gameOver = true;
}
Check: What If No case Matches?
The player presses a letter key, not an arrow key. What does the switch statement do?
Nothing: with no matching case and no default, the car simply does not move that turn.
Word Origin: "Collision"
Latin "com-": together
Latin "laedere": to hurt
Together: "to strike together"
Questions?
Loops: The Game Loop
The Game Loop
while runs until win or crash
Each pass: one keypress, move
The loop condition is the game
while (!gameOver) {
printGrid();
moveCar();
checkCollision();
checkWin();
}
Auto-Drive: Timed Moves
A clock checks elapsed time
Moves once per interval
No keypress needed each time
auto now = chrono::steady_clock::now();
// seconds since the last move
double elapsed =
chrono::duration<double>(now -
lastMoveTime).count();
if (elapsed >= moveIntervalSec) {
lastMoveTime = now;
// ... move in currentDir
}
A. An operating system for lab computers B. A compiled programming language C. A web browser plug-in for forms D. A spreadsheet program for grades
Answer: B
A compiler turns C++ source code directly into machine code before the program runs.
g++ compiles .cpp to .exe
Different from an interpreter
Runs without a browser
Q2
What is the main difference between C and C++?
A. C++ cannot use the basic types of C B. C++ runs only inside a web browser C. C++ removes the functions from C D. C++ adds classes and objects to C
Answer: D
C++ is built on C's core syntax, then adds object-oriented features like classes.
class Car { ... }
C has no classes/objects
C++ keeps C's basic types
Q3
Which function does every C++ program have?
A. main() B. start() C. loop() D. begin()
Answer: A
main() is the required starting point; execution always begins there.
int main() { return 0; }
Only one main() per program
Program starts here first
Q4
After int credits = 15; credits = credits + 3; what is credits?
A. 15 B. 12 C. 18 D. 45
Answer: C
The right side (15 + 3) is computed first, then stored back into credits.
15 + 3 = 18
credits now holds 18
Reassignment, not a new var
Q5
Which declaration correctly stores a GPA such as 3.75?
A. int gpa = 3.75; B. double gpa = 3.75; C. string gpa = "3.75"; D. bool gpa = 3.75;
Answer: B
A GPA has a decimal part, so it needs a floating-point type like double.
int can't hold .75
double gpa = 3.75;
string stores text, not math
Q6
What is the value of 17 % 5?
A. 2 B. 3 C. 7 D. 5
Answer: A
% gives the remainder after division: 17 / 5 = 3 remainder 2.
17 = 5*3 + 2
10 % 3 is 1
% is not division itself
Q7
What does the condition (units >= 12) check?
A. Whether units is exactly 12 B. Whether units is less than 12 C. Whether units is not equal to 12 D. Whether units is 12 or more
Answer: D
>= means greater than or equal to, so 12 itself also satisfies it.
units=12 is true
units=11 is false
units=20 is true
Q8
In if (x > 0) {...} else if (x > 10) {...}, when x is 20, which block runs?
A. Both blocks run in order B. Only the else-if block C. Only the first if block D. Neither block runs
Answer: C
x > 0 is already true, so the if-branch runs and the else-if is never even checked.
20 > 0 is true
else-if only runs if false
Only one branch ever runs
Q9
What does || do in (isFull || isClosed)?
A. True if at least one side is true B. True only if both sides are true C. Flips the value of each side D. Assigns isClosed to isFull
Answer: A
|| is logical OR: the whole expression is true if either side is true.
true || false is true
false || false is false
&& needs BOTH sides true
Q10
How many times does for (int i = 1; i <= 10; i += 2) run its body?
A. 10 times B. 5 times C. 4 times D. 6 times
Answer: B
i steps 1,3,5,7,9, then 11 fails the <=10 test, so the loop stops.
1,3,5,7,9 = 5 values
i+=2 skips every other
11 fails i<=10
Q11
What does while (count < 3) do when count starts at 5?
A. Runs the body 3 times B. Runs the body 5 times C. Skips the body entirely D. Runs the body forever
Answer: C
A while loop checks its condition before running; 5<3 is already false.
5 < 3 is false
Checked before first run
Body never executes once
Q12
What is the difference between break and continue inside a loop?
A. break ends the program, continue pauses it B. break skips one pass, continue ends the loop C. break and continue both end the loop at once D. break ends the loop, continue skips one pass
Answer: D
break exits the loop completely; continue just jumps to the next iteration.
break: stop looping now
continue: skip to next i
Neither ends the program
Q13
After int scores[4] = {90, 85, 70, 65}; what is scores[3]?
A. 70 B. 65 C. 90 D. 85
Answer: B
Arrays are zero-indexed, so index 3 is the 4th element.
scores[0] is 90
scores[3] is 65
4 elements, indices 0-3
Q14
What does v.size() return for vector<int> v = {3, 8, 1};?
A. 3 B. 8 C. 1 D. 2
Answer: A
size() returns how many elements the vector currently holds, not their values.
3 elements were listed
v.size() returns 3
Not the value of an element
Q15
Why does int grades[3]; grades[3] = 70; cause a problem?
A. 70 is too large a value B. The array name is misspelled C. Index 3 is outside the array D. The array must hold doubles
Answer: C
A 3-element array has valid indices 0, 1, 2 only; index 3 is out of bounds.
Valid: grades[0..2]
grades[3] is out of bounds
C++ won't stop you at runtime
Q16
What does void printRoster(string names[], int n) return?
A. No value at all B. A string value C. An int value D. An array of names
Answer: A
void means the function performs an action but returns nothing to the caller.
void = no return value
int would return a number
Still can print/do work
Q17
Given double average(int a, int b), which call is valid?
A. average(2.5, 3); B. average("80","90"); C. average(80); D. average(80, 90);
Answer: D
The function needs exactly two int arguments; the other calls use wrong types or counts.
average(80, 90) matches
Strings won't convert to int
One argument isn't enough
Q18
What happens to a variable declared inside a function when the function ends?
A. It keeps its value for main to use B. It is destroyed with its value C. It becomes a global variable D. It is returned to main automatically
Answer: B
Local variables only exist for the lifetime of the function call; they're gone after it returns.
Local scope ends with func
main() can't see it after
Not saved for next call
Q19
Write a C++ function void countdown(int n) that prints the numbers from n down to 1, one per line. Use a loop.
Answer
voidcountdown(int n) {
for (int i = n; i >= 1; i--) {
cout << i << endl;
}
}
Q20
Write a C++ function void trafficLight(string color) that prints "Drive" if color is "green" and "Stop" if color is "red". Use an if/else.
The summary sheet is the one reference allowed during the real exam: no laptops, phones, or separate notes. Same syllabus policy you confirmed in Lab 1 applies here too.
Lab 1
Lab 1: Getting Started
Answer in your own words
A few sentences per question
No prior experience needed
Question
What do you think a "computer program" actually is?
Answer
Something a computer runs using its internal components, where the code gets read by the hardware.
Question
Have you ever used an app or website that didn't work right? What happened?
Answer
A Minecraft mod turned the screen black. Only one specific, worse-performing setting fixed it, so the mod got removed.
Question
What's different about talking to a person versus "talking" to a computer?
Answer
A person shows body language and tone. Talking to a computer is more like talking at it, since you only get text back.
Question
If you had to tell a computer, step by step, how to make a sandwich, what would you need to say?
Answer
Every step, explicitly: get plates and bread, spread the filling, then place one slice on top so they touch.
Question
Just from the word itself, what do you think "debugging" means?
Answer
Removing bugs from a program so it functions correctly.
Question
Why do you think computers need such exact, precise instructions?
Answer
It's like how there, their, and they're sound the same but mean different things. A computer can't guess which one is meant.
Question
Have you ever followed confusing instructions or a recipe? What made them hard to follow?
Answer
Helped build a PC over the summer; ports and wires were named differently across manuals, and some parts had no instructions at all.
Question
Name one app you use every day. What do you think it's doing behind the scenes?
Answer
Reddit: it tracks votes, calculates karma, lets people post, and sorts content by popularity and growth potential.
Question
If a program you wrote didn't do what you expected, how would you start figuring out why?
Answer
Read the compiler's error output line by line, then double-check the logic by testing again.
Question
What's one thing you'd like to be able to build by the end of this course?
Answer
Card games are a hobby, so building a virtual version of one would be fun to try.
Question
What applications are low-level languages used for today?
Answer
Anything close to the hardware or needing top speed: operating-system kernels, device drivers, and embedded chips.
Example: the Linux kernel and Arduino firmware are written in C.
Question
Why do run-time errors occur?
Answer
The code compiled fine, but while running it reaches a case it cannot handle, like bad input or dividing by zero.
Example: 10 / n compiles, then crashes when the user types n = 0.
Question
What is the difference between an error and a bug?
Answer
The bug is the mistake in your code. The error is what the computer reports when that bug runs. Fix the bug, the error goes away.
Example: = instead of == is the bug; the wrong output is the error.
Question
Why was the original language named "C"?
Answer
It followed a Bell Labs language called B, so Dennis Ritchie named the next step C, the next letter.
Example: the lineage is BCPL to B to C, and later C++ (one past C).
Please read the course syllabus and ask any questions; once completed, confirm you have read the syllabus.
"++" is the increment operator: one better than C. Stroustrup built it at Bell Labs (AT&T) starting in 1979, released it publicly in 1985.
Covered in: Module 1
Question
Stable, but evolving?
Why avoid unportable code?
Why not easier for beginners?
Answer
Stable means old code keeps compiling as new features are added. Portability and full power mattered more than an easy on-ramp.
Covered in: Module 1
Question
Abstraction vs. OOP?
What is a class?
Answer
Data abstraction hides how a type is built behind a clean interface. OOP adds inheritance and polymorphism on top. A class is C++'s tool for both.
Covered in: Module 7
Question
Hardest goal to balance?
What do safe/efficient mean?
Answer
Safe means hard to misuse; efficient means fast and low-memory. The two often pull against each other, which is why balancing them is hardest.
Covered in: Module 6–7
Question
What is type-safe linkage?
What does overloading do?
Answer
Type-safe linkage lets the compiler catch mismatched calls across separately-compiled files. Overloading lets one function name serve many types.
Covered in: Module 6
Question
Why add multiple inheritance?
What's an abstract class?
Answer
Single inheritance only extends one parent; some designs need two. An abstract class defines an interface with no full implementation of its own.
Covered in: Module 8
Question
Why skip these in the paper?
What are they?
Answer
Both were still being designed in 1989, so the paper only covers shipped C++ 2.0 features. Exceptions handle runtime errors; templates write one type for many kinds of data.
Covered in: Module 11
Question
What's a static member?
What does operator-> do?
Answer
A static member belongs to the class, not to any one object. operator-> lets a custom "smart pointer" type use ordinary pointer syntax.
Covered in: Module 7–8
Question
Has C++ changed since 1989?
Why is this so hard to read?
Answer
Yes, hugely; C++11 through C++23 each added major features. This paper is a design memo for other language experts, not a tutorial. Read it for the "why," not to fully understand every term yet.
Q1. Briefly describe a situation where if/else or switch is needed to decide an outcome.
Answer
A login screen needs if/else to decide whether to grant access, show an error, or lock the account, since the outcome depends entirely on which condition is true.
Question
Q2. Why would you prefer switch instead of if/else statements?
Answer
A switch reads more clearly when one variable is compared against many exact values, since it avoids repeating that variable's name in every single condition.
Question
Q3. What does "break" do?
Answer
break exits the switch statement right away, so execution jumps past the closing brace instead of falling through into the next case's code.
Question
Q4. What is the "default" statement used for in switches?
Answer
default runs when none of the listed case values match, giving the program a defined behavior for input it did not explicitly plan for.
Question
Q5. Briefly describe what this code snippet does.
if (isRaining || isSnowing) {
std::cout << "bring an umbrella";
} else {
std::cout << "you don't need one!";
}
Answer
It checks whether it is raining or snowing. If either is true, it prints a message recommending an umbrella; if both are false, it prints a message saying one is not needed.
Lab 2
Lab 2: Branches
Write and test working code
Question: 25 pts
Ask the user about weather
Rain: take an umbrella
Cold: wear a jacket
Hot: bring water
Else: you're good to go
Use if / else if / else
Answer
string w;
cin >> w;
if (w == "rain") cout << "Take umbrella.";
else if (w == "cold") cout << "Wear jacket.";
else if (w == "hot") cout << "Bring water.";
else cout << "You're good to go!";
int score = 85;
if (score >= 60) {
cout << "You passed.";
}
else if (score >= 80) {
cout << "B or higher.";
}
else {
cout << "Did not pass.";
}
Answer
// 60 is checked FIRST, so it// prints "passed" and skips// the B-or-higher checkif (score >= 80)
cout << "B or higher.";
else if (score >= 60)
cout << "You passed.";
else
cout << "Did not pass.";
Homework 3
Homework 3: Branches & Loops
Answer in complete sentences
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Q1. What kind of conditional statement is best to use when you have many exact-value outcomes to check against a single variable?
Q2. What is the difference between writing "else if" and writing a separate, standalone "if" statement right after the first one?
Q3. What happens if you forget to write "break" inside a case in a switch statement?
Q4. Can a switch statement compare a range of values, like score >= 60? Why or why not?
Q5. There is a problem in the following code snippet, what is it?
int score = 70;
if (score >= 90) {
string grade = "A";
}
cout << grade;
Q6. What kind of loop is best to use when you know exactly how many times you want to repeat a block of code?
Q7. What kind of loop will always run at least once?
Q8. What happens if you write a loop with a condition that never becomes false?
Q9. How many if-else statements can you have in a loop?
Q10. There is a problem in the following code snippet, what is it?
for (int i = 0; i < 3; i++) {
int x = i * 10;
}
cout << x;
Lab 3
Lab 3: Conditions & Loops
Write and test working code
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Question: 25 pts
Ask for 5 grades, one at a time. Check if each is 60 or higher. Print how many passed.
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Q1. What's the difference between a fixed-size array and a vector?
Q2. Why does an array index start at 0 instead of 1?
Q3. What happens if you access an array index that's out of bounds?
Q4. What method adds a new element to the end of a vector?
Q5. Why use a vector instead of an array when the car count changes?
Q6. What's the difference between a parameter and an argument?
Q7. Can a function return more than one value directly? Why or why not?
Q8. What's the scope of a variable declared inside a function?
Q9. Why use a function instead of copying the same code three times?
Q10. What's a function prototype, and why declare one?
Lab 4
Lab 4: Arrays & Functions
Write and test working code
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Question 1: 10 pts
Declare an array of 5 car prices (double). Print each one with a loop.
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Q1. What's the difference between a class and an object?
Q2. What's encapsulation, and why keep a class's data private?
Q3. What's a constructor, and when does it run?
Q4. What's the difference between a public and a private member?
Q5. What does "this" refer to inside a member function?
Q6. What's inheritance, in one sentence?
Q7. What's the difference between public and protected inheritance?
Q8. Can a derived class access a private base class member directly?
Q9. What's a destructor, and when does it run?
Q10. Why use inheritance instead of copying code into a new class?
Lab 5
Lab 5: Classes & Inheritance
Write and test working code
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Q1. What's a virtual function, and why use one?
Q2. What happens if a base class pointer calls a non-virtual function?
Q3. What's an abstract class, and how do you create one?
Q4. Can you create an object of an abstract class directly?
Q5. What's the difference between cin and cout?
Q6. What does ofstream let you do?
Q7. What happens if ifstream opens a file that doesn't exist?
Q8. What's the difference between >> and getline()?
Q9. Why use fixed and setprecision together?
Q10. What does a stringstream let you do with a line of text?
Lab 6
Lab 6: Polymorphism & Streams
Write and test working code
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Q1. What's an exception, in one sentence?
Q2. What's the difference between throw, try, and catch?
Q3. What happens if a thrown exception is never caught?
Q4. What's std::exception, and why catch it by reference?
Q5. What's a custom exception class, and why write one?
Q6. What data structure holds GridRunner's grid, and why that one?
Q7. How does GridRunner detect a wall or edge collision?
Q8. Why are the car's start and destination chosen randomly?
Q9. What does making Obstacle's onHit() virtual actually buy you?
Q10. Describe one change you'd make to GridRunner, and why.
Lab 7
Lab 7: Exceptions & Semester Project
Write and test working code
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.
Question 1: 10 pts
Write a BadPrice class inheriting from std::exception.
class Wall : public Obstacle {
public:
void onHit() override {
cout << "Crashed into wall!";
}
};
The Car & Grid Classes
Car: just row and col
Grid: size and the 2D cells
class Car {
public:
int row, col;
};
class Grid {
public:
int size;
vector<vector<char>> cells;
};
Polymorphism: One Call, Many Forms
obstacles: any Obstacle type
onHit() picks the real type
vector<Obstacle*> obstacles;
obstacles.push_back(new Wall());
for (auto* o : obstacles) {
o->onHit();
}
Exceptions: A Bad Grid Size
BadGridSize names the problem
Caught before the game starts
class BadGridSize : public exception {
public:
const char* what() const {
return "Grid size must be 5-50";
}
};
Putting It Together: main.cpp
Build the grid, place the car
Loop until a win or a crash
int main() {
srand(time(0));
Grid grid(20);
Car car;
placeRandom(car, grid);
while (!gameOver) {
printGrid(grid, car);
handleInput(car, grid);
}
}
Final Project: Submission
Your extended GridRunner code
A short README of your own
Points: TBD. Due: TBD (PT)
Submit via Canvas. Groups OK, but by submitting you're confirming you personally understand the work. AI is fine to use, but clearly state which parts used AI and which parts you did without it.