Pacific Seal

Welcome
Introduction to Computer Science


Course: COMP 051 — 02
Term: Fall 2026
Time: 3:00 PM – 4:45 PM on Tuesday, Thursday
Location: Baun Hall 214
Office Hours: Tuesday, Thursday 1:30–2:30 PM, CTC 117 or Zoom

Week Meeting Dates (TR) Topic Notes Assignment Domain
Week 1 Aug 25, 27 Course Overview, What is a Program? Lab 1 / HW 1 University
Week 2 Sep 1, 3 Variables and Basic I/O Labor Day is Mon, Sep 7
Week 3 Sep 8, 10 Branches HW 2 / Lab 2
Week 4 Sep 15, 17 Loops
Week 5 Sep 22, 24 Arrays & Vectors HW 3 / Lab 3
Week 6 Sep 29, Oct 1 User Defined Functions Fall Student Break is Fri, Oct 2 Automotive
Week 7 Oct 6, 8 Objects and Classes Lab/HW 4
Week 8 Oct 13, 15 Inheritance Midterm Exam: Oct. 15th
Week 9 Oct 20, 22 Data Streams Lab/HW 5
Week 10 Oct 27, 29 Polymorphism & Virtual Functions
Week 11 Nov 3, 5 Exceptions Lab/HW 6 Automotive
Week 12 Nov 10, 12 Semester Review and Project
Week 13 Nov 17, 19 Semester Review Lab/HW 7
Week 14 Nov 24 Finals Preparation No class Nov 26 (Thanksgiving)
Week 15 Dec 1, 3 Final Review Project Showcase: Fri, Dec 4, 2–3:15 PM, Makerspace Final project presentations or quiz
Week 16 Dec 10 Final Exam: Dec. 10th, 3–5PM in Baun 214

Why This Matters

  • From ENIAC to C++ in decades
  • C++ grew out of C and UNIX
  • Still runs OSes and browsers
1945ENIAC – one of thefirst general-purpose electronic computers1969UNIX created at Bell Labs(Ritchie & Thompson)1972C language (Dennis Ritchie,Bell Labs)1983“C with Classes”renamed C++ (Bjarne Stroustrup)TodayC++ still powers OS kernels,browsers, and games

Where You Already Use C++

Web BrowsersVideo GamesSpace MissionsSelf-DrivingPhoto & VideoC++

C++ Behind Everyday Apps

Chromium Powers the Chrome browser Web Browsers
Unreal Engine Built Fortnite & more Video Games
Ingenuity NASA's Mars helicopter Space Missions

Sources: Wikipedia, Chromium, Epic Games, Unreal Engine, NASA/JPL, Ingenuity

Image 1 Image 2 Image 3 Image 4 Image 5 Image 6

Before Operating Systems

  • 1940s–1950s: switches, punch cards, raw code
  • One program controlled the whole machine
  • Devices, stop/start handled manually
  • Very slow, error-prone
Early computers with punch cards

Bell Labs and AT&T

  • 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.
Bell Labs/AT&T

History of C/C++

  • Early 1970s at Bell Labs (Dennis Ritchie)
  • System programming for UNIX
(add: Bell Labs / UNIX)
(add: portability/hardware)

Why C?

  • Close to hardware, portable
  • Small runtime, fast compilation

Questions?

From Code to Machine

C SourceCompilerAssemblyAssemblerMachine Code

C Code


    int totalCredits(int a, int b) {
        return a + b;
    }
      
C SourceCompilerAssemblyAssemblerMachine Code

Compiler


    $ gcc -S totalCredits.c -o totalCredits.s
      

Translates C source into assembly

C SourceCompilerAssemblyAssemblerMachine Code

Assembly


    totalCredits:
        mov eax, edi    ; a into eax
        add eax, esi    ; add b to eax
        ret             ; return result
      

x86-64 System V calling convention

C SourceCompilerAssemblyAssemblerMachine Code

Assembler


    $ as totalCredits.s -o totalCredits.o
      

Assembles into machine code (object file)

C SourceCompilerAssemblyAssemblerMachine Code

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

Connecting to registrarsystem...Enrollment confirmed!

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++
(add: Stroustrup / early C++)

C Is a Subset of C++

C++classes, templatesCstructs, printf

Every valid C program is (almost) valid C++

(add: OOP diagram)

Why C++?

  • Object‑oriented programming
  • Performance with abstraction

Quick Check

Which is a subset of the other?

  1. C++ is a subset of C
  2. C is a subset of C++
  3. They are unrelated

B. C is a subset of C++.

Questions?

I/O & Variables

> std::cin >> credits;Credits enrolled? 15

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?

  1. << sends output
  2. >> reads input
  3. == 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
x1957op:=C++int xA short history

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
credits15Variables = labeled memory

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
📜Latinvariare, to change💻Todaya value that can vary

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"
📜Latindeclarare, make clear💻Todayintroduce a name + type

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
📜Latininitium, a beginning💻Todayset the starting value

Quick Check

What's the difference: declare vs. initialize?

  1. No difference at all
  2. Initialize also sets a value
  3. 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 =
📜Latinassignare, to mark out💻Todaystore a value in a slot

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
📜Latinre-, again💻Todaygive it a new value

Quick Check

What happens when you reassign a variable?

  1. A new variable is created
  2. The old value is overwritten
  3. 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
int18boolTDifferent types, different sizes

Word Origin: "Type"

  • Greek: typos, a mark/model
  • Defines a value's shape
  • int, double, char, bool...
📜Greektypos, a mark/model💻Todaywhat kind of data it is

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?

  1. unitsCompleted
  2. cumulativeGPA
  3. 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

Quick Check

Which university variable fits double best?

  1. tuitionBalance
  2. semesterCount
  3. isFullTime

A. tuitionBalance needs cents, a decimal value.

Code It: Tuition Balance

  • Declare balance
  • Set it to 450.75
  • How would you write it?

    double bal=450.75;

float vs. double

  • float: less precision
  • double: more precision
  • This course uses double
float4Bdouble8BBytes of memory used

Type: char

  • One single character
  • Wrapped in single quotes
  • e.g., a grade letter

    char grade = 'A';
    char initial = 'S';

Quick Check

Which is a valid char value?

  1. 'A'
  2. "A"
  3. A

A. char uses single quotes, one character.

Quick Check

Which university variable fits char best?

  1. letterGrade
  2. studentID
  3. creditHours

A. letterGrade is one character, like 'A'.

Code It: Letter Grade

  • Declare letterGrade
  • Set it to 'B'
  • How would you write it?

    char letterGrade='B';

Type: bool

  • Only true or false
  • Named after George Boole
  • e.g., isEnrolled, passed

    bool isEnrolled=true;
    bool passed = false;

bool in Practice

  • Stores yes/no answers
  • Used a lot in decisions
  • if (isEnrolled) later on

    bool ok=grade>=60;
    cout << ok; // 1

Quick Check

Which university variable fits bool best?

  1. isEnrolled
  2. major
  3. unitsTaken

A. isEnrolled is only ever true or false.

Code It: Is Enrolled

  • Declare isEnrolled
  • Set it to true
  • How would you write it?

    bool isEnrolled=true;

Type: string

  • Text: words, sentences
  • Wrapped in double quotes
  • Needs #include <string>

    #include <string>
    string name="Alice";

What Is +=?

  • Shorthand for reassignment
  • x += 5 means x = x + 5
  • Also -=, *=, /=, %=

    int x = 10;
    x += 5; // x = x + 5
    // x is now 15

Compound Assignment Ops

  • += add and assign
  • -= subtract and assign
  • *=, /=, %= work the same

    int credits = 12;
    credits += 3; // 15
    credits -= 2; // 13

Quick Check

What does x += 5; do?

  1. Sets x to 5
  2. Sets x to x + 5
  3. Compares x to 5

B. x += 5; reassigns x to x + 5.

Code It: Running Total

  • Declare total = 0 (int)
  • Add 10 using +=
  • Print total
  • How would you write it?

    int total = 0;
    total += 10;
    cout << total;

Code It: Countdown Seats

  • Declare seats = 5 (int)
  • Subtract 1 using -=
  • Print seats
  • How would you write it?

    int seats = 5;
    seats -= 1;
    cout << seats;

string in Practice

  • Store any length of text
  • Can combine with +
  • e.g., building a message

    string first = "Ana";
    string last = "Lee";
    string full = first;
    full += " ";
    full += last;

Quick Check

Which university variable fits string best?

  1. studentName
  2. birthYear
  3. isGraduate

A. studentName holds text, a person's name.

Code It: Student Name

  • Declare studentName
  • Set it to "Maria"
  • How would you write it?

    string studentName =
        "Maria";

Quick Check

Which type would you use for a course name?

  1. int
  2. bool
  3. string

C. string stores text like a course name.

Naming Rules

  • Start with a letter or _
  • No spaces, no dashes
  • Case-sensitive: age ≠ Age

    int age;   // valid
    int _temp; // valid
    int 2fast; // invalid

Naming Conventions

  • Use descriptive names
  • camelCase in C++
  • Not just x, y, z

    int studentCount;
    int sc;

Case Styles in C++

  • camelCase: variables
  • PascalCase: class names
  • ALL_CAPS: constants

    int studentAge;
    class Student {};
    const int MAX_A=100;

Choosing Good Names

  • Be specific, not generic
  • Avoid cryptic short names
  • Loop counters (i, j) OK

    int d; // unclear
    int daysLeft;

Quick Check

Which naming style fits a class name?

  1. camelCase
  2. PascalCase
  3. ALL_CAPS

B. PascalCase: Capitalize each word, e.g. Student.

Quick Check

Which variable name is invalid in C++?

  1. studentAge
  2. _temp
  3. 2ndTry

C. Names can't start with a digit.

Code It: A Clearer Name

  • Rename a bad variable: d
  • Make it clear and descriptive
  • How would you write it?

    int daysLeft;

Why Comment Code?

  • Explains why, not just what
  • Helps future you and others
  • Ignored by the compiler

    // A student's GPA
    double gpa = 3.8;

Single-Line Comments

  • Starts with //
  • Runs to end of line
  • Best for short notes

    int credits = 15;

Multi-Line Comments

  • Starts /* ends */
  • Spans several lines
  • Good for longer notes

    /* Explains the grade
       calc below */

Quick Check

Which starts a single-line comment?

  1. //
  2. /* */
  3. #

A. // starts a comment to end of line.

Code It: Add a Comment

  • credits = 15
  • Add a note: units
  • How would you write it?

    // units
    int credits = 15;

Multiple Variables, One Line

  • Same type, comma-separated
  • Each still needs a value
  • Saves a little typing

    int hw1=10, hw2=8;

Swapping Two Variables

  • a = 5, b = 9
  • Need a 3rd, temp variable
  • How would you swap them?

    int a = 5, b = 9;
    int temp = a;
    a = b;
    b = temp;
    // now a=9, b=5

Word Origin: "Constant"

  • Latin: constare, stand firm
  • const means never reassigned
  • Compiler enforces this
📜Latinconstare, stand firm💻Todaya value that never changes

Constants: const

  • A variable that can't change
  • Set once, at initialization
  • Protects a fixed value

    const double PI=3.14;
    // PI = 3; // error!

Quick Check

What does the const keyword do?

  1. Deletes the variable
  2. Prevents reassignment
  3. Makes it a string

B. const locks the value after initialization.

Code It: Lock a Constant

  • Declare MAX, an int
  • Lock it at 30, never changes
  • How would you write it?

    const int MAX = 30;

Try It Yourself

  • Open onlinegdb.com
  • Pick "C++" as the language
  • Type, then click Run
Run▶onlinegdb.com/online_c++_compiler

Try It: Declare & Print

  • Declare an int named age
  • Assign it your age
  • Print it with cout
  • Run it at onlinegdb.com

    int age;
    age = 20;
    cout << age;

Try It: Initialize a double

  • Initialize a double gpa
  • Give it a value like 3.5
  • Print it with cout
  • Run it at onlinegdb.com

    double gpa = 3.5;
    cout << gpa;

Try It: Reassign a Variable

  • Initialize credits to 12
  • Reassign it to 15
  • Print it before and after
  • Run it at onlinegdb.com

    int credits = 12;
    cout << credits;
    credits = 15;
    cout << credits;

Try It: Swap Two Variables

  • Declare a = 3, b = 7
  • Swap them with a temp var
  • Print a and b after
  • Run it at onlinegdb.com

    int a = 3, b = 7;
    int temp = a;
    a = b;
    b = temp;
    cout << a << b;

Try It: Choose the Right Type

  • Declare name (string)
  • Declare gpa (double)
  • Declare passed (bool)
  • Run it at onlinegdb.com

    string name = "Sam";
    double gpa = 3.2;
    bool passed = true;

Try It: Build a Message

  • Store first, last (string)
  • Combine with +
  • Print the full name
  • Run it at onlinegdb.com

    string first = "Sam";
    string last = "Ray";
    cout << first + last;

Reserved Words

  • Keywords the language owns
  • int, class, return, etc.
  • Can't be used as names

    int int=5; //error!
    int total=5; //fine

Uninitialized Variables

  • Declared, but no value set
  • Holds leftover "garbage"
  • Always initialize first

    int credits;
    cout << credits;
    // unpredictable!

Types: Quick Summary

  • int: whole numbers
  • double: decimals
  • char, bool, string: rest
int5boolTchrAOne name, one type, one value

Try It: Compute an Average

  • Declare x, y (int)
  • Declare a (double)
  • Print a = (x+y)/2.0
  • Run it at onlinegdb.com

    int x = 10, y = 8;
    double a=(x+y)/2.0;
    cout << a;

Quick Check

Which line only DECLARES a variable, no value?

  1. int x = 5;
  2. int x;
  3. x = 5;

B. int x; declares it with no value yet.

5 + 3 = 810 / 3 = 310 % 3 = 1operators + - * / %

Expressions

int hw1 = 10, hw2 = 3;
    int sum = hw1 + hw2;
    int product = hw1 * hw2;
    double avg = (hw1 + hw2) / 2.0;

Quick Check

What does the % operator return?

  1. A percentage
  2. The remainder (modulo)
  3. A random number

B. The remainder of division.

Questions?

Practice Quiz

Practice Quiz: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question.

Program
Algorithm
Compiler
Syntax Error
A mistake that prevents code from compiling
Human-readable code before compiling
App for writing, running, and debugging code
Finding and fixing errors in code
Instructions a CPU can run directly
A set of instructions a computer executes
An ordered sequence of steps that solves a problem
Turns C++ source into machine code
Source Code
IDE
Debugging
Machine Code

Questions?

Where We Are: Module 1

  • Module 1 done: C++ basics
  • Next: Variables & I/O

Why This Matters

  • Named memory predates FORTRAN
  • Typing traces back to ALGOL
  • C++ types inherited from C
1949EDSAC – one of thefirst computers with named memory1957FORTRAN (IBM) – firsthigh-level language with named variables1958ALGOL 58 adds block-scoped,typed variable declarations1972C (Bell Labs) – statictyping that C++ inherits directlyTodayEvery C++ variable has oneof a fixed set of native types

Basic I/O with Types

Where I/O Comes From & Goes To

  • Your code sits in the middle
  • Green in, blue out
  • 4 places data can flow
TerminalWebsiteAnother PCFileCodeInputOutput

cout: Printing a Value

  • cout prints to the screen
  • << is the insertion operator
  • endl ends the current line
#include <iostream>

std::cout << pages;
std::cout << std::endl;

cout: Printing a Value

#include <iostream>

std::cout << pages;
std::cout << std::endl;

cin: Reading a Value

  • cin reads keyboard input
  • >> is the extraction operator
  • The value fills a variable
#include <iostream>

std::cin >> pages;

cin: Reading a Value

#include <iostream>

std::cin >> pages;

endl vs. \n

  • Both end the current line
  • endl also flushes the buffer
  • \n is usually a bit faster
#include <iostream>

std::cout << pages;
std::cout << std::endl;
std::cout << pages << "\n";

endl vs. \n

#include <iostream>

std::cout << pages;
std::cout << std::endl;
std::cout << pages << "\n";

The Output Buffer

  • Program doesn't wait on I/O
  • Output waits in a buffer
  • endl flushes it now
  • \n leaves it buffered
cout << pages Buffer Screen Screen endl: flush now "\n": waits Buffer also flushes when it fills up, or when the program ends

Chaining Several Reads

  • One cin can read many values
  • >> again for the next variable
  • We'll reuse this all module
#include <iostream>

std::cin >> pages >> copies;

Chaining Several Reads

#include <iostream>

std::cin >> pages >> copies;

Practice: Read & Print a Value

  • Read pages from input
  • Print it back with a label
  • Use cin, then cout
#include <iostream>

// TODO: std::cin >> pages;
// TODO: std::cout with a label
Pages: 45

Questions?

History of Data Types

A Short History of Types

  • 1957: FORTRAN adds named data
  • 1958: ALGOL adds typed vars
  • Every language kept the idea
1949EDSAC – one of thefirst computers with named memory1957FORTRAN (IBM) – firsthigh-level language with named variables1958ALGOL 58 adds block-scoped,typed variable declarations1972C (Bell Labs) – statictyping that C++ inherits directlyTodayEvery C++ variable has oneof a fixed set of native types

What Is a Data Type?

  • Sets the box's size & shape
  • Decides what values fit inside
  • int, float, char, bool...
type?What shape is the box?

Why Do We Need Types?

  • Fits data in the right size
  • Only legal operations allowed
  • Bugs are caught before running
Right SizeRight RulesCatch BugsClear CodeWhyTypes?

Why the Printer Needs Types

  • Pages in a job: a whole number
  • Cost per page: needs cents
  • Printer busy: yes or no
pages45cost0.08busytrueDifferent data, different types

The Native C++ Types

  • Seven built-in kinds of data
  • Each has its own size & range
  • Pick the type that fits
intshortlongfloatdoublecharboolC++Types

Type Ranges & Examples

TypeExampleMinMaxComment
intint pages;-2,147,483,6482,147,483,647Most common whole number
shortshort copiesRequested;-32,76832,767Smaller range, saves memory
longlong printerSerial;-2,147,483,648 or less2,147,483,647 or moreFor very large whole numbers
floatfloat toner = 85.5f;±3.4×1038~7 digits preciseDecimal, needs f suffix
doubledouble costPerPage = 0.08;±1.8×10308~15 digits preciseDecimal, default precision
charchar size = 'L';-128127One character or small number
boolbool busy = true;falsetrueOnly two values

⚠️ long is only guaranteed to match int's range; many systems (Linux/Mac) give it far more.

Today: Programming a Printer

  • You now know all seven types
  • Time to put them to work
  • Every example: a real printer
🖨️University Printer

const: A Value That Can't Change

  • const locks the value in place
  • Reassigning it is an error
  • Good for a fixed max copies
const int MAX_COPIES = 5;
// MAX_COPIES = 8;  // error

const: A Value That Can't Change

const int MAX_COPIES = 5;
// MAX_COPIES = 8;  // error

const Fits: MAX_COPIES

  • A fixed rule, set once
  • Never changes at runtime
  • Perfect for const
🔒MAX_COPIES = 5Locked for the whole program

const Doesn't Fit: pagesLeft

  • Drops as pages print
  • Needs reassignment each time
  • const would cause an error
pagesLeft as printing happens531

Practice: Set the Copy Limit

  • Max copies allowed: 5
  • Use const so it can't change
  • Name it MAX_COPIES
// TODO: declare MAX_COPIES
// value: 5, must be const
🔒MAX_COPIES = 5

Type Ranges (Approximate)

  • Ranges vary by system
  • Typical values, not guarantees
  • Bigger types, bigger ranges
TypeApprox. Range
short-32K to 32K
int-2.1B to 2.1B
longat least -2.1B to 2.1B
unsigned int0 to 4.3B
float±3.4×1038, ~7 digits
double±1.8×10308, ~15 digits
char-128 to 127
booltrue or false only

Questions?

Whole Numbers

int: The Default Choice

  • Whole numbers, no decimals
  • 4 bytes on most systems
  • The safe default choice
#include <iostream>

int pages;
std::cin >> pages;
std::cout << pages;
std::cout << std::endl;

int: The Default Choice

#include <iostream>

int pages;
std::cin >> pages;
std::cout << pages;
std::cout << std::endl;

int: Fits or Not?

Fits

  • 45
  • -12
  • 1000

 

Does Not Fit

  • 3.14 (a decimal)
  • "A4" (that's text)
  • 'A' (that's a char)

short & long: Other Sizes

  • short: smaller range, less RAM
  • long: bigger range than int
  • Pick based on the value range
#include <iostream>

short copiesRequested;
std::cin >> copiesRequested;
long printerSerial;
std::cin >> printerSerial;

short & long: Other Sizes

#include <iostream>

short copiesRequested;
std::cin >> copiesRequested;
long printerSerial;
std::cin >> printerSerial;

short & long: Fits or Not?

Fits

  • short: 100
  • long: 5000000000

 

Does Not Fit

  • short: 90000 (too big)
  • long: 3.14 (a decimal)

unsigned: Only Positive

  • No negative values allowed
  • Doubles the positive range
  • Great fit for counts
#include <iostream>

unsigned int jobsQueued;
std::cin >> jobsQueued;

unsigned: Only Positive

#include <iostream>

unsigned int jobsQueued;
std::cin >> jobsQueued;

unsigned: Fits or Not?

Fits

  • 0
  • 100
  • 4000000

 

Does Not Fit

  • -5 (negative)
  • 3.14 (a decimal)

sizeof: How Big Is It?

  • sizeof returns bytes used
  • int is usually 4 bytes
  • Sizes can vary by system
#include <iostream>

std::cout << sizeof(int);
// prints 4 on most systems

sizeof: How Big Is It?

#include <iostream>

std::cout << sizeof(int);
// prints 4 on most systems

Practice: Read Job Info

  • Read pages (int)
  • Read copiesRequested (short)
  • Print both with labels
// TODO: read pages
// TODO: read copiesRequested
// TODO: print both
Pages: 45
Copies: 3

Questions?

Real Numbers: float & double

float vs. double: Precision

  • Both store decimal values
  • double: 8 bytes, more precise
  • float: 4 bytes, less precise
float (4B)4.5fdouble (8B)0.08Both hold decimals

float & double: Fits or Not?

Fits

  • 0.08
  • 92.5
  • 3.14159

 

Does Not Fit

  • "high" (that's text)
  • true (that's a bool)

Why Precision Matters

  • Printing costs need accuracy
  • double avoids rounding drift
  • Printer uses double for cost
double costPerPage = 0.08;
double totalCost = 12.40;

Why Precision Matters

double costPerPage = 0.08;
double totalCost = 12.40;

The f Suffix

  • float literals need an f
  • Without it, it's a double
  • Mixing types can surprise you
float toner = 85.5f;
double costPerPage = 0.08;
// 0.08 alone is a double

The f Suffix

float toner = 85.5f;
double costPerPage = 0.08;
// 0.08 alone is a double

Integer Division Gotcha

  • int / int drops the decimal
  • 100 / 3 in ints equals 33
  • Use a double to keep it exact
#include <iostream>

int t = 100, j = 3;
std::cout << t / j;
// prints 33, not 33.3
std::cout << t / (double)j;

Integer Division Gotcha

#include <iostream>

int t = 100, j = 3;
std::cout << t / j;
// prints 33, not 33.3
std::cout << t / (double)j;

Practice: Read the Toner Level

  • Read toner (float)
  • Print it back with a label
  • Use cin, then cout
#include <iostream>

// TODO: std::cin >> toner;
// TODO: std::cout with a label
Toner: 85.5

Questions?

Text & Logic: char & bool

char: One Character

  • Holds a single character
  • Written with single quotes
  • 1 byte in memory
#include <iostream>

char size;
std::cin >> size;

char: One Character

#include <iostream>

char size;
std::cin >> size;

bool: True or False

  • Only two possible values
  • true or false, nothing else
  • Perfect for yes/no flags
#include <iostream>

bool busy;
std::cin >> busy;

bool: True or False

#include <iostream>

bool busy;
std::cin >> busy;

char & bool: Fits or Not?

Fits

  • 'A'
  • 'L'
  • true
  • false

 

Does Not Fit

  • "A4" (double quotes = text)
  • 45 (that's an int)

Comparing char and bool

  • Both are small, 1 byte each
  • char stores a letter/symbol
  • bool stores a yes/no state
size (char)'A'busy (bool)trueOne char, one true/false

How Much Memory?

  • char and bool: 1 byte each
  • int: 4 bytes, double: 8 bytes
  • Small types add up in arrays
#include <iostream>

std::cout << sizeof(char);
std::cout << sizeof(bool);

How Much Memory?

#include <iostream>

std::cout << sizeof(char);
std::cout << sizeof(bool);

Practice: Read the Paper Size

  • Read size (char)
  • Print it back with a label
  • Use cin, then cout
#include <iostream>

// TODO: std::cin >> size;
// TODO: std::cout with a label
Paper: A

Questions?

Assignment & Reassignment

Declaring vs. Initializing

  • Declare: create the empty box
  • Initialize: fill it right away
  • pagesLeft; vs pagesLeft = 5;
pagesLeft?pagesLeft5Declared vs. initialized

How Assignment Works

  • = copies a value into the box
  • The box's old value is gone
  • Right side, then left side
5 is copied into the boxpagesLeft55

Reassignment: New Value

  • Same variable, new value
  • Printing fewer pages left
  • Only the latest value survives
pagesLeft (before)5pagesLeft (after)3The old value is gone

Practice: Swap Two Job Page Counts

  • job1Pages = 5, job2Pages = 8
  • Swap their two values
  • You'll need a temp variable
int job1Pages = 5, job2Pages = 8;
// TODO: swap the two values
// use a temp variable
job1Pages8job2Pages5

Questions?

Uninitialized Variables

What If You Skip Init?

  • int pagesLeft; // no value
  • What's really inside the box?
  • It's not always zero!
pagesLeft?int pagesLeft; // no value given

Local Variables: Garbage Values

  • Declared inside a function
  • Memory isn't cleared first
  • The value is unpredictable
#include <iostream>

int pagesLeft;
std::cout << pagesLeft;
// prints garbage, not 0

Local Variables: Garbage Values

#include <iostream>

int pagesLeft;
std::cout << pagesLeft;
// prints garbage, not 0

Global & static: Zero by Default

  • Declared outside any function
  • C++ zero-initializes these
  • Safe, but easy to forget why
int totalPagesPrinted;
// starts at 0
// only true globally

Global & static: Zero by Default

int totalPagesPrinted;
// starts at 0
// only true globally

Default Values by Type

TypeLocal (auto)Global/static
intgarbage0
doublegarbage0.0
chargarbage'\0'
boolgarbagefalse

Practice: Spot the Bug

  • This local int has no value
  • What does this actually print?
  • Why is that risky?
#include <iostream>

int pagesLeft;
std::cout << pagesLeft;
std::cout << std::endl;
// what prints here?
pagesLeft???

Why This Matters

  • Uninitialized data misleads
  • Always give data a real value
  • A habit that prevents bugs
pagesLeft0Initialize everything, always

Questions?

Bits & Bytes

The Bit & The Byte

  • 1948: word "bit" coined
  • 1964: IBM sets 8-bit byte
  • Every type sized in bytes
1948Claude Shannon's paperpopularizes the word 'bit'1963ASCII – a 7-bit codefor letters, digits, symbols1964IBM System/360 setsthe 8-bit byte as standard1998IEC defines KiB, MiBto fix the 1024-vs-1000 mixupTodayEvery C++ type has afixed size in bits & bytes

What Is a Bit? What Is a Byte?

1 Bytebitbitbitbitbitbitbitbit8 bits = 1 byte

Bits Per Native Type

TypeBytesBitsRange
bool18true or false only
char18-128 to 127
short216-32K to 32K
int432-2.1B to 2.1B
long4 or 8*32 or 64*at least -2.1B to 2.1B
float432±3.4×1038
double864±1.8×10308

⚠️ long's size varies by system: 4 bytes on Windows, 8 on Linux/Mac.

The ASCII Table

CategoryDecimal RangeExample
Control chars0 – 3110 = newline
Space, punctuation32 – 4732 = space
Digits 0–948 – 5748 = '0'
More punctuation58 – 6463 = '?'
Uppercase A–Z65 – 9065 = 'A'
More punctuation91 – 9695 = '_'
Lowercase a–z97 – 12297 = 'a'

⚠️ ASCII only covers 0–127; wider text needs Unicode.

From Character to Bits

  • char stores 1 byte
  • 'A' is ASCII 65
  • 65 in binary: 01000001
char size = 'A';01000001'A' = 65 = 01000001

sizeof: Checking Every Type

  • sizeof returns bytes
  • Works on any type
  • Handy for checking sizes
#include <iostream>

std::cout << sizeof(bool);
std::cout << sizeof(char);
std::cout << sizeof(int);

sizeof: Checking Every Type

#include <iostream>

std::cout << sizeof(bool);
std::cout << sizeof(char);
std::cout << sizeof(int);

Practice: How Many Bytes?

  • bool busy;
  • char size;
  • int pages;
  • Total bytes, all three?
bool busy;
char size;
int pages;
// total bytes?
6 bytes (1 + 1 + 4)

⚠️ Real compilers may pad for alignment, so totals can vary.

Practice: Decode the Status Code

  • char status = 'P';
  • ASCII value of 'P'?
  • Binary, using 8 bits?
char status = 'P';
// ASCII value?
// binary, 8 bits?
80 = 01010000

Practice Lab

If/Else Statements

  • Branching: pick a path
  • Every language has it
  • C++ inherited it from C
1957FORTRAN adds the IFstatement, branching begins1960ALGOL introduces thestructured if/then/else block1972C adds if/else(Dennis Ritchie, Bell Labs)1985C++ keeps if/elsefrom C (Bjarne Stroustrup)TodayEvery language hasif/else branching

Where If/Else Shows Up

if / elseLogin:correct password?Grading:pass or fail?ATM:enough balance?Traffic light:safe to go?Game:win or lose?Weather app:rain or shine?

What Is a Condition?

conditiontruefalseif blockrunselse blockruns

if / else Syntax

  • Condition goes in ( )
  • Braces group each block
  • else needs no condition
  • else runs only if false
if (condition) {
    // runs when true
}
else {
    // runs when false
}

True or False?

int age = 20;
if (age >= 18)
TRUE

True or False?

int credits = 9;
if (credits > 12)
FALSE

True or False?

char grade = 'B';
if (grade == 'A')
FALSE

True or False?

double gpa = 3.5;
if (gpa >= 3.5)
TRUE

True or False?

bool passed = true;
if (passed)
TRUE

True or False?

int absences = 0;
if (absences != 0)
FALSE

True or False?

int score = 59;
if (score < 60)
TRUE

True or False?

bool enrolled = false;
if (enrolled)
FALSE

Combining Conditions

OpMeaningExample
&&both must be truea && b
||either can be truea || b
!flips true/false!a

⚠️ && needs both true; a single false fails it.

Questions?

Lab 1: University Gym

Scenario: Gym Check-In

  • 20 minutes, work solo
  • isMember: ask the class
  • You write the if/else
🏃

Plan Your Variables

  • Member status: yes or no
  • Pick from the 7 native types
  • bool, char, or int?
// pick a type for isMember
bool isMember; // yes/no fits bool

⚠️ Don't use int for yes/no; bool is exact.

Round 1: Write the Condition

  • Ask: are you a member?
  • Fill in true or false
  • Then write the if condition
bool isMember; // what do you recommend?
// if condition here?

Answer: Round 1

if (isMember)

Round 2: Add the else

  • Add an else branch
  • else needs no condition
  • Runs only when if is false
if (isMember) {
    cout << "Welcome!";
}
// add else here

Answer: Round 2

else {
    cout << "Join at desk";
}

⚠️ else never gets its own condition.

Round 3: Trace the Output

  • isMember = false now
  • What does it print?
  • Trace if/else by hand
bool isMember = false;
if (isMember) {
    cout << "Welcome!";
}
else {
    cout << "Join at desk";
}

Answer: Round 3

Join at desk

Round 4: Write It Yourself

  • bool hasGuestPass = true;
  • Write the full if/else
  • No starter given this time
bool hasGuestPass = true;
// write if/else below

Answer: Round 4

if (hasGuestPass) {
    cout << "Guest access";
}
else {
    cout << "Not a member";
}

Round 5: Find the Bug

  • Code has one mistake
  • Spot it before running
  • Hint: check the operator
bool isMember = true;
if (isMember = false) {
    cout << "Welcome!";
}

Answer: Round 5

Use == not =

⚠️ = assigns; use == to compare.

Round 6: Combine with &&

  • Ask: member AND has ID?
  • Fill in both values
  • Write the && condition
bool isMember; // what do you recommend?
bool hasID; // what do you recommend?
// if condition here?

Answer: Round 6

if (isMember && hasID)

Round 7: Read Input with cin

  • cin reads keyboard input
  • Store it in isMember
  • Use cin >> isMember
bool isMember;
cout << "Member? (1/0): ";
// read input here?

Answer: Round 7

cin >> isMember;

⚠️ cin expects 1 or 0, not the word true.

Round 8: Validate and Print

  • Read isMember with cin
  • if: print Access OK
  • else: print Denied
bool isMember;
cout << "Member? (1/0): ";
cin >> isMember;
// if/else here?

Answer: Round 8

if (isMember) {
    cout << "Access OK";
}
else {
    cout << "Access Denied";
}

Round 9: Two Members, Read Input

  • isMember1 and isMember2
  • Member 1 types: 1 (pass)
  • Member 2 types: 0 (none)
bool isMember1, isMember2;
cout << "Member 1? (1/0): ";
cin >> isMember1;
cout << "Member 2? (1/0): ";
// read Member 2 here?

Answer: Round 9

cin >> isMember2;

Round 10: Two Members, Print Results

  • Check both, one at a time
  • if: Access OK
  • else: Access Denied
if (isMember1) {
    cout << "Member 1: OK";
}
else {
    cout << "Member 1: Denied";
}
// now check Member 2?

Answer: Round 10

if (isMember2) {
    cout << "Member 2: OK";
}
else {
    cout << "Member 2: Denied";
}

Lab 1 Deliverable

  • Working if/else on screen
  • Explain the trace out loud
  • Ready when instructor checks
✅

Questions?

Lab 2: Algorithms

Scenario: Design Before Code

  • 20 minutes, teams of two
  • Paper and pencil, no C++ yet
  • Answer is shown at the end
📐

Task 1: Define Algorithm

  • As a team, define it
  • Write it on paper
  • Compare with another team
📝

Task 2: When Do You Plan?

  • Before or after writing code?
  • Discuss with your partner
  • Be ready to justify it
🤔

The PIN Guessing Game

  • Range: 1 to 10
  • Computer asks 3 questions
  • Each: higher, lower, correct
🎯

Sample Run: A Correct Guess

  • Program asks about 5 first
  • 2 = Lower, 1 = Higher
  • Narrows to the exact PIN
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

YesNoHigher/LowerCorrectrepeat up to 3xStartExplain rules,range 1-10Ask about thecurrent guessValid reply?Print: Cheater!!!Stop the gameEndHigher, Lower,or Correct?Print: It mustbe N!EndNarrow the range(new midpoint)

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 class
if (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 class
if (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

Answer: Round 4, Combined

Partner A + Partner B, one condition:

if (copies > 0 && isActive) {
    cout << "Checkout allowed";
}
else {
    cout << "Not allowed";
}

Lab 3 Deliverable

  • Both partners can explain it
  • Show the traced output
  • Ready when instructor checks
✅

Questions?

Lab 4: University Dining Hall

Scenario: Meal Swipe Check

  • 20 minutes, whole class
  • balance: ask the class
  • One shared program, 3 teams
🍽

Class Roles

  • Team Logic: the condition
  • Team Output: the messages
  • Team Testing: predict values
  • Everyone: trace together
👥

Plan Your Variables

  • balance & minSwipe: integers
  • Pick from the 7 native types
  • double, int, or char?
// pick a type for balance
int balance; // what do you recommend?
int minSwipe = 5; // fixed

⚠️ Reserve double for values needing decimals.

Round 1: Team Logic's Condition

  • Ask: what's your balance?
  • Fill in a real number
  • Team Logic types the line
int balance; // what do you recommend?
int minSwipe = 5;
// if condition here?

Answer: Round 1

if (balance >= minSwipe)

⚠️ >= includes the equal case too.

Round 2: Team Output's Messages

  • Team Output fills the braces
  • if: swipe accepted
  • else: balance too low
if (balance >= minSwipe) {
    // accepted message?
}
else {
    // too low message?
}

Answer: Round 2

cout << "Swipe accepted";
cout << "Balance too low";

Round 3: The Class Traces It

  • balance = 3 now
  • Predict it as a class
  • Compare every table's answer
int balance = 3;
int minSwipe = 5;
if (balance >= minSwipe) {
    cout << "Swipe accepted";
}
else {
    cout << "Balance too low";
}

Answer: Round 3

Balance too low

Round 4: A New Shared Value

  • Ask: how many meals left?
  • Fill in a real number
  • Team Logic: write if
int mealsLeft; // what do you recommend?
// if condition here?

Answer: Round 4

if (mealsLeft > 0)

Round 5: Output Writes, Testing Predicts

  • Team Output: fill braces
  • Team Testing: predict it
  • mealsLeft = 0, so which runs?
if (mealsLeft > 0) {
    // has-meals message?
}
else {
    // no-meals message?
}

Answer: Round 5

cout << "Swipe your meal";
cout << "No meals left";

Round 6: Combine with &&

  • Ask: balance AND valid ID?
  • Fill in both values
  • Write the && condition
int balance; // what do you recommend?
bool hasID; // what do you recommend?
// if condition here?

Answer: Round 6

if (balance >= minSwipe && hasID)

Lab 4 Deliverable

  • Class agrees on one output
  • Each team states its part
  • Ready when instructor checks
✅

Questions?

Practice Quiz

Practice Quiz: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question.

Variable
int
bool
cin
Reads input from the keyboard
Prints output to the screen
Tells the compiler what kind of value is stored
Creating a variable with a type and name
Storing a value into a variable with =
A named spot in memory that stores a value
Type that stores a whole number
Type that stores true or false
cout
Data Type
Declaration
Assignment

Questions?

Where We Are: Module 2

  • Module 2 done: types & I/O
  • Next: Branches

Why This Matters

  • Jumps came before if/else
  • Dijkstra pushed structure
  • Now in nearly every language
1950sMachine code: conditionaljump instructions (JNZ, JZ)1957FORTRAN's arithmetic IFstatement1960ALGOL 60 introducesif–then–else as a block1968Dijkstra's “Go ToStatement Considered Harmful”Todayif / else / switch invirtually every language

What Is a Branch?

What Is a Branch?

  • Programs need to make choices
  • A branch picks one path
  • Example: check the paper tray
bool paperTrayFull = true;
if (paperTrayFull) {
    cout << "Ready to print";
}

What Is a Branch?

  • Each branch runs on its own
  • Only one path executes
  • Example: printer online?
bool printerOnline = false;
if (printerOnline) {
    cout << "Sending job...";
} else {
    cout << "Printer offline!";
}

What Is a Branch?

  • A condition is true or false
  • Never both at once
  • Example: is toner available?
bool tonerOk = true;
if (tonerOk) {
    cout << "Printing...";
} else {
    cout << "Refill toner";
}

Word Origin: "Boolean"

George Boole
  • English mathematician, 1800s
  • Self-taught, no formal degree
His 1854 Book
  • "An Investigation of the
  • Laws of Thought"
  • Logic expressed as algebra

Boole showed that true/false logic could be written as math – AND, OR, NOT. C++'s bool type is named after him directly.

Questions?

Decision-Making

Decision-Making in Programs

  • Check if the printer is jammed
  • Avoids damage and wasted pages
bool printerJam = true;
if (printerJam) {
    cout << "Clear the jam";
} else {
    cout << "Printer ready";
}

Decision-Making in Programs

  • Compare tray to the job
  • Picks the matching tray
int tray = 1;
if (tray == 1) {
    cout << "Tray 1 selected";
} else if (tray == 2) {
    cout << "Tray 2 selected";
} else {
    cout << "Invalid tray";
}

Decision-Making in Programs

  • Check toner and paper both
  • Required before a batch job
bool paper = true;
bool toner = false;
if (paper && toner) {
    cout << "Starting batch";
} else {
    cout << "Check supplies";
}

Questions?

Real-World Examples

Card Swipe Door

  • Check if the card is valid
  • Grant or deny access
#include <iostream>
bool cardValid = false;
if (cardValid) {
    cout << "Door opens";
} else {
    cout << "Access denied";
}

Extend: Card Swipe Door

  • Add a maintenance check
  • Locked doors deny entry
#include <iostream>
bool maintenance = false;
if (maintenance) {
    cout << "Door locked";
} else if (cardValid) {
    cout << "Door opens";
} else {
    cout << "Access denied";
}

Traffic Light

  • Check the light color
  • Decide: go, slow, or stop
#include <iostream>
char light = 'Y';
if (light == 'G') {
    cout << "Go";
} else if (light == 'Y') {
    cout << "Slow down";
} else {
    cout << "Stop";
}

Extend: Traffic Light

  • Add a broken-light case
  • Trace light = 'X'
#include <iostream>
// light = 'X'
if (light == 'G') {
    cout << "Go";
} else if (light == 'Y') {
    cout << "Slow down";
} else if (light == 'X') {
    cout << "Light broken";
} else {
    cout << "Stop";
}

ATM Machine

  • Check if the PIN is correct
  • Grant or deny access
#include <iostream>
bool pinCorrect = false;
if (pinCorrect) {
    cout << "Access granted";
} else {
    cout << "Incorrect PIN";
}

Extend: ATM Machine

  • Add a 3-attempt limit
  • Block the card at 3
#include <iostream>
int attempts = 3;
if (attempts >= 3) {
    cout << "Card blocked";
} else if (pinCorrect) {
    cout << "Access granted";
} else {
    cout << "Incorrect PIN";
}

Elevator

  • Compare requested to current
  • Picks a direction to move
#include <iostream>
int requested = 5, current = 3;
if (requested > current) {
    cout << "Going up";
} else if (requested < current) {
    cout << "Going down";
} else {
    cout << "Already there";
}

Extend: Elevator

  • Add an overweight check
  • Overweight blocks moving
#include <iostream>
bool overweight = true;
if (overweight) {
    cout << "Overweight, exit";
} else if (requested > current) {
    cout << "Going up";
} else {
    cout << "Going down";
}

Smart Thermostat

  • Check the current temperature
  • Turn heating or cooling on
#include <iostream>
int temp = 68;
if (temp < 70) {
    cout << "Heating ON";
} else if (temp > 75) {
    cout << "Cooling ON";
} else {
    cout << "System idle";
}

Extend: Smart Thermostat

  • Add a system-off state
  • Off skips heat/cool
#include <iostream>
bool systemOn = false;
if (!systemOn) {
    cout << "System OFF";
} else if (temp < 70) {
    cout << "Heating ON";
} else {
    cout << "Cooling ON / idle";
}

Coffee Machine

  • Check water and bean levels
  • Brew only if both are ready
#include <iostream>
bool water = true, beans = false;
if (water && beans) {
    cout << "Brewing...";
} else {
    cout << "Refill first";
}

Extend: Coffee Machine

  • Add a cup-present check
  • No cup blocks brewing
#include <iostream>
bool cupPresent = false;
if (!cupPresent) {
    cout << "Insert a cup";
} else if (water && beans) {
    cout << "Brewing...";
} else {
    cout << "Refill first";
}

Password Login

  • Track which attempt this is
  • Lock out after 3 tries
#include <iostream>
int attempt = 1;
if (attempt == 1) {
    cout << "Wrong, try again";
} else if (attempt == 2) {
    cout << "Wrong, last try";
} else if (attempt == 3) {
    cout << "Account locked";
}

Extend: Password Login

  • Add an already-locked check
  • Block any further tries
#include <iostream>
bool locked = true;
if (locked) {
    cout << "Account is locked";
} else if (attempt < 3) {
    cout << "Wrong, try again";
} else {
    cout << "Account locked";
}

Questions?

if / else in C++

If / Else Statements

  • Basic conditional check
  • Two possible paths only
  • if(cond) {...} else {...}
#include <iostream>
int temp = 75;
if (temp > 70) {
    cout << "Turn on AC";
} else {
    cout << "AC off";
}

Else If

  • Handles several conditions
  • First true one runs
  • Good for priority checks
#include <iostream>
int score = 82;
if (score >= 90) {
    cout << "A";
} else if (score >= 75) {
    cout << "B";
} else {
    cout << "C or below";
}

Best Practices

  • Keep conditions readable
  • Use braces every time
  • Avoid deep nesting
#include <iostream>
if (isReady) {
    cout << "Ready";
} else {
    cout << "Not ready";
}

Common Mistakes

  • Using = instead of ==
  • Forgetting the else case
#include <iostream>
bool active = true;
if (active = false) {  // bug
    cout << "Inactive";
}

Common Mistakes

  • Loose condition checked first
  • Stricter case never runs
#include <iostream>
int score = 85;
if (score >= 60) {
    cout << "Pass"; // bug: catches 85
} else if (score >= 80) {
    cout << "Honors";
}

⚠️ Put the stricter condition first, or the looser one always wins.

Common Mistakes

  • Missing braces on if
  • Only next line is inside if
#include <iostream>
bool ready = false;
if (ready)
    cout << "Go";
    cout << "Oops, always runs";

Quick Check

  • Good for many discrete values?
#include <iostream>
int mode = 2;
if (mode == 1) {
    cout << "B&W";
} else if (mode == 2) {
    cout << "Color";
}

Answer: No, prefer switch for many discrete values.

Nested If

  • Checks conditions inside
  • another if block
  • Reduce nesting when you can
#include <iostream>
if (hasPaper) {
    if (tonerOk) {
        cout << "Ready";
    }
} else {
    cout << "Add paper";
}

Logical Operators

  • && needs both true
  • || needs just one true
#include <iostream>
bool paper = true;
bool toner = true;
if (paper && toner) {
    cout << "Printing...";
}

Short-Circuit Evaluation

  • Checked left to right
  • Stops once outcome is known
#include <iostream>
if (isConnected && hasJob) {
    cout << "Processing";
}

Summary: If / Else

  • Use for two-way choices
  • Keep it short and readable
#include <iostream>
bool ready = true;
if (ready) {
    cout << "Go";
} else {
    cout << "Wait";
}

Questions?

switch in C++

Advantages of if/else

  • Any condition, any type
  • Works with ranges (>, <)
  • Combine with &&, ||

Where switch Helps

  • Many else-if gets messy
  • Hard to read one value
  • switch reads cleaner here

⚠️ Many options on one value? switch reads cleaner.

Switch Statement

  • Alternative to many else-if
  • Works on int, char, enum
#include <iostream>
int mode = 2;
switch(mode) {
    case 1: cout << "B&W"; break;
    case 2: cout << "Color"; break;
    default: cout << "Unknown";
}

Best Practices

  • Always break each case
  • Add a default case
#include <iostream>
char opt = 'B';
switch(opt) {
    case 'A': cout << "Opt A"; break;
    case 'B': cout << "Opt B"; break;
    default: cout << "Invalid";
}

Multiple Cases, One Action

  • Stack cases to group them
  • Avoids repeating code
#include <iostream>
char grade = 'B';
switch(grade) {
    case 'A':
    case 'B': cout << "Pass"; break;
    default: cout << "Fail";
}

Switch With Enum

  • Enums improve readability
#include <iostream>
enum Mode { BW=1, COLOR=2 };
Mode m = COLOR;
switch(m) {
    case BW: cout << "B&W"; break;
    case COLOR: cout << "Color"; break;
}

Quick Check

  • switch or if/else for 4 modes?
#include <iostream>
int mode = 3;
switch(mode) {
    case 1: cout << "B&W"; break;
    case 2: cout << "Color"; break;
    case 3: cout << "Draft"; break;
}

Answer: switch, it's more readable for discrete values.

Fallthrough Cases

  • Omitting break runs the
  • next case too, on purpose
#include <iostream>
char c = 'A';
switch(c) {
    case 'A':
    case 'B': cout << "Good"; break;
    case 'C': cout << "Average";
}

Default Case

  • Catches unexpected values
  • Prevents silent bugs
#include <iostream>
int opt = 5;
switch(opt) {
    case 1: cout << "One"; break;
    default: cout << "Unknown";
}

Quick Check

  • What if you forget break?
#include <iostream>
int x = 2;
switch(x) {
    case 1: cout << "One";
    case 2: cout << "Two"; // falls
    case 3: cout << "Three";
}

Answer: Execution falls through to the next case.

Summary: Switch

  • Best for discrete values
  • Always add default
#include <iostream>
char opt = 'C';
switch(opt) {
    case 'C': cout << "Option C"; break;
    default: cout << "Unknown";
}

Traffic Light

  • Check the light color
  • One case per color
#include <iostream>
char light = 'G';
switch (light) {
    case 'G': cout << "Go"; break;
    case 'Y': cout << "Slow down"; break;
    default: cout << "Stop";
}

Elevator Floor Button

  • Pick the floor to visit
  • One case per floor
#include <iostream>
int floor = 3;
switch (floor) {
    case 1: cout << "Lobby"; break;
    case 2: cout << "Office"; break;
    case 3: cout << "Gym"; break;
    default: cout << "Invalid floor";
}

Vending Machine

  • Pick a snack by number
  • One case per snack
#include <iostream>
int choice = 2;
switch (choice) {
    case 1: cout << "Chips"; break;
    case 2: cout << "Candy"; break;
    case 3: cout << "Soda"; break;
    default: cout << "Sold out";
}

ATM Menu

  • Pick an action by number
  • One case per menu item
#include <iostream>
int choice = 1;
switch (choice) {
    case 1: cout << "Withdraw"; break;
    case 2: cout << "Deposit"; break;
    case 3: cout << "Balance"; break;
    default: cout << "Invalid choice";
}

Word Origin: "Switch"

Electrical Roots
  • A physical lever that
  • picks one circuit path
In Code
  • Same idea: pick ONE case
  • based on a value

The metaphor is literal: an old telephone switchboard physically routed a call down one wire, exactly one path, out of many.

Practice Lab

Requirements

  • Build a text Horse Race Game
  • Track: Start, Middle, Finish
  • Player picks Move or Quit
  • Print the horse's position
// Goal:
// Start -> Middle -> Finish
// Two player choices get there

Step 1: Track the Position

  • Use constants, not magic
  • numbers, for each spot
const int START = 0;
const int MIDDLE = 1;
const int FINISH = 2;
int horsePos = START;

Step 2: Ask for a Move

  • 1 = Move Forward, 2 = Quit
  • Store the answer in choice
int choice;
cout << "1=Move, 2=Quit: ";
cin >> choice;

Step 3: Handle the Choice

  • if/else moves the horse
  • or ends the game
if (choice == 1) {
    horsePos = MIDDLE;
    cout << "Horse: _ H _";
} else {
    cout << "You quit.";
    return 0;
}

Step 4: Second Move

  • Ask again, this time
  • using switch instead
switch(choice) {
    case 1:
        horsePos = FINISH;
        cout << "Horse: _ _ H";
        break;
    case 2:
        cout << "You quit.";
        break;
}

Step 5: Check the Winner

  • Compare position to FINISH
  • Print a win message
if (horsePos == FINISH) {
    cout << "You won!";
}

Deliverables

  • A working horse_race.cpp
  • Uses if/else AND switch
  • Handles both Quit points
// Submit horse_race.cpp
// Test: choose Move, Move
// Test: choose Quit at step 1

Questions?

Practice Lab Part 2

What You'll Practice

  • Review Module 2: types, I/O
  • Review Module 3: if / else
  • New tool: the while loop
  • Last two: plan on paper
P1–P2reviewP3–P5while loopP6–P7on paper

Problem 1: Campus Coffee

  • Coffee is $4 a cup
  • Student ID: $1 off a cup
  • Read how many cups
  • No if, no loop yet
Cups: 3
You pay: $9

Answer 1: Campus Coffee

  • Two consts: price, deal
  • Subtract once for the deal
  • Multiply by the cups
int cups;
const int PRICE = 4;
const int DEAL = 1;
std::cout << "Cups: ";
std::cin >> cups;
int each = PRICE - DEAL;
std::cout << "You pay: $" << cups * each;

Problem 2: Coffee Size

  • 1 small, 2 medium, 3 large
  • Prices: $3, $4, $5
  • Read the size number
  • Use if / else if
Size (1-3): 2
Price: $4

Answer 2: Coffee Size

  • One branch per size
  • else if checks the next
  • Last else covers large
int size;
std::cout << "Size (1-3): ";
std::cin >> size;
if (size == 1) std::cout << "Price: $3";
else if (size == 2) std::cout << "Price: $4";
else std::cout << "Price: $5";

Before Problem 3: while

  • while (test) { body }
  • Runs while the test is true
  • Body must move toward false
  • Else it loops forever
truerepeatfalseis the test true?run the bodyexit the loop

⚠️ If the body never changes the test, the loop runs forever.

Problem 3: Seat Numbers

  • Read a count n (an int)
  • Print 1, 2, 3, up to n
  • One number per line
  • Use a while loop
seatprinted1122334 (> n)stop

Answer 3: Seat Numbers

  • seat starts at 1
  • Loop while seat is not past n
  • seat = seat + 1 each pass
int n;
std::cout << "How many seats? ";
std::cin >> n;
int seat = 1;
while (seat <= n) {
    std::cout << seat << std::endl;
    seat = seat + 1;
}

Problem 4: Sum to Sentinel

  • Read scores, one per line
  • Stop when the user types -1
  • Add each score to a total
  • Print the total at the end
Score: 8
Score: 9
Score: 7
Score: -1
Total: 24

Answer 4: Sum to Sentinel

  • Read once before the loop
  • Loop until the score is -1
  • Read again inside the loop
int total = 0;
int score;
std::cout << "Score: ";
std::cin >> score;
while (score != -1) {
    total = total + score;
    std::cout << "Score: ";
    std::cin >> score;
}
std::cout << "Total: " << total;

Problem 5: Validate Units

  • Units must be 1 to 18
  • Re-ask while out of range
  • Accept the first valid one
  • Then print "Registered"
Units: 25
Range 1-18. Units: 0
Range 1-18. Units: 15
Registered: 15

Answer 5: Validate Units

  • The test is the bad case
  • || means either side is off
  • Re-read until the test fails
int units;
std::cout << "Units: ";
std::cin >> units;
while (units < 1 || units > 18) {
    std::cout << "Range 1-18. Units: ";
    std::cin >> units;
}
std::cout << "Registered: " << units;

Problem 6: Coffee Card

  • Card needs 10 stamps
  • Each coffee is one stamp
  • Loop while stamps under 10
  • Write the pseudocode
  • Paper only, no C++
yesnostamps = 0while stamps < 10buy a coffee, stamps++free coffee!

Answer 6: Coffee Card

  • Start stamps at 0
  • Test before the body
  • Stops at exactly 10
set stamps = 0
while stamps < 10
    buy one coffee
    stamps = stamps + 1
print "free coffee unlocked"

Problem 7: Payment Plan

  • Balance and monthly payment
  • Subtract while balance > 0
  • Count how many months
  • Write pseudocode and a trace
  • Paper only, no C++
yesnoread balance, paymentwhile balance > 0balance -= payment, months++print months

Answer 7: Payment Plan

  • months starts at 0
  • Last payment may overshoot
  • Trace $500, $200 gives 3
read balance
read payment
set months = 0
while balance > 0
    balance = balance - payment
    months = months + 1
print months

Part 2 Deliverables

  • One .cpp per problem 1 to 5
  • Problems 6–7: photo of paper
  • Every loop must be a while
  • Test each with the sample run
// P1-P5 : one .cpp each
// P6-P7 : pseudocode on paper
// loops : while only

Bonus Game: Rock Paper Scissors

  • 1 rock, 2 paper, 3 scissors
  • You type your move
  • Computer picks with rand()
  • if decides win, lose, or tie
3 roundsyou pick 1, 2, or 3computer: rand() picksif compares: win/lose/tie

Step 1: The Libraries

  • cstdlib gives rand / srand
  • ctime gives time
  • srand seeds it once
  • Seed with the clock so it
  • differs each run
#include <cstdlib>   // rand(), srand()
#include <ctime>     // time()

srand(time(0));   // seed from the clock
int you, cpu, n = 1;

Step 2: Pick Moves Each Round

  • while runs 3 rounds
  • Read your move into you
  • rand() % 3 gives 0, 1, 2
  • + 1 shifts it to 1, 2, 3
while (n <= 3) {
    std::cout << "You (1-3)? ";
    std::cin >> you;
    cpu = rand() % 3 + 1;   // 0,1,2 -> 1,2,3
    // decide the winner (next slide)
    n = n + 1;
}

Step 3: Decide the Winner

  • Same number is a tie
  • you % 3 + 1 is the move
  • that beats you
  • Anything else, you win
if (you == cpu)
    std::cout << "Tie\n";
else if (you % 3 + 1 == cpu)
    std::cout << "You lose\n";
else
    std::cout << "You win\n";

Sample Run

  • Rock vs scissors: win
  • Paper vs scissors: lose
  • Rock vs rock: tie
You (1-3)? 1
You win
You (1-3)? 2
You lose
You (1-3)? 1
Tie

Questions?

Practice Quiz

Practice Quiz: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question.

if
else
&&
||
Logical OR operator
An expression that evaluates to true or false
Compares two values, like &lt; or ==
An if statement inside another if statement
Branches based on matching one of several values
Runs a block only when a condition is true
Runs when the if condition is false
Logical AND operator
Boolean Expression
Relational Operator
Nested If
Switch

Questions?

Looking Ahead: Module 4

Where We Are: Module 3

  • Module 3 done: branches
  • Next: Loops

Why This Matters

  • Loops started as jump-backs
  • FORTRAN's DO was the first
  • C++ inherits all 3 loop forms
1950sMachine code: a conditionaljump back up to repeat1957FORTRAN's DO loop – thefirst structured loop1960ALGOL 60 introduces thefor-loop1972C adds for / while / do-whileTodayC++ inherits all three loopforms from C

What Is a Loop?

  • Repeat a block of code
  • A test decides when to stop
  • C++: while, for, do-while
falserepeatrun the bodytest still true?leave the loop

Loops Beat Copy-Paste

  • Print 1 to 100 by hand?
  • One loop does it all
  • Fix it once, not 100 times
cout << 1;cout << 2;cout << 3;cout << 4;cout << 5;cout << 6;cout << 7;...100 lines=one for loop1 to 100

The Three Parts of a Loop

  • Start: set a counter
  • Test: keep going?
  • Update: step the counter
back to testinit: i = 1set the countertest: i <= n ?body + updatedo work, i = i + 1

Word Origin: "Iteration"

iter-
  • Latin "iterum": again
iterare
  • Latin verb: to repeat

One iteration is one pass through the loop body; the word just means doing it again.

Questions?

The while Loop

The while Loop

  • Check the test first
  • Then run the body
  • Body must move the test
int x = 1;
while (x <= 5) {
    std::cout << x << " ";
    x = x + 1;
}
// prints: 1 2 3 4 5

while: Trace the Count

  • x starts at 1
  • Loop while x <= 5
  • x goes up each pass
xwhat happensx = 1prints "1 "x = 2prints "2 "x = 3prints "3 "x = 6test fails, stop

while: Read Until a Sentinel

  • Read one value first
  • Loop until it is -1
  • Add each to a total
int total = 0;
int num;
std::cin >> num;
while (num != -1) {
    total = total + num;
    std::cin >> num;
}
std::cout << "sum = " << total;

while: Avoid the Infinite Loop

  • No update means never stop
  • Always change the test
  • Ctrl+C stops a runaway
// BAD: x never changes
int x = 1;
while (x <= 3) {
    std::cout << x;   // 1 1 1 ...
}
// FIX: add  x = x + 1;  in the body

Questions?

The for Loop

The for Loop

  • All three parts, one line
  • Best when the count is known
  • init, then test, then body
for (int i = 1; i <= 5; i++) {
    std::cout << i << " ";
}
// prints: 1 2 3 4 5

for Equals while

  • for is a packed while
  • Same init, test, update
  • Pick the clearer one
for (A; B; C) is a packed whilefor ( A ; B ; C )A: initB: testC: updateA runs once, B before each pass, C after the body

for: Add 1 to n

  • Read n from the user
  • Loop i from 1 to n
  • sum = sum + i
int n, sum = 0;
std::cin >> n;
for (int i = 1; i <= n; i++) {
    sum = sum + i;
}
std::cout << "sum = " << sum;

Questions?

The do-while Loop

The do-while Loop

  • Body runs first
  • Test is at the bottom
  • Always runs at least once
int choice;
do {
    std::cout << "1=Play 2=Quit: ";
    std::cin >> choice;
} while (choice != 2);
std::cout << "Bye!";

do-while vs while

  • while: may run 0 times
  • do-while: runs 1+ times
  • Menus fit do-while
whilecheck testthen bodymay run 0 timesdo-whilerun bodythen checkruns 1+ times

Questions?

Nested Loops

Nested Loops

  • A loop inside a loop
  • Inner runs fully each pass
  • Good for grids and tables
for (int r = 1; r <= 3; r++) {
    for (int c = 1; c <= 3; c++) {
        std::cout << "(" << r << c << ")";
    }
    std::cout << "\n";
}

Nested: Trace the Grid

  • Outer picks the row
  • Inner sweeps the columns
  • 3 x 3 is 9 passes
(1,1)(1,2)(1,3)(2,1)(2,2)(2,3)(3,1)(3,2)(3,3)rowsinner: sweeps the columns

Nested: Draw a Chessboard

  • 8 by 8 nested loop
  • (row + col) % 2 picks color
  • No array needed
for (int r = 0; r < 8; r++) {
    for (int c = 0; c < 8; c++) {
        if ((r + c) % 2 == 0)
            std::cout << "W ";
        else
            std::cout << "B ";
    }
    std::cout << "\n";
}

Questions?

break, continue, Pitfalls

break and continue

  • break: leave the loop now
  • continue: skip to next pass
  • Use them sparingly
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;  // skip 3
    if (i == 5) break;     // stop
    std::cout << i << " ";
}
// prints: 1 2 4

Off-by-One Errors

  • 0 to <= 5 runs 6 times
  • 0 to < 5 runs 5 times
  • Count the passes on paper
// runs 6 times: 0 1 2 3 4 5
for (int i = 0; i <= 5; i++)
    std::cout << i;

// runs 5 times: 0 1 2 3 4
for (int i = 0; i < 5; i++)
    std::cout << i;

Loop Pitfalls Checklist

  • Did the test change?
  • Right start and end?
  • One job per loop
Does the test ever become false?Right start and end values?Off by one: <= vs < ?One job inside the loop?

Questions?

Practice Lab

From Rounds to Randomness

  • Start simple: fixed rounds
  • Then add real randomness
  • Same loops, new games
CountdownLucky #Dice RollGuess NumWin StreakRPSfixed rounds

Countdown Game

  • Goal: reach zero and stop
  • Counts down from n to 1
  • One line per number
  • Then a final message
int n = 5;
for (int i = n; i >= 1; i--) {
    std::cout << i << "\n";
}
std::cout << "Blast off!\n";

Lucky Number Game

  • Goal: find 7 in fewest tries
  • Target is fixed: 7
  • Loop while wrong guess
  • Counts the tries
int lucky = 7, guess = 0, tries = 0;
while (guess != lucky) {
    std::cin >> guess;
    tries++;
}
std::cout << "Tries: " << tries;

Lucky Number: Trace It

  • 3 is too low
  • 5 is too low
  • 7 matches, loop stops
guesstries so far3152637match, stop

What Is rand()?

  • Returns a random int
  • Range: 0 to RAND_MAX
  • Needs #include <cstdlib>
0RAND_MAXrand() returns one value herea huge range, hard to use directly

Picking a Range with %

  • % keeps the remainder
  • rand() % 6 gives 0-5
  • +1 shifts it to 1-6
rand(): any huge number% 6 keeps the remainderResult: 0, 1, 2, 3, 4, 5+1 shifts this to 1, 2, 3, 4, 5, 6

Adding Randomness: rand()

  • rand() gives a random int
  • % picks a range
  • srand seeds it once
#include <cstdlib>
#include <ctime>
srand(time(0));  // seed once
int 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 run
int 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
123456rand() % 6 + 1 gives one of these, at random

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
roll #value14263146each run gives different numbers

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
gameloop usedCountdownforLucky NumberwhileDice RollforGuess Numberdo-whileWin StreakwhileRPSfor

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 AttemptsMath Quiz

Password Attempts

  • Goal: unlock in 3 tries
  • PIN is fixed, tries limited
  • while loop, checks tries left
  • Stops early if correct
const int 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";
else std::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.

for
while
do-while
Iteration
One full pass through a loop's body
A loop whose condition never becomes false
Exits a loop immediately
Skips to the next loop iteration
Variable that tracks how many passes have run
Loop with a built-in counter
Loop that checks its condition before each pass
Loop that always runs at least once
Infinite Loop
break
continue
Loop Counter

Questions?

Looking Ahead: Module 5

Where We Are: Module 4

  • Module 4 done: loops
  • Next: Arrays & Vectors

Why This Matters

  • Indexed arrays date to ALGOL
  • C arrays are fixed, fast
  • Vectors can grow, arrays can't
1957FORTRAN addsthe DO-array1960ALGOL 60 formalizesindexed arrays1972C arrays: fast,fixed-size blocks1998C++ STL vector:arrays that growTodayEvery languagestill has both

Why Arrays? The Problem

The Problem: Too Many Names

  • The Registrar tracks 200 GPAs
  • One variable per student?
  • That's 200 variable names
double grade1;double grade2;double grade3;⋮double grade30;30 separate names to manage

Individual Variables Don't Scale

  • 30 grades need 30 variables
  • Adding student 31? New line
  • Looping over them? Impossible
double grade1;double grade2;double grade3;⋮double grade30;30 separate names to manage

⚠️ A fixed number of variables can never loop over an unknown number of students.

Existing Software Solves This

  • Spreadsheets: one column
  • Databases: one table
  • Same idea, different tool
📊Excel column🗃️SQL table column📋One name, many rows

Word Origin: "Array"

arayer
  • Old French: to set in order
arrangier
  • To arrange, line up in a row

An array is values lined up in order, each one numbered by position.

The Answer: One Array

  • One name: grades
  • Five values, side by side
  • Each has its own position
grades9207818521003674

Declaring & Indexing

Declaring an Array

  • Type, name, size in brackets
  • Creates empty slots
  • Fill each slot by index
int grades[5];
// 5 empty int slots
grades[0] = 92;
grades[1] = 78;

Zero-Based Counting

  • Indexing starts at 0
  • Not 1, like counting people
  • Last index is size - 1
grades9207818521003674index 0 is the first slot

⚠️ The first slot is index 0, not index 1.

Word Origin: "Index"

index
  • Latin: pointer, one who shows
indicare
  • To point out, indicate

An index literally points to one slot in the array.

Reading an Element

  • Reading an element
  • Use the index in brackets
  • grades[0] is the first grade
std::cout << grades[0];
// prints 92
std::cout << grades[4];
// prints 67, the last one

Updating an Element

  • Writing updates a slot
  • Old value is overwritten
  • Same syntax as reading
grades[2] = 95;
// updates slot 2
std::cout << grades[2];
// now prints 95

Initializing All at Once

  • List values at declare time
  • No index-by-index filling
  • Great for known starting data
int seats[3] = {40, 35, 28};
// fill all 3 at once
std::cout << seats[1];
// prints 35

Practice: What Prints?

  • seats[0] = 40, seats[1] = 35
  • cout << seats[1];
  • What is printed?

Answer: 35

Looping Through Arrays

Why Loop an Array?

  • for loop visits every index
  • i goes from 0 to size - 1
  • grades[i] changes each pass
grades9207818521003674

Printing Every Grade

  • i < 5 stops at index 4
  • i++ moves to the next slot
  • Prints every grade, one line
for (int i = 0; i < 5; i++) {
    std::cout << grades[i] << "\n";
}

Sum All Grades

  • total starts at 0
  • Add each grade in the loop
  • The Registrar needs this sum
int total = 0;
for (int i = 0; i < 5; i++) {
    total += grades[i];
}
std::cout << total;

Average All Grades

  • Average = total ÷ count
  • Use 5.0, not 5, for the count
  • Int division would truncate
double avg = total / 5.0;
// 5.0, not 5: avoid int division
std::cout << avg;

⚠️ total / 5 (int / int) drops the decimal part entirely.

Find the Highest Grade

  • Start by assuming slot 0 wins
  • Compare every later slot
  • Keep the biggest one seen
int highest = grades[0];
for (int i = 1; i < 5; i++) {
    if (grades[i] > highest) {
        highest = grades[i];
    }
}

Find the Lowest Grade

  • Same pattern, flipped operator
  • Start at slot 0, scan the rest
  • Keep the smallest one seen
int lowest = grades[0];
for (int i = 1; i < 5; i++) {
    if (grades[i] < lowest) {
        lowest = grades[i];
    }
}

Count Passing Grades

  • Loop + condition + array
  • Count grades 70 or above
  • Records reports pass rates
int passing = 0;
for (int i = 0; i < 5; i++) {
    if (grades[i] >= 70) {
        passing++;
    }
}

Practice: Trace the Loop

  • grades = {92, 78, 85, 100, 67}
  • Count grades >= 90
  • How many pass?

Answer: 2 (92 and 100)

Array Bugs to Avoid

Arrays Have a Fixed Size

  • Size is fixed at declaration
  • int grades[5] is always 5
  • No 6th slot ever appears
grades9207818521003674exactly 5 slots, forever

Bug: Off-by-One

  • <= 5 checks index 5 too
  • Index 5 doesn't exist!
  • Valid indexes are 0 to 4
for (int i = 0; i <= 5; i++) {
    std::cout << grades[i];
}

⚠️ <= instead of < reads one slot past the array's end.

Bug: Out-of-Bounds

  • Out-of-bounds isn't caught
  • C++ doesn't stop you
  • Result: garbage or a crash
grades9207818521003674?5index 5: undefined behavior

🚨 Reading past the end is undefined behavior, not a clean error.

Practice: Spot the Bug

  • int nums[3];
  • for (int i = 0; i <= 3; i++)
  • What's wrong here?

Answer: <= 3 reads index 3, which doesn't exist

The Fix: Match Size Exactly

  • Match the loop bound to size
  • size() (vectors) helps later
  • Never hardcode a guess
int names[30];
// or grades, or any array
for (int i = 0; i < 30; i++)

Vectors: Growing Arrays

Why Vectors?

  • A new student enrolls today
  • Arrays can't grow to fit them
  • We need a resizable container
📏array[30]: fixed🧑‍🎓student 31 enrolls🚫no room left

Word Origin: "Vector"

vehere
  • Latin: to carry, to convey
C++ STL, 1998
  • A container that can grow

A vector "carries" a sequence of values and can grow as needed.

Declaring a Vector

  • Needs #include <vector>
  • std::vector<type> name
  • Starts with zero elements
#include <vector>
std::vector<int> grades;
// starts empty, size 0

Adding a New Student

  • push_back adds to the end
  • The vector grows automatically
  • New student? Just push_back
grades.push_back(92);
grades.push_back(78);
// size is now 2

Vector Size: .size()

  • Replaces guessing the size
  • Always accurate, never guessed
  • Use it as the loop bound
std::cout << grades.size();
// how many elements right now

Looping a Vector

  • Same [ ] indexing as arrays
  • Loop bound is grades.size()
  • Works no matter the count
for (int i = 0; i < grades.size(); i++) {
    std::cout << grades[i] << "\n";
}

This loop never needs a manual off-by-one fix. size() always matches.

Arrays vs. Vectors

  • Know the exact count? Array
  • Runtime count? Use a vector
  • Both use [ ] to read/write
ArrayVectorFixed sizeSet at declare timegrades[5]Grows as neededpush_back() to addstd::vector<int>

2D Arrays: Tables

A Grade Table

  • A table: rows and columns
  • Every student, every grade
  • One array of arrays
HW1HW2Dana9288Alex7881

Declaring a 2D Array

  • Two sizes: rows, then columns
  • table[row][col] finds a cell
  • Each cell is one grade
int table[2][2];
// 2 students, 2 assignments
table[0][0] = 92;
// Dana, HW1

Looping a 2D Array

  • Outer loop: each row
  • Inner loop: each column
  • Nested loops, from Module 4
for (int r = 0; r < 2; r++) {
    for (int c = 0; c < 2; c++) {
        std::cout << table[r][c] << " ";
    }
    std::cout << "\n";
}

Practice: Print the Table

  • table[0][0]=92, table[0][1]=88
  • table[1][0]=78, table[1][1]=81
  • What does row 1 print?

Answer: 78 81

Real Software Uses 2D Too

  • Spreadsheets store data too
  • Image pixels: row and column
  • Same 2D-array idea underneath
📊Spreadsheet grid🖼️Image pixel grid🔢Both: row, column

Recap: Arrays & Vectors

  • Array: fixed, fast, simple
  • Vector: grows, more flexible
  • 2D array: a grid of values
ToolSizeAdd?ArrayFixedNoVectorGrowspush_back2D ArrayFixed gridNo

Questions?

Practice Lab

Dice Roll Tally

  • Roll a die, store every result
  • Count how often each face hits
  • Find the most common roll
🎲Roll a die N times💾Store every roll📊Tally each face🏆Find the winner

Requirements

  • Ask the class for N (rolls)
  • Store each roll in an array
  • Count each face 1 through 6
⌨️Read N🎲Roll N times📋Tally & report

Step 1: Declare the Rolls Array

  • rolls holds up to 20 values
  • n is the actual roll count
  • 20 is just a safe upper limit
int n; // ask the class
int rolls[20];
// up to 20 rolls

Step 2: Roll and Store

  • Loop n times, once per roll
  • rand() % 6 + 1 gives 1 to 6
  • Store it directly in the array
for (int i = 0; i < n; i++) {
    rolls[i] = rand() % 6 + 1;
}

Uses the same rand() from Module 4. Still needs srand(time(0)) once, at the top of main.

Step 3: Print All Rolls

  • Loop through every stored roll
  • One line, space-separated
  • Confirms the array filled
for (int i = 0; i < n; i++) {
    std::cout << rolls[i] << ' ';
}

Step 4: A Tally Array

  • tally[0] counts face 1
  • tally[5] counts face 6
  • Every counter starts at zero
int tally[6] = {0, 0, 0, 0, 0, 0};
// one counter per face

⚠️ Use tally[roll - 1], not tally[roll]. Face 1 lives at index 0.

Step 5: Count with a Condition

  • All three ideas at once
  • if checks the roll is valid
  • roll-1 maps face to index
for (int i = 0; i < n; i++) {
    if (rolls[i] >= 1 && rolls[i] <= 6) {
        tally[rolls[i] - 1]++;
    }
}

Step 6: Print the Tally

  • f+1 turns index into a face
  • Prints face, then its count
  • One line per face, 1 through 6
for (int f = 0; f < 6; f++) {
    std::cout << (f+1);
    std::cout << ": " << tally[f] << "\n";
}

Step 7: Find the Most Common Roll

  • Same find-the-max pattern
  • best tracks the top index
  • best + 1 is the winning face
int best = 0;
for (int f = 1; f < 6; f++) {
    if (tally[f] > tally[best]) {
        best = f;
    }
}

Sample Output

  • n = 20 rolls, six tallies
  • Face 3 and face 6 tie at 5
  • Code keeps the first max seen
FaceCount132135425465

Deliverable

  • Write it: roll, tally, print
  • Show output for n = 20
  • One line: which face won, why
tally[0..5]301152234455face = index + 1

Questions?

Practice Lab Part 2

A Real System to Build

  • Not a game: a real system
  • A host seats real guests
  • No table gets double-booked
🍽️A guest wants a table🔍Find one that is free✅Reserve it, never twice

Existing Software Solves This

  • OpenTable, Resy: real apps
  • Same core idea underneath
  • We'll build a small version
🍴Real restaurants💻Use reservation software🛠️We build the same idea

Requirements

  • Track every table: free or not
  • Take reservations one by one
  • Stop when the floor is full
💾Store table status🔄Ask, check, reserve🔁Loop until full

Warm-Up: One Row of Tables

  • Start small: just one row
  • 10 tables, numbered 0 to 9
  • Scale up once this works
One Row (10 Tables)0123456789

Plan Your Variables

  • One int per table: 0 or 1
  • 0 means empty, 1 means taken
  • int, not bool: matches later
🔀A table has 2 states🔢0 = empty, 1 = reserved✅Use int for both

Step 1: Declare the Row

  • row holds 10 table slots
  • Index 0 is the 1st table
  • Not yet given a value
int row[10];  // 10 tables

Step 2: Fill It with Zeros

  • Loop once per table
  • 0 means the table is free
  • Runs before anyone arrives
for (int i = 0; i < 10; i++) {
    row[i] = 0;
}

Step 3: Print the Row

  • Loop through every table
  • Print each status in order
  • Confirms the row is empty
for (int i = 0; i < 10; i++) {
    std::cout << row[i] << ' ';
}

Check: What Does It Print?

  • After Steps 1-2-3 run
  • row has 10 tables, all free
  • What appears on screen?
Row After Step 20123456789

Answer: What Does It Print?

0 0 0 0 0 0 0 0 0 0
// ten zeros, space-separated
// one 0 per table, all free

One Row Isn't Enough

  • A real floor has many rows
  • One array can't hold a grid
  • Need rows AND columns
➡️10 tables in 1 row🏢A floor has many rows🔲Need a 2D array

⚠️ A 1D array can't hold a grid: it has no row and column.

Ten Rows of Ten

  • 10 rows, 10 tables each
  • 100 tables total on the floor
  • Row and column find each one
The Real Floor (10x10)

Plan Your Variables: The Floor

  • Same 0/1 idea, one more index
  • tables[row][col] finds one
  • row and col each 0 through 9
🔢int tables[10]➕add a 2nd [10] for columns🔲tables[10][10]

Step 4: Declare the Floor

  • 10 rows, 10 tables per row
  • Two sizes: [rows][columns]
  • All 100 still unset
int tables[10][10];

⚠️ Row comes first, then column: tables[row][col].

Step 5: Empty Every Table

  • Outer loop: pick the row
  • Inner loop: pick the column
  • Every cell starts at 0
for (int r = 0; r < 10; r++) {
  for (int c = 0; c < 10; c++) {
    tables[r][c] = 0;
  }
}

Step 6: Print the Floor

  • Inner loop prints one row
  • \n starts the next row
  • Result: a 10x10 grid on screen
for (int r = 0; r < 10; r++) {
  for (int c = 0; c < 10; c++) {
    std::cout << tables[r][c];
  }
  std::cout << "\\n";
}

Check: Rows or Columns First?

  • tables[2][7]: row 2, col 7
  • Which loop must be OUTER?
  • So each full row prints first
tables[2][7]

Answer: Rows or Columns First?

🔁Outer loop: row r🔂Inner loop: col c🖨️Print row, then newline
// outer = row: r = 2
// inner = col: c = 0..9
// tables[2][7] is the 8th
// cell printed on row 2

Requirements: One Reservation

  • Ask which table: row, column
  • Check the number is valid
  • Reserve it, or say it is taken
❓Ask for row, col✅Check it exists & is free🚪Reserve or refuse

Step 7: Ask for a Table

  • Two ints: row and column
  • One cin reads both at once
  • Host types them, space apart
int r, c;
std::cin >> r >> c;

Step 8: Check the Table Number

  • Row and column: 0 through 9
  • Anything else is off the floor
  • Catch it before using it
if (r < 0 || r > 9 ||
    c < 0 || c > 9) {
  std::cout << "No such table";
}

Step 9: Is It Empty?

  • 0 means nobody has it yet
  • Runs before we reserve it
  • Guards against double-booking
if (tables[r][c] == 0) {
  // reserve it: Step 10
}

Step 10: Reserve It

  • 1 marks the table as taken
  • Only runs inside the if above
  • Confirms it back to the host
tables[r][c] = 1;
std::cout << "Reserved!";

Step 11: Already Taken

  • else runs when it was not free
  • Same row/col, no change made
  • Host tries a different table
else {
  std::cout << "Table taken";
}

Sample Run: One Reservation

  • Host asked for table 2, 7
  • It was free, now reserved
  • Grid shows a 1 at row 2, col 7
Table (row col): 2 7Reserved!

How Do We Know We're Full?

  • Count every table still at 0
  • Zero empty means fully booked
  • Recheck after each reservation
🔍Scan all 100 tables🔢Count the zeros🈵0 empties = full

Step 12: Count Empty Tables

  • Same nested loop as Step 5
  • empty grows by 1 each 0 found
  • Reruns after every booking
int empty = 0;
for (int r = 0; r < 10; r++)
 for (int c = 0; c < 10; c++)
  if (tables[r][c] == 0) empty++;

Step 13: The Reservation Loop

  • while keeps going as long
  • as empty is above zero
  • Body: Steps 7 through 11
while (empty > 0) {
  // Steps 7-11 go here
}

Step 14: Recount After Each Booking

  • Last line inside the while
  • Rerun Step 12 to update empty
  • Loop rechecks the new value
while (empty > 0) {
  // ask, check, reserve
  // then recount:
  empty = 0;
  // (Step 12 loop again)
}

Step 15: Fully Booked

  • Loop ends on its own
  • empty reached zero
  • One message after the loop
// after the while loop ends:
std::cout << "Fully booked!";

Check: Trace the Loop

  • 99 tables reserved, 1 free
  • That 1 gets booked next
  • What does empty equal then?
1 Table Left (9, 9)

Answer: Trace the Loop

1️⃣empty was 1✅That table gets reserved0️⃣empty recounts to 0
// before: empty == 1
// reserve the last table
// recount: empty == 0
// while (0 > 0) is false
// loop stops, prints message

Sample Run: Filling the Floor

  • Booking after booking
  • Grid fills with 1s over time
  • Stops the moment empty hits 0
Table: 0 0 Reserved!Table: 0 1 Reserved!...Table: 9 9 Reserved!Fully booked!

Beyond Booking

  • Same array, more features
  • Cancel, count, search, report
  • Each is a small new loop
✅Book a table (done)🔧Cancel, count, search💡More useful, same array

Extension 1: Cancel a Reservation

  • Ask for a taken table
  • Set it back to 0: free again
  • empty grows by 1
tables[r][c] = 0;
empty++;
std::cout << "Canceled";

Extension 2: Count Reservations So Far

  • 100 minus empty tables
  • No new loop needed
  • One line, using what we track
int reserved = 100 - empty;

Extension 3: Occupancy Percentage

  • reserved out of 100 tables
  • 100.0 keeps the math decimal
  • Prints like "42.0%"
double pct = reserved * 100.0 / 100;
std::cout << pct << '%';

Extension 4: Find the First Empty Table

  • Same nested loop shape again
  • Stops at the first 0 it finds
  • Suggests a table to the host
for (int r = 0; r < 10; r++)
 for (int c = 0; c < 10; c++)
  if (tables[r][c] == 0) {
    // first empty: r, c
  }

Extension 5: Reprompt on Invalid Input

  • while re-asks until it fits
  • Loops back to Step 7 & 8
  • Host can never enter table 15
while (r < 0 || r > 9) {
  std::cout << "Try again: ";
  std::cin >> r;
}

Extension 6: Print Only Reserved Tables

  • Same grid scan, one more if
  • Skips every table still at 0
  • Shorter than the full grid
for (int r = 0; r < 10; r++)
 for (int c = 0; c < 10; c++)
  if (tables[r][c] == 1)
   std::cout << r << c << '\n';

Check: Extension Trace

  • Table (4, 4) just canceled
  • It was the only taken table
  • What does occupancy % show?
Only (4, 4) Was Taken

Answer: Extension Trace

1️⃣reserved was 10️⃣Cancel sets it back to 0🧮pct = 0 * 100.0 / 100
// reserved = 100 - empty
// empty becomes 100 again
// reserved = 0
// pct = 0.0  (0% occupied)

Reading tables[row][col]

  • First [ ]: which row
  • Second [ ]: which column
  • Order never swaps, ever
tables[3][6]: row 3, col 6

The Whole Program: Structure

  • Setup: declare & empty floor
  • Loop: ask, check, book, count
  • After: fully booked message
🏗️Setup the floor (Steps 4-6)🔁Reservation loop (Steps 7-15)🈵Fully booked!

Recap: What We Used

  • A 1D array, then a 2D array
  • Nested loops: row, then column
  • if/else and a while loop
  • cin for input, cout for output
🔲Arrays: 1D, then 2D🔁Loops: for, nested, while🔀if/else + cin/cout

Deliverable

  • Build the reservation system
  • Book, cancel, and find a table
  • Show it running fully booked
💻Write the program🧪Test book & cancel🈵Run until full

Questions?

Practice Quiz

Practice Quiz: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question.

Array
Index
Vector
Element
One single value stored inside an array
How many elements an array or vector holds
Accessing an index that doesn't exist
Visiting every element in order
Adds a new element to the end of a vector
Fixed-size list of same-type values
Position of a value inside an array
Array that can grow or shrink in size
Size
Out of Bounds
Traversal
push_back

Questions?

Looking Ahead: Module 6

Where We Are: Module 5

  • Module 5 done: arrays, vectors
  • Next: User-Defined Functions

Why This Matters

  • FORTRAN II added subprograms
  • ALGOL added scope, recursion
  • C++ adds overloading on top
1958FORTRAN II addsuser subprograms1960ALGOL 60 addsrecursion and scope1972C: every programis built from functions1985C++ adds overloadingand referencesTodaySmall named piecesin every language

The Problem: Repeated Code

  • Bill for 3 cars
  • Same formula, pasted 3 times
  • Fix one? Fix all three
double a = 3 * 120.0 + 35.0;
double b = 5 * 120.0 + 35.0;
double c = 2 * 120.0 + 35.0;

Copy-Paste Breaks

  • Shop fee rises to 40
  • Find every pasted copy
  • Miss one: a wrong bill
📋Same formula copied🔍Fee changes: edit each⚠️Miss one: wrong price

⚠️ Every pasted copy is a place a bug can hide.

Existing Software Solves This

  • Excel: =SUM(A1:A5)
  • Calculators: a sqrt button
  • Name it once, reuse it
📊Spreadsheet formulas🧮Calculator buttons🏷️One name, reusable

Word Origin: "Function"

functio
  • Latin: a performance
fungi
  • Latin: to perform, carry out

A function is a named task the program can perform on demand.

The Answer: A Named Block

  • Write the formula once
  • Give the block a name
  • Call the name anywhere
✏️Write it once🏷️Give it a name📞Call it many times

Check: Why Not Copy-Paste?

The shop fee rises from 35 to 40. With 3 pasted copies of the formula, how many places must you edit?

Answer
Three, and missing one gives a wrong bill. With one function, you edit one place.

Functions You Already Use

  • main is a function
  • sqrt is a function
  • Both use a name and ( )
#include <cmath>
int main() {
  double r = std::sqrt(81.0);
  std::cout << r;   // 9
  return 0;
}

Check: Spot the Function

In std::sqrt(81.0), which part is the function name, and which part is the input?

Answer
sqrt is the name. 81.0 is the input, passed inside the parentheses.

Questions?

Declaring & Calling

Anatomy of a Function

  • Return type, then the name
  • Parameters go in ( )
  • The body goes in { }
doublereturn type: what comes backcostname: what we call it(int hours)parameter list: the input{ ... }body: the code that runs

Requirements: Repair Bill

  • Given the labor hours
  • Compute the repair bill
  • Do it for any car
🚗Read the hours🧮Compute the cost🖨️Print the bill

Step 1: Define a Function

  • double: what it gives back
  • cost: the name we chose
  • Body sits between braces
double cost() {
  return 3 * 120.0 + 35.0;
}

Step 2: Call It

  • Write the name and ( )
  • The call runs the body
  • The value comes back
int main() {
  double bill = cost();
  std::cout << bill;
  return 0;
}

Define Before You Call

  • Compiler reads top to bottom
  • cost must appear above main
  • Else: not declared
double cost() {
  return 395.0;
}

int main() {
  std::cout << cost();
}

⚠️ Calling a function before its definition is a compile error.

Check: Above or Below?

main calls cost(). Should cost be written above or below main, and why?

Answer
Above. The compiler reads top to bottom, so it must know cost before the call.

Trace: What Prints?

What does this program print?

int five() { return 5; }

int main() {
  std::cout << five() + 2;
}
Answer
7. five() returns 5, and then 5 + 2 is 7.

Many Calls, One Definition

  • Call cost() as often as needed
  • Its body is written once
  • Each call runs it again
📞Call #1📞Call #2🏷️Same body runs each time

Check: Count the Bodies

cost() is called in three places in main. How many times is its body written?

Answer
Once. Every call reuses that single body.

Recap: Declaring & Calling

  • Define: type name() { }
  • Call: name();
  • Define above the call
✏️Define it📞Call it↩️Value returns

Questions?

Parameters & Returns

The Problem: One Fixed Answer

  • cost() always gives 395
  • Cars need other hours
  • We must pass a number in
🚗3 hours📚5 hours🔒cost() ignores both

Word Origin: "Parameter"

para + metron
  • Greek: beside + measure
parametrum
  • Modern Latin, 1600s

A parameter is a measurable value that stands beside the formula.

Parameters vs. Arguments

  • Parameter: the placeholder
  • Argument: the real value
  • In cost(3), 3 is one
int hoursparameter: a named placeholdercost(3)argument: the value 3

Step 1: Add a Parameter

  • int hours: a local variable
  • Each call fills it in
  • Use it inside the body
double cost(int hours) {
  return hours * 120.0 + 35.0;
}

Step 2: Pass an Argument

  • 3 fills in hours
  • 5 fills it the next time
  • One function, many answers
double a = cost(3);
double b = cost(5);
std::cout << a << " " << b;

Check: Which Value?

double cost(int hours) returns hours * 100.0. What does cost(3) return?

Answer
300.0. hours is 3, and 3 * 100.0 is 300.0.

Step 3: Two Parameters

  • Separate them with commas
  • Each needs its own type
  • Calls pass them in order
double cost(int hours, double rate) {
  return hours * rate + 35.0;
}

Order Matters

  • Arguments match by position
  • First goes to hours
  • Swapped: a wrong bill
cost(3, 120.0);   // right
cost(120.0, 3);   // wrong order

⚠️ The compiler may accept swapped arguments of convertible types and still give a wrong answer.

Check: Match the Arguments

double cost(int hours, double rate). In cost(2, 150.0), what is rate?

Answer
150.0. Arguments match parameters by position, so 2 goes to hours.

Return Values

  • return sends a value back
  • Its type matches the function
  • The function ends there
📥Arguments go in⚙️The body runs📤return sends the result

Word Origin: "Return"

retourner
  • Old French: to turn back
return
  • Result turns back to caller

A return hands the result back to the code that made the call.

Using the Returned Value

  • Store it in a variable
  • Or print it directly
  • Or use it in math
double t = cost(3, 120.0);
std::cout << cost(5, 120.0);
double all = t + cost(2, 120.0);

Return Ends the Function

  • Code after return is skipped
  • First return that runs wins
  • Use it to exit early
int half(int n) {
  return n / 2;
  std::cout << "never";  // skipped
}

Check: Write max2

Write max2: it takes two ints and returns the larger one.

int max2(int a, int b) {
  if (a > b) {
    return a;
  }
  return b;
}

Check: Which Return Type?

A function averages two int MPG readings and may give 34.5. Which return type fits, int or double?

Answer
double. An int would drop the .5, so 34.5 would become 34.

Example: MPG Rating

  • Takes an mpg, returns a char
  • Several returns, one runs
  • Reads like a rating scale
char rating(int mpg) {
  if (mpg >= 40) return 'A';
  if (mpg >= 30) return 'B';
  if (mpg >= 20) return 'C';
  if (mpg >= 10) return 'D';
  return 'F';
}

Check: Trace rating(35)

Using rating() from the last slide, what does rating(35) return?

Answer
'B'. 35 fails the >= 40 test, then passes >= 30, so it returns 'B'.

Recap: Parameters & Returns

  • Parameters take input
  • return sends output
  • Types must match
📥Parameters: input📤return: output✅Types must match

Questions?

void & Prototypes

Functions With No Result

  • Some functions just do work
  • Print a header, log a line
  • No value comes back
🖨️Print a report header🚫Nothing is returned🏷️Use void as the type

Word Origin: "Void"

voide
  • Old French: empty
vacivus
  • Latin: empty, unoccupied

A void function returns nothing: its result slot is empty.

Step 1: A void Function

  • void: nothing comes back
  • No return value needed
  • It just prints a banner
void banner() {
  std::cout << "== AutoCare ==\n";
}

Step 2: Call a void Function

  • Call it as its own statement
  • No variable to store into
  • Cannot be used in math
int main() {
  banner();
  std::cout << "Oil Change\n";
  banner();
}

Check: void or Not?

Which one needs a return type other than void: printReceipt() or totalFee()?

Answer
totalFee. It hands a number back. printReceipt only prints, so it is void.

The Ordering Problem

  • main is often written first
  • Helpers sit below it
  • The compiler wants a heads-up
✏️main calls cost()❓cost is defined below🚫Error: not declared

Word Origin: "Prototype"

protos
  • Greek: first
typos
  • Greek: impression, model

A prototype is the first, early model of a function: just its shape.

Step 3: Write a Prototype

  • Signature only, then a ;
  • Goes above main
  • The body can live below
double cost(int hours);   // prototype

int main() {
  std::cout << cost(3);
}

double cost(int hours) {
  return hours * 120.0;
}

Check: Will This Build?

The prototype says double cost(int). The definition says double cost(double). Will it build?

Answer
No. They are different functions, so the prototype has no body and linking fails.

Questions?

Scope & Lifetime

Where Is a Variable Seen?

  • A variable lives in its braces
  • Outside them it is unknown
  • Each function has its own
main()x lives herecost()hours and total live hereNo sharingneither sees the other

Word Origin: "Scope"

skopos
  • Greek: a target, a watcher
scopo
  • Italian: aim, purpose

Scope is the range a variable can see: its field of view.

Local Variables

  • total exists only in cost
  • main cannot read it
  • It vanishes on return
double cost(int hours) {
  double total = hours * 120.0;
  return total;
}
// total is unknown out here

Error: Out of Scope

  • cost(3) ran and finished
  • Its total is already gone
  • main cannot see total
int main() {
  cost(3);
  std::cout << total;   // error
}

⚠️ A local variable is destroyed when its function returns.

Check: Can main See It?

cost declares double total inside its braces. Can main print total? Why?

Answer
No. total is local to cost. main only gets its value if cost returns it.

Same Name, No Clash

  • twice changes its own n
  • main's n stays 5
  • Each call gets a fresh n
int twice(int n) {
  n = n * 2;
  return n;
}
// main: int n = 5; twice(n);
// main's n is still 5

Trace: Which n?

What does this program print?

int twice(int n) { return n * 2; }

int main() {
  int n = 4;
  twice(n);
  std::cout << n;
}
Answer
4. twice returned 8, but the result was thrown away and main's n never changed.

Global vs. Parameter

  • const globals are safe
  • The value never changes
  • A name beats a magic 35
const double SHOP_FEE = 35.0;

double bill(int hours) {
  return hours * 120.0 + SHOP_FEE;
}

Check: Global or Param?

hours changes for every car. Should it be a global variable or a parameter?

Answer
A parameter. Data that changes belongs in a parameter, not in a global.

Recap: Scope & Lifetime

  • Locals live in their braces
  • They die on return
  • Same name, separate boxes
🔒Locals stay inside↩️Gone on return🧩Separate boxes per call

Questions?

Pass by Reference

Copies by Default

  • Arguments are copied in
  • The function edits the copy
  • Your variable stays the same
📦main: x = 5📋A copy goes in: n = 5✏️Function edits its copy

Pass by Value

  • bump changes only n
  • x is untouched
  • This is pass by value
void bump(int n) {
  n = n + 10;
}
// main: int x = 5;
// bump(x);  x is still 5

Trace: Did x Change?

What does this program print?

void bump(int n) { n = n + 10; }

int main() {
  int x = 5;
  bump(x);
  std::cout << x;
}
Answer
5. bump changed its own copy of x, not x itself.

Word Origin: "Reference"

referre
  • Latin: to carry back
reference
  • A name for the original

A reference is a second name that carries you back to the same variable.

Pass by Reference

  • Add & after the type
  • No copy: a second name
  • Edits change the original
📦main: x = 5🔗n is another name for x✏️Edit n, and x changes

Step 1: Add the &

  • int& means a reference
  • n is x itself
  • The body is unchanged
void bump(int& n) {
  n = n + 10;
}

Step 2: Call It

  • The call looks the same
  • x becomes 15
  • No copy was made
int x = 5;
bump(x);
std::cout << x;   // 15

Check: Spot the Difference

One character separates pass by value from pass by reference in the parameter list. Which one?

Answer
The &. int& n is a reference to the original; int n is a copy.

Example: Swap Two Values

  • Both parameters are references
  • A temp holds one value
  • Swaps the callers' variables
void swap2(int& a, int& b) {
  int tmp = a;
  a = b;
  b = tmp;
}

Trace: After the Swap

Using swap2 from the last slide, what prints?

int x = 3;
int y = 8;
swap2(x, y);
std::cout << x << " " << y;
Answer
8 3. Both parameters are references, so x and y themselves were swapped.

Arrays as Parameters

  • Arrays are never copied
  • It edits the real one
  • Pass the size too
void zero(int a[], int n) {
  for (int i = 0; i < n; i++)
    a[i] = 0;
}
// zero(readings, 5);

Check: Why Pass n?

Why must zero() take n as a second parameter?

Answer
An array parameter does not carry its length. The function needs n to know where to stop.

Recap: Pass by Reference

  • Value: a copy is edited
  • Reference: the original
  • Arrays: always the original
📋Value: edit a copy🔗Reference: the original📚Arrays: the original

Questions?

Overloading & Defaults

Same Name, Different Inputs

  • C++ allows one name twice
  • Parameter lists must differ
  • The compiler picks a match
🏷️cost(int hours)🏷️cost(int, double rate)🎯The arguments pick one

Overloading cost()

  • Two versions of cost
  • Different parameter lists
  • Both are valid together
double cost(int hours) {
  return hours * 120.0;
}
double cost(int hours, double rate) {
  return hours * rate;
}

Check: Which cost() Runs?

Given the two cost() versions, which one runs for cost(3), and which for cost(3, 150.0)?

Answer
cost(3) runs the one-parameter version. cost(3, 150.0) runs the two-parameter one.

Default Arguments

  • rate has a default value
  • The caller may leave it out
  • cost(3) uses 120.0
double cost(int hours,
           double rate = 120.0) {
  return hours * rate;
}

Check: Which Rate?

With the default above, what rate does cost(3) use? What about cost(3, 150.0)?

Answer
cost(3) uses 120.0. cost(3, 150.0) uses 1600.0: a passed argument overrides the default.

Defaults Go Last

  • Right-most parameters only
  • No gaps allowed
  • Else: a compile error
(int c, double r=1)legal: default on the right(double r=1, int c)error: default on the left

⚠️ A parameter with a default cannot come before one without.

Check: Is It Legal?

Is double cost(double rate = 120.0, int hours) legal C++?

Answer
No. Once a parameter has a default, every parameter after it needs one too.

Questions?

Practice Lab

Requirements: Service Shop Tool

  • Compute a repair bill
  • Turn an MPG into a rating
  • Report the average MPG
🧮cost(hours)🚗rating(mpg)📊average(g, n)

Plan Your Functions

Name the three functions this tool needs, and the return type of each.

Answer
cost: double. rating: char. average: double. Each takes the input it needs.

Step 1: Prototypes

  • Signatures go above main
  • Bodies come below main
  • The tool reads top-down
double cost(int hours);
char rating(int mpg);
double average(int g[], int n);

Step 2: cost()

  • Hours times the rate
  • Plus a flat 35.0 shop cost
  • Returns the bill
double cost(int hours) {
  return hours * 120.0 + 35.0;
}

Step 3: rating()

  • Highest cutoff first
  • Returns as soon as one hits
  • F is the fallback
char rating(int mpg) {
  if (mpg >= 40) return 'A';
  if (mpg >= 30) return 'B';
  if (mpg >= 20) return 'C';
  return 'F';
}

Step 4: average()

  • Loop over n readings
  • Add each into sum
  • Divide by n at the end
double average(int g[], int n) {
  double sum = 0;
  for (int i = 0; i < n; i++)
    sum += g[i];
  return sum / n;
}

Check: Why i < n?

In average(), why does the loop stop at i < n and not at a fixed 5?

Answer
The array does not know its length. Using n lets one function work for any fleet size.

Step 5: Ask the Class

  • Read the hours taken
  • Ask the class for a value
  • Store it in an int
int hours;
std::cout << "Hours: ";
std::cin >> hours;   // ask the class

Step 6: MPG Report

  • Five MPGs in an array
  • rating() per reading
  • average() for the fleet
int g[5] = {42, 28, 35, 51, 18};
for (int i = 0; i < 5; i++)
  std::cout << rating(g[i]) << " ";
std::cout << average(g, 5);

Sample Run: Service Shop Tool

  • Hours from the class
  • MPGs come from the array
  • Every result via a function
Hours: 3Bill: 395A C B A FAverage: 34.8

Extension: void Helper

Write a void function printLine that prints a line of 20 dashes.

void printLine() {
  std::cout << "--------------------\n";
}

Extension: By Reference

Write refuel(double& tank) that adds 5.0 to the caller's tank.

void refuel(double& tank) {
  tank = tank + 5.0;
}
// refuel(t);  t changes

Deliverable

  • Write all three functions
  • Add printLine and refuel
  • Run it, show the output
✏️Write the functions🧪Test each one✅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
6x6 Example Board111💣11💣💣💣

The Rules

  • Click a cell to reveal it
  • A mine ends the game
  • A number: mines touching it
This 1: one mine touches it111💣11💣💣💣

Win or Lose

  • Reveal a mine: you lose
  • Reveal all safe cells: you win
  • Numbers guide safe guesses
💣Hit a mine: lose🔢Reveal a number🏆Clear the board: win

Plan Your Functions

  • Break the game into pieces
  • Each piece: one function
  • Functions call each other
initBoardstart every cell emptyplaceMinesscatter mines randomlycountAdjacentmines touching one cellfillNumbersset every safe cell&#39;s countprintBoardshow the board on screenrevealCelluncover one cellisWoncheck if the game is won

Why Functions First?

  • Each function: one clear job
  • Loops and arrays live inside
  • main() calls them in order
🔧Plan the functions🔄Loops go inside each one🔗main() connects them

Step 1: Board Constants

  • SIZE: the board is 6x6
  • A named constant, not 6
  • Used everywhere below
const int 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
void initBoard(int b[SIZE][SIZE]);
void placeMines(int b[SIZE][SIZE], int n);
int countAdjacent(int b[SIZE][SIZE],
                  int r, int c);
void fillNumbers(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
🖥️A blank grid to start🔄Loop every row and col✅Set each cell to 0

Step 4: initBoard, the Loop

  • Outer loop: pick the row
  • Inner loop: pick the column
  • Nested: every cell, once
void initBoard(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
void initBoard(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
🎲Pick a random row, col❓Already a mine?💣No: mark it -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
void placeMines(int b[SIZE][SIZE], int n) {
  int placed = 0;
  while (placed < n) {
    // pick a cell next
  }
}

Step 8: placeMines, Pick a Cell

  • rand() % SIZE: 0 through 5
  • One call for row, one for col
  • A random spot each time
int r = rand() % SIZE;
int c = rand() % SIZE;

Step 9: placeMines, Avoid Repeats

  • -1 already means a mine
  • Skip it: try again next loop
  • Otherwise: place the mine
if (b[r][c] == -1) {
  continue;
}
b[r][c] = -1;
placed++;

⚠️ 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
Center + 8 Neighbors💣💣💣

Requirements: countAdjacent

  • Takes the board, one row, col
  • Checks the 8 cells around it
  • Returns how many are mines
📌Given one cell (r, c)🔍Scan its 8 neighbors🔢Return the mine count

Step 10: countAdjacent, Setup

  • count: mines found so far
  • dr, dc range -1 to 1
  • That pair covers all 8 cells
int countAdjacent(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
💣Mines are already placed🔄Visit every safe cell🔢Store its mine count

Step 15: fillNumbers

  • Skip cells that are already -1
  • Otherwise: call countAdjacent
  • Store the result in that cell
void fillNumbers(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
# = hidden, else revealed1

Step 16: printBoard, the Loop

  • Same nested-loop shape again
  • One character printed per cell
  • A newline after each row
void printBoard(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
👀Player picks a cell✅Mark it revealed❓Was it a mine?

Step 19: revealCell

  • bool return: true means mine
  • Set revealed first, always
  • Then check what was under it
bool revealCell(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
🔄Scan every cell❓Safe and still hidden?🏆None found: you won

Step 20: isWon

  • Look for one hidden safe cell
  • Found one: return false
  • None found: the player won
bool isWon(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])
        return false;
  return true;
}

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.

Requirements: main()

  • Set up the board once
  • Loop: show board, ask, reveal
  • Stop on a mine or a win
setupinit, place, fillloopprint, ask, revealendlose or win message

Step 21: main(), Setup

  • Seed random, then set up
  • Order: mines placed, then fill
  • Ten mines on a 6x6 board
srand(time(0));
initBoard(board);
placeMines(board, 6);
fillNumbers(board);

Step 22: main(), the Game Loop

  • won starts false
  • Loop while not won
  • Body: print, ask, reveal
bool won = false;
while (!won) {
  printBoard(board, revealed);
  // ask for a cell next
}

Step 23: main(), Ask for a Cell

  • Two ints: row and column
  • One cin reads both
  • Player types them, space apart
int r, c;
std::cout << "Row col: ";
std::cin >> r >> c;

Step 24: main(), Reveal It

  • hitMine: true if it was one
  • revealCell does the real work
  • Next: react to hitMine
bool hitMine = revealCell(board,
                            revealed, r, c);

Step 25: main(), Lose Path

  • hitMine true: game over
  • Print the board one last time
  • break: exit the while loop
if (hitMine) {
  printBoard(board, revealed);
  std::cout << "Boom! You lost.";
  break;
}

Step 26: main(), Win Path

  • isWon: checks the whole board
  • True: set won, loop will stop
  • False: while loop runs again
won = isWon(board, revealed);
if (won) {
  printBoard(board, revealed);
  std::cout << "You win!";
}

Sample Run: A Few Turns

  • Board reprints after each move
  • A number: safe, keep going
  • Boom or You win: the loop ends
Row col: 0 01###########Row col: 5 51#########00...

Check: Trace the Break

  • revealCell returns true
  • main() checks hitMine next
  • What happens right after that?
// The board prints once more,
// a lose message shows, and
// break exits the while loop.

How It All Fits Together

  • main() calls each function
  • Setup runs once, loop repeats
  • Every piece has one clear job
initBoard, placeMinessetup: oncefillNumberssetup: onceprintBoard, revealCellloop: every turnisWonloop: checked every turn

Recap: What We Used

  • Functions: one job each
  • Nested loops: rows and columns
  • Arrays: the board and revealed
  • if/else: bounds, mine checks
🔧Functions organize the code🔄Loops walk the grid🔲Arrays hold the state

Extension 1: Flag a Cell

  • A flagged array, like revealed
  • Player marks a suspected mine
  • printBoard shows F, not #
bool flagged[SIZE][SIZE];
// set true on a flag command
// printBoard checks it before #

Extension 2: Count Remaining

  • Track safe cells still hidden
  • Total safe cells, minus shown
  • Print it each turn as a hint
['int total = SIZE * SIZE - 6;', '// subtract revealed count too']

Extension 3: Bigger Board

  • Change SIZE to a larger value
  • Scale the mine count with it
  • Everything else stays the same
['const int SIZE = 10;', 'placeMines(board, 15);']

Deliverable

  • Write all seven functions
  • Add one extension you like
  • Play it: win once, lose once
💻Write the functions🧪Test win and lose✅Add one extension

Questions?

Practice Lab Part 3

CampusNav: The Story

  • Shuttle office needs CampusNav
  • At the end: merge into one

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.

CAMPUSNAV ROUTE0isValidStop1nextStop2stopType3isRushHour4totalDistance5buildCumulative6reverseRoute7printCountdownEach stop on the route: one function

Student 1: isValidStop()

Signature: bool isValidStop(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.

bool isValidStop(int stop, int total) {
  if (stop < 0) return false;
  if (stop >= total) return false;
  return true;
}

Student 2: nextStop()

Signature: int nextStop(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.

int nextStop(int cur, int total) {
  if (cur + 1 >= total) return 0;
  return cur + 1;
}

Student 3: stopType()

Signature: char stopType(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.

char stopType(int stop) {
  if (stop < 3) return 'B';
  if (stop < 6) return 'T';
  return 'W';
}

Student 4: isRushHour()

Signature: bool isRushHour(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.

bool isRushHour(int hr) {
  if (hr == 7 || hr == 8 || hr == 9)
    return true;
  if (hr == 16 || hr == 17 || hr == 18)
    return true;
  return false;
}

Student 5: totalDistance()

Signature: int totalDistance(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.

int totalDistance(int dist[], int n) {
  int sum = 0;
  int i = 0;
  while (i < n) {
    sum += dist[i];
    i++;
  }
  return sum;
}

Student 6: buildCumulative()

Signature: void buildCumulative(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.

void buildCumulative(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: void reverseRoute(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.

void reverseRoute(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: void printCountdown(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.

void printCountdown(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
Stop 3 valid? yesNext stop: 4 (Train)Rush hour? yesTotal trip: 9 miles3 stops left... 2... 1

Deliverable

  • Write your one function
  • Test it against its cases
  • Merge and run CampusNav
✏️Write your function🧪Test it✅Merge and run

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
Named block of reusable code
Variable listed in a function's definition
Actual value passed into a function call
Prototype
Scope
Pass by Reference
void

Questions?

Looking Ahead: Module 7

Where We Are: Module 6

  • Module 6 done: functions
  • Next: Objects and Classes

Module 7

Objects and Classes

class Car make, model, year mileage (the object's state) drive(miles) getInfo() (the object's behavior) One car. One object.

What Is an Object?

Why This Matters

  • Simula 67 invented the class
  • C++ began as C with Classes
  • Now core to most languages
1967Simula 67 (Dahl & Nygaard,Norway) introduces the class1972Smalltalk (Alan Kay, XeroxPARC): “everything is an object”1979“C with Classes”(Bjarne Stroustrup, Bell Labs)1983Renamed C++TodayObjects and classes are coreto nearly every major language

What Is an Object?

A CAR, AS AN OBJECT STATE make: "Honda" model: "Civic" year: 2024 mileage: 0 what the car HAS BEHAVIOR drive(miles) refuel() getInfo() what the car DOES An object bundles its own state with its own behavior.

Quick Example: Engine

  • Engine: under the hood
  • State: horsepower, cylinders
  • Behavior: start()
class Engine {
private:
  double horsepower;
  int cylinders;
public:
  void start();
};

Quick Example: Transmission

  • Transmission: shifts the gears
  • State: type, gears
  • Behavior: shift()
class Transmission {
private:
  string type;
  int gears;
public:
  void shift();
};

Quick Example: Battery

  • Battery: powers the car
  • State: voltage, cycleCount
  • Behavior: charge()
class Battery {
private:
  double voltage;
  int cycleCount;
public:
  void charge();
};

Quick Example: FuelTank

  • FuelTank: holds the gas
  • State: capacity, level
  • Behavior: refill()
class FuelTank {
private:
  double capacity;
  double level;
public:
  void refill();
};

Quick Example: Tire

  • Tire: meets the road
  • State: size, treadDepth
  • Behavior: needsReplacing()
class Tire {
private:
  int size;
  double treadDepth;
public:
  bool needsReplacing();
};

Quick Example: Brake

  • Brake: slows the car
  • State: type, padWear
  • Behavior: apply()
class Brake {
private:
  string type;
  double padWear;
public:
  void apply();
};

Quick Example: Dashboard

  • Dashboard: shows the driver
  • State: speed, warningLight
  • Behavior: update()
class Dashboard {
private:
  int speed;
  bool warningLight;
public:
  void update();
};

Quick Example: Odometer

  • Odometer: tracks distance
  • State: totalMiles, isDigital
  • Behavior: addMiles()
class Odometer {
private:
  double totalMiles;
  bool isDigital;
public:
  void addMiles();
};

Quick Example: GPS

  • GPS: finds the way
  • State: latitude, longitude
  • Behavior: getLocation()
class GPS {
private:
  double latitude;
  double longitude;
public:
  string getLocation();
};

Quick Example: AirbagSystem

  • AirbagSystem: protects riders
  • State: deployed, sensorCount
  • Behavior: deploy()
class AirbagSystem {
private:
  bool deployed;
  int sensorCount;
public:
  void deploy();
};

Quick Example: Headlight

  • Headlight: lights the road
  • State: isOn, bulbType
  • Behavior: toggle()
class Headlight {
private:
  bool isOn;
  string bulbType;
public:
  void toggle();
};

Quick Example: Mirror

  • Mirror: shows what is behind
  • State: position, isHeated
  • Behavior: adjust()
class Mirror {
private:
  string position;
  bool isHeated;
public:
  void adjust();
};

Quick Example: Seat

  • Seat: holds the driver
  • State: position, isHeated
  • Behavior: recline()
class Seat {
private:
  int position;
  bool isHeated;
public:
  void recline();
};

Quick Example: Radio

  • Radio: plays the music
  • State: frequency, volume
  • Behavior: tune()
class Radio {
private:
  double frequency;
  int volume;
public:
  void tune();
};

Quick Example: Sunroof

  • Sunroof: opens to the sky
  • State: isOpen, tiltAngle
  • Behavior: open()
class Sunroof {
private:
  bool isOpen;
  int tiltAngle;
public:
  void open();
};

Quick Example: Wiper

  • Wiper: clears the rain
  • State: speed, isOn
  • Behavior: activate()
class Wiper {
private:
  int speed;
  bool isOn;
public:
  void activate();
};

Quick Example: ClimateControl

  • ClimateControl: sets the temp
  • State: temperature, isOn
  • Behavior: setTemp()
class ClimateControl {
private:
  double temperature;
  bool isOn;
public:
  void setTemp();
};

Quick Example: Mechanic

  • Mechanic: fixes the car
  • State: name, yearsExperience
  • Behavior: repair()
class Mechanic {
private:
  string name;
  int yearsExperience;
public:
  void repair();
};

Quick Example: Customer

  • Customer: owns the car
  • State: name, phone
  • Behavior: requestService()
class Customer {
private:
  string name;
  string phone;
public:
  void requestService();
};

Quick Example: Dealership

  • Dealership: sells the cars
  • State: name, inventoryCount
  • Behavior: sellCar()
class Dealership {
private:
  string name;
  int inventoryCount;
public:
  void sellCar();
};

Quick Example: Garage

  • Garage: houses the bays
  • State: bayCount, isOpen
  • Behavior: openBay()
class Garage {
private:
  int bayCount;
  bool isOpen;
public:
  void openBay();
};

Quick Example: ParkingSpot

  • ParkingSpot: holds one car
  • State: number, isOccupied
  • Behavior: park()
class ParkingSpot {
private:
  int number;
  bool isOccupied;
public:
  void park();
};

Quick Example: ServiceAppt

  • ServiceAppt: books the visit
  • State: date, serviceType
  • Behavior: confirm()
class ServiceAppt {
private:
  string date;
  string serviceType;
public:
  void confirm();
};

Quick Example: Invoice

  • Invoice: bills the work
  • State: amount, isPaid
  • Behavior: markPaid()
class Invoice {
private:
  double amount;
  bool isPaid;
public:
  void markPaid();
};

Quick Example: Insurance

  • Insurance: covers the car
  • State: provider, premium
  • Behavior: isActive()
class Insurance {
private:
  string provider;
  double premium;
public:
  bool isActive();
};

Quick Example: Warranty

  • Warranty: covers a repair
  • State: monthsLeft, covers
  • Behavior: isValid()
class Warranty {
private:
  int monthsLeft;
  string covers;
public:
  bool isValid();
};

Quick Example: TestDrive

  • TestDrive: tries the car
  • State: minutes, route
  • Behavior: start()
class TestDrive {
private:
  int minutes;
  string route;
public:
  void start();
};

Quick Example: Inspection

  • Inspection: checks it passes
  • State: date, passed
  • Behavior: record()
class Inspection {
private:
  string date;
  bool passed;
public:
  void record();
};

Quick Example: LicensePlate

  • LicensePlate: IDs the car
  • State: number, state
  • Behavior: isExpired()
class LicensePlate {
private:
  string number;
  string state;
public:
  bool isExpired();
};

Quick Example: Registration

  • Registration: makes it legal
  • State: expires, owner
  • Behavior: renew()
class Registration {
private:
  string expires;
  string owner;
public:
  void renew();
};

Quick Example: LoanerCar

  • LoanerCar: a spare car
  • State: model, free
  • Behavior: checkOut()
class LoanerCar {
private:
  string model;
  bool free;
public:
  void checkOut();
};

Quick Example: TradeIn

  • TradeIn: swaps for a new car
  • State: model, estValue
  • Behavior: appraise()
class TradeIn {
private:
  string model;
  double estValue;
public:
  void appraise();
};

Quick Example: KeyFob

  • KeyFob: locks the car
  • State: batteryLow, range
  • Behavior: lock()
class KeyFob {
private:
  bool batteryLow;
  int range;
public:
  void lock();
};

Objects Are Everywhere

  • A phone: a Contact object
  • A game: a Player object
  • A store app: a Cart object
📱 Contact object 🎮 Player object 🛒 Cart object 🚗 Car object (this module)

Check: State or Behavior?

Is a car's color state or behavior? What about honk()?

color is state (something the car HAS). honk() is behavior (something the car DOES).

Questions?

Classes: The Blueprint

One Class, Many Objects

class Car Honda Civic one Car object Ford F-150 one Car object Tesla Model 3 one Car object One class, many objects: each car has its own make, model, and mileage, built from the same blueprint.

Step 1: An Empty Class

  • class is a new keyword
  • Car: the blueprint's name
  • Semicolon after the braces
class Car {

};

Step 2: Create Objects

  • Car: the type, like int
  • c1, c2: two Car objects
  • Each is separate and own data
Car c1;
Car c2;

Check: Class or Object?

Is Car a class or an object? Is c1 a class or an object?

Car is the class (the blueprint). c1 is an object (one actual car built from it).

Questions?

Member Variables

Member Variables = State

  • Each object's own data
  • Live inside the class body
  • One copy per object
class Car string make; string model; int year; double mileage; member variables

Step 3: Add Member Variables

  • string for make and model
  • int for the year
  • double for mileage
class Car {
  string make;
  string model;
  int year;
  double mileage;
};

Step 4: Dot Notation

  • object.member: one field
  • Reads just like English
  • Each object, its own copy
c1.make = "Honda";
c1.year = 2024;
std::cout << c1.make;

Check: Separate Copies?

c1.year = 2024; c2.year = 2019;. What is c1.year now?

Still 2024. Each object has its own separate copy of every member variable.

Questions?

Constructors

Why a Constructor?

  • Without one: junk start data
  • A constructor runs on creation
  • Guarantees a valid start state
No constructor mileage: ? With constructor mileage: 0 A constructor sets every member variable to a real, known value the moment the object is created, every single time.

Step 5: A Constructor

  • Same name as the class
  • No return type at all
  • Runs once, when c1 is made
Car() {
  mileage = 0;
}

Step 6: Take Parameters

  • Pass in starting values
  • this->make avoids a clash
  • Sets all four fields at once
Car(string mk, string md, int yr) {
  make = mk;
  model = md;
  year = yr;
  mileage = 0;
}

Check: Which Runs First?

Car c1("Honda", "Civic", 2024);. When does the constructor run?

Immediately: the moment c1 is created, before any other line touches c1.

Step 7: Build an Object

  • Values go in the parentheses
  • Matches the constructor order
  • c1 starts fully set up
Car c1("Honda", "Civic", 2024);

Questions?

Member Functions

Behavior = Member Functions

  • Live inside the class too
  • Can read/change member vars
  • Called with dot notation
class Car drive(miles) getInfo() member functions c1.drive(50);

Step 8: drive() Function

  • void: returns nothing
  • Adds miles to mileage
  • Changes this object in place
void drive(double miles) {
  mileage += miles;
}

Step 9: getInfo() Function

  • Returns a formatted string
  • Reads this object's own fields
  • No parameters at all
string getInfo() {
  return make + " " + model;
}

Check: Whose Mileage?

c1.drive(50); c2.drive(10);. Does this change c1's mileage or c2's?

Each call only changes its own object. c1.drive(50) only updates c1.mileage.

Sample Run: Car Object

Car c1("Honda", "Civic", 2024); c1.drive(50); cout << c1.getInfo(); Honda Civic mileage is now 50

Questions?

Public vs Private

Why Hide Data?

  • mileage = -500 makes no sense
  • private blocks direct access
  • public methods control changes
Wide open c1.mileage = -500; Protected setMileage() checks Encapsulation: hide the raw data, expose only safe, controlled ways to read or change it.

Step 10: private / public

  • private: hidden from outside
  • public: the object's interface
  • Members default to private
class Car {
private:
  double mileage;
public:
  void drive(double m);
};

Step 11: A Safe Getter

  • Lets code read mileage
  • Still can't be set directly
  • Read-only, one-way access
double getMileage() {
  return mileage;
}

Check: Can It Compile?

mileage is private. Does c1.mileage = 10; outside the class compile?

No. Outside code cannot touch a private member directly, by design.

Extension: isNew()

Write isNew(), returning true when mileage is under 500.

bool isNew() {
  return mileage < 500;
}

Questions?

Practice Lab

Requirements: Dealership Tool

  • Track one car for sale
  • Record a test drive's miles
  • Print a one-line summary
🚗Car object🚗💨drive() updates it📋getInfo() reports it

Plan Your Class

Name the private fields and the two public functions this tool needs.

make, model, year, mileage (private). drive(miles) and getInfo() (public).

Step 1: Class Skeleton

  • Four private fields
  • public: starts the interface
  • Constructor comes next
class Car {
private:
  string make, model;
  int year;
  double mileage;
public:
};

Step 2: The Constructor

  • Takes make, model, year
  • mileage always starts at 0
  • Goes inside public:
Car(string mk, string md, int yr) {
  make = mk; model = md; year = yr;
  mileage = 0;
}

Step 3: drive()

  • Takes the miles driven
  • Adds onto mileage
  • Returns nothing
void drive(double miles) {
  mileage += miles;
}

Step 4: getInfo()

  • Builds one summary string
  • Combines make, model, miles
  • Returns it to the caller
string getInfo() {
  return make + " " + model
       + ", " + to_string(mileage);
}

Check: Why to_string()?

mileage is a double, but getInfo() returns a string. Why call to_string()?

You cannot add a double directly to a string with +; to_string() converts it first.

Step 5: Use the Class

  • Build one Car object
  • Simulate a test drive
  • Print the summary
Car c1("Honda", "Civic", 2024);
c1.drive(12.5);
std::cout << c1.getInfo();

Sample Run: Dealership Tool

Honda Civic, 12.500000 make + model + mileage, one line

Extension: Add price

Add a private double price, plus a getter getPrice().

private:
  double price;
public:
  double getPrice() {
    return price;
  }

Deliverable

  • Write the full Car class
  • Build one object, drive it
  • Print getInfo(), show output
✏️Write the class🧪Build and drive it✅Show the output

Questions?

Practice Lab Part 2

The Scenario: Garage Manager

  • A small garage: 5 cars
  • Each one its own Car object
  • Report on the whole garage
🚗🚗🚗5 Car objects🔄Loop over the garage📊Report on all of them

The Plan: Array of Objects

Car fleet[5] [0][1][2][3][4]an array of Car objects

Step 1: Declare the Array

  • fleet: 5 Car objects
  • Each already default-built
  • Same array syntax from Mod. 5
Car fleet[5];

Step 2: Fill the Array

  • Assign each slot a real car
  • Uses the constructor directly
  • Five distinct objects now
fleet[0] = Car("Honda", "Civic", 2024);
fleet[1] = Car("Ford", "F-150", 2021);

Step 3: Print the Garage

  • Loop every index, 0 to 4
  • fleet[i]: that one Car object
  • Call getInfo() on each
for (int i = 0; i < 5; i++) {
  std::cout << fleet[i].getInfo();
}

Check: fleet[2].drive()

fleet[2].drive(30); : which car in the garage just changed?

Only the Car object at index 2. The other four are untouched.

Step 4: Find the Newest

  • Track the lowest mileage
  • Compare one object at a time
  • Reuses getMileage() from Mod.
int best = 0;
for (int i = 1; i < 5; i++) {
  if (fleet[i].getMileage() <
      fleet[best].getMileage())
    best = i;
}

Extension: Needs Service

Count how many cars in fleet have mileage over 5000.

int count = 0;
for (int i = 0; i < 5; i++)
  if (fleet[i].getMileage() > 5000)
    count++;

Deliverable

  • Fill the 5-car garage
  • Print every car's info
  • Report the newest car
🚗🚗🚗Build the garage📋Print every car✅Report the newest

Questions?

Practice Quiz

Practice Quiz: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question.

Class
Object
Member
Constructor
Runs automatically when an object is created
Bundling data and behavior inside one class
Section accessible only inside the class itself
Section accessible from outside the class
Pointer to the current object inside a member function
Blueprint for creating objects
A real instance created from a class
A variable or function that belongs to a class
Encapsulation
Private
Public
this

Questions?

Looking Ahead: Module 8

Where We Are: Module 7

  • Module 7 done: classes
  • Next: Classes and Inheritance

Why This Matters

  • Subclasses began with Simula
  • Java chose single only
  • C++ still allows both kinds
1967Simula 67 (Dahl &Nygaard) adds subclasses to OOP1972Smalltalk formalizes singleinheritance as core to its object model1985C++ adds inheritance syntax: public/private/protected, virtual functions1995Java deliberately allows onlysingle inheritance, avoiding C++'s complexityTodayC++ still supports bothsingle and multiple inheritance
Vehicle Car Truck Car IS-A Vehicle. Truck IS-A Vehicle.

What Is Inheritance?

What Is Inheritance?

  • A new class reuses an old one
  • Car IS-A Vehicle
  • No copy-pasting code twice
class VehicleCarTruckCar and Truck both get Vehicle's fieldsand functions, automatically, with no copying.

Why Not Just Copy-Paste?

  • Two classes, same fields twice
  • Fix one, forget the other
  • Inheritance: one true source
📋📋Copy-pasted fields💥A fix misses one copy✅Inherit instead: one source

Check: IS-A or HAS-A?

A Car has an Engine. A Car is a Vehicle. Which relationship is inheritance?

IS-A. Car is a Vehicle uses inheritance. Car has an Engine is composition, a member variable instead.

Base and Derived Classes

Step 1: The Base Class

  • Vehicle: shared fields
  • make, model, year
  • Every vehicle has these
class Vehicle {
public:
  string make, model;
  int year;
};

Step 2: A Derived Class

  • : public Vehicle means IS-A
  • Car gets make/model/year free
  • Plus its own new field
class Car : public Vehicle {
public:
  int doors;
};

Step 3: Use the Derived Class

  • c has make, model, year, doors
  • Inherited fields work directly
  • No extra code needed
Car c;
c.make = "Honda";
c.doors = 4;

Check: What Does Truck Get?

class Truck : public Vehicle. Does Truck have a make field?

Yes. Truck inherits every public member of Vehicle automatically, including make.

Mechanic : public Employee

  • Mechanic: fixes cars
  • Mechanic IS-A Employee
  • Adds: certLevel
class Employee {
public:
  string name;
  int yearsHere;
};
class Mechanic : public Employee {
public:
  int certLevel;
};

Salesperson : public Employee

  • Salesperson: sells cars
  • Salesperson IS-A Employee
  • Adds: salesCount
class Employee {
public:
  string name;
  int yearsHere;
};
class Salesperson : public Employee {
public:
  int salesCount;
};

main(): Mechanic and Salesperson

  • One object of each class
  • Both inherit from Employee
  • Own field set separately
Mechanic m;
m.name = "Ana";
m.certLevel = 3;
Salesperson s;
s.name = "Raj";
s.salesCount = 12;
cout << m.name << " " << m.certLevel;
cout << s.name << " " << s.salesCount;

Customer : public Person

  • Customer: buys cars
  • Customer IS-A Person
  • Adds: loyaltyPoints
class Person {
public:
  string name;
  string phone;
};
class Customer : public Person {
public:
  int loyaltyPoints;
};

main(): Customer

  • One Customer object
  • Inherits from Person
  • Own field set separately
Customer c;
c.name = "Ana";
c.loyaltyPoints = 250;
cout << c.name << " " << c.loyaltyPoints;

Invoice : public Document

  • Invoice: bills work
  • Invoice IS-A Document
  • Adds: amountDue
class Document {
public:
  string date;
  string owner;
};
class Invoice : public Document {
public:
  double amountDue;
};

Warranty : public Document

  • Warranty: covers a repair
  • Warranty IS-A Document
  • Adds: monthsLeft
class Document {
public:
  string date;
  string owner;
};
class Warranty : public Document {
public:
  int monthsLeft;
};

main(): Invoice and Warranty

  • One object of each class
  • Both inherit from Document
  • Own field set separately
Invoice i;
i.date = "Oct 13";
i.amountDue = 450.00;
Warranty w;
w.date = "Oct 13";
w.monthsLeft = 18;
cout << i.date << " " << i.amountDue;
cout << w.date << " " << w.monthsLeft;

ServiceAppt : public Appointment

  • ServiceAppt: books a repair
  • ServiceAppt IS-A Appointment
  • Adds: serviceType
class Appointment {
public:
  string date;
  string customer;
};
class ServiceAppt : public Appointment {
public:
  string serviceType;
};

TestDrive : public Appointment

  • TestDrive: books a drive
  • TestDrive IS-A Appointment
  • Adds: minutes
class Appointment {
public:
  string date;
  string customer;
};
class TestDrive : public Appointment {
public:
  int minutes;
};

main(): ServiceAppt and TestDrive

  • One object of each class
  • Both inherit from Appointment
  • Own field set separately
ServiceAppt s;
s.date = "Oct 13";
s.serviceType = "Oil";
TestDrive t;
t.date = "Oct 13";
t.minutes = 30;
cout << s.date << " " << s.serviceType;
cout << t.date << " " << t.minutes;

CustomerAccount : public Account

  • CustomerAccount: a buyer
  • CustomerAccount IS-A Account
  • Adds: balance
class Account {
public:
  string owner;
  string id;
};
class CustomerAccount : public Account {
public:
  double balance;
};

DealerAccount : public Account

  • DealerAccount: tracks a seller
  • DealerAccount IS-A Account
  • Adds: commission
class Account {
public:
  string owner;
  string id;
};
class DealerAccount : public Account {
public:
  double commission;
};

main(): CustomerAccount and DealerAccount

  • One object of each class
  • Both inherit from Account
  • Own field set separately
CustomerAccount c;
c.owner = "Ana";
c.balance = 1200.50;
DealerAccount d;
d.owner = "Raj";
d.commission = 300.00;
cout << c.owner << " " << c.balance;
cout << d.owner << " " << d.commission;

Tire : public Part

  • Tire: meets the road
  • Tire IS-A Part
  • Adds: treadDepth
class Part {
public:
  string name;
  double cost;
};
class Tire : public Part {
public:
  double treadDepth;
};

Battery : public Part

  • Battery: powers the car
  • Battery IS-A Part
  • Adds: voltage
class Part {
public:
  string name;
  double cost;
};
class Battery : public Part {
public:
  double voltage;
};

main(): Tire and Battery

  • One object of each class
  • Both inherit from Part
  • Own field set separately
Tire t;
t.name = "Ana";
t.treadDepth = 8.50;
Battery b;
b.name = "Raj";
b.voltage = 12.60;
cout << t.name << " " << t.treadDepth;
cout << b.name << " " << b.voltage;

Garage : public Facility

  • Garage: repairs cars
  • Garage IS-A Facility
  • Adds: bayCount
class Facility {
public:
  string address;
  int sqft;
};
class Garage : public Facility {
public:
  int bayCount;
};

Dealership : public Facility

  • Dealership: sells cars
  • Dealership IS-A Facility
  • Adds: inventory
class Facility {
public:
  string address;
  int sqft;
};
class Dealership : public Facility {
public:
  int inventory;
};

main(): Garage and Dealership

  • One object of each class
  • Both inherit from Facility
  • Own field set separately
Garage g;
g.address = "1 Main St";
g.bayCount = 6;
Dealership d;
d.address = "1 Main St";
d.inventory = 120;
cout << g.address << " " << g.bayCount;
cout << d.address << " " << d.inventory;

Sale : public Transaction

  • Sale: a car sold
  • Sale IS-A Transaction
  • Adds: salePrice
class Transaction {
public:
  string date;
  double total;
};
class Sale : public Transaction {
public:
  double salePrice;
};

TradeIn : public Transaction

  • TradeIn: a car swapped
  • TradeIn IS-A Transaction
  • Adds: appraised
class Transaction {
public:
  string date;
  double total;
};
class TradeIn : public Transaction {
public:
  double appraised;
};

main(): Sale and TradeIn

  • One object of each class
  • Both inherit from Transaction
  • Own field set separately
Sale s;
s.date = "Oct 13";
s.salePrice = 24500.00;
TradeIn t;
t.date = "Oct 13";
t.appraised = 11000.00;
cout << s.date << " " << s.salePrice;
cout << t.date << " " << t.appraised;

Insurance : public Policy

  • Insurance: covers a loss
  • Insurance IS-A Policy
  • Adds: premium
class Policy {
public:
  string provider;
  string id;
};
class Insurance : public Policy {
public:
  double premium;
};

ReturnPolicy : public Policy

  • ReturnPolicy: covers a return
  • ReturnPolicy IS-A Policy
  • Adds: daysAllowed
class Policy {
public:
  string provider;
  string id;
};
class ReturnPolicy : public Policy {
public:
  int daysAllowed;
};

main(): Insurance and ReturnPolicy

  • One object of each class
  • Both inherit from Policy
  • Own field set separately
Insurance i;
i.provider = "AutoSure";
i.premium = 95.00;
ReturnPolicy r;
r.provider = "AutoSure";
r.daysAllowed = 30;
cout << i.provider << " " << i.premium;
cout << r.provider << " " << r.daysAllowed;

Inspection : public Record

  • Inspection: checks safety
  • Inspection IS-A Record
  • Adds: passed
class Record {
public:
  string date;
  string vin;
};
class Inspection : public Record {
public:
  bool passed;
};

Registration : public Record

  • Registration: makes it legal
  • Registration IS-A Record
  • Adds: expires
class Record {
public:
  string date;
  string vin;
};
class Registration : public Record {
public:
  string expires;
};

main(): Inspection and Registration

  • One object of each class
  • Both inherit from Record
  • Own field set separately
Inspection i;
i.date = "Oct 13";
i.passed = true;
Registration r;
r.date = "Oct 13";
r.expires = "2027";
cout << i.date << " " << i.passed;
cout << r.date << " " << r.expires;

GPS : public Device

  • GPS: finds the way
  • GPS IS-A Device
  • Adds: signal
class Device {
public:
  string model;
  bool isOn;
};
class GPS : public Device {
public:
  double signal;
};

KeyFob : public Device

  • KeyFob: locks the car
  • KeyFob IS-A Device
  • Adds: battery
class Device {
public:
  string model;
  bool isOn;
};
class KeyFob : public Device {
public:
  int battery;
};

main(): GPS and KeyFob

  • One object of each class
  • Both inherit from Device
  • Own field set separately
GPS g;
g.model = "Civic";
g.signal = 4.50;
KeyFob k;
k.model = "F-150";
k.battery = 80;
cout << g.model << " " << g.signal;
cout << k.model << " " << k.battery;

Receptionist : public Staff

  • Receptionist: greets customers
  • Receptionist IS-A Staff
  • Adds: deskNumber
class Staff {
public:
  string name;
  string shift;
};
class Receptionist : public Staff {
public:
  int deskNumber;
};

Manager : public Staff

  • Manager: runs the floor
  • Manager IS-A Staff
  • Adds: teamSize
class Staff {
public:
  string name;
  string shift;
};
class Manager : public Staff {
public:
  int teamSize;
};

main(): Receptionist and Manager

  • One object of each class
  • Both inherit from Staff
  • Own field set separately
Receptionist r;
r.name = "Ana";
r.deskNumber = 2;
Manager m;
m.name = "Raj";
m.teamSize = 8;
cout << r.name << " " << r.deskNumber;
cout << m.name << " " << m.teamSize;

UsedCarListing : public Listing

  • UsedCarListing: a used car ad
  • UsedCarListing IS-A Listing
  • Adds: mileage
class Listing {
public:
  string model;
  double price;
};
class UsedCarListing : public Listing {
public:
  double mileage;
};

NewCarListing : public Listing

  • NewCarListing: a new car ad
  • NewCarListing IS-A Listing
  • Adds: color
class Listing {
public:
  string model;
  double price;
};
class NewCarListing : public Listing {
public:
  string color;
};

main(): UsedCarListing and NewCarListing

  • One object of each class
  • Both inherit from Listing
  • Own field set separately
UsedCarListing u;
u.model = "Civic";
u.mileage = 2.50;
NewCarListing n;
n.model = "F-150";
n.color = "Red";
cout << u.model << " " << u.mileage;
cout << n.model << " " << n.color;

ServiceReview : public Review

  • ServiceReview: rates a repair
  • ServiceReview IS-A Review
  • Adds: mechanic
class Review {
public:
  string author;
  int rating;
};
class ServiceReview : public Review {
public:
  string mechanic;
};

SalesReview : public Review

  • SalesReview: rates a sale
  • SalesReview IS-A Review
  • Adds: salesperson
class Review {
public:
  string author;
  int rating;
};
class SalesReview : public Review {
public:
  string salesperson;
};

main(): ServiceReview and SalesReview

  • One object of each class
  • Both inherit from Review
  • Own field set separately
ServiceReview se;
se.author = "Ana";
se.mechanic = "Ana";
SalesReview sa;
sa.author = "Raj";
sa.salesperson = "Raj";
cout << se.author << " " << se.mechanic;
cout << sa.author << " " << sa.salesperson;

RentalCar : public Vehicle

  • RentalCar: a rental unit
  • RentalCar IS-A Vehicle
  • Adds: dailyRate
class Vehicle {
public:
  string make;
  int year;
};
class RentalCar : public Vehicle {
public:
  double dailyRate;
};

DemoCar : public Vehicle

  • DemoCar: a showroom demo
  • DemoCar IS-A Vehicle
  • Adds: testDrives
class Vehicle {
public:
  string make;
  int year;
};
class DemoCar : public Vehicle {
public:
  int testDrives;
};

main(): RentalCar and DemoCar

  • One object of each class
  • Both inherit from Vehicle
  • Own field set separately
RentalCar r;
r.make = "Honda";
r.dailyRate = 59.99;
DemoCar d;
d.make = "Ford";
d.testDrives = 7;
cout << r.make << " " << r.dailyRate;
cout << d.make << " " << d.testDrives;

MechanicShift : public Shift

  • MechanicShift: a repair shift
  • MechanicShift IS-A Shift
  • Adds: baysAssigned
class Shift {
public:
  string day;
  int hours;
};
class MechanicShift : public Shift {
public:
  int baysAssigned;
};

FrontDeskShift : public Shift

  • FrontDeskShift: a desk shift
  • FrontDeskShift IS-A Shift
  • Adds: callsHandled
class Shift {
public:
  string day;
  int hours;
};
class FrontDeskShift : public Shift {
public:
  int callsHandled;
};

main(): MechanicShift and FrontDeskShift

  • One object of each class
  • Both inherit from Shift
  • Own field set separately
MechanicShift m;
m.day = "Mon";
m.baysAssigned = 2;
FrontDeskShift f;
f.day = "Tue";
f.callsHandled = 40;
cout << m.day << " " << m.baysAssigned;
cout << f.day << " " << f.callsHandled;

LoyaltyDiscount : public Discount

  • LoyaltyDiscount: repeat perk
  • LoyaltyDiscount IS-A Discount
  • Adds: pointsNeeded
class Discount {
public:
  string code;
  double percent;
};
class LoyaltyDiscount : public Discount {
public:
  int pointsNeeded;
};

SeasonalDiscount : public Discount

  • SeasonalDiscount: a timed deal
  • SeasonalDiscount IS-A Discount
  • Adds: season
class Discount {
public:
  string code;
  double percent;
};
class SeasonalDiscount : public Discount {
public:
  string season;
};

main(): LoyaltyDiscount and SeasonalDiscount

  • One object of each class
  • Both inherit from Discount
  • Own field set separately
LoyaltyDiscount l;
l.code = "FALL10";
l.pointsNeeded = 500;
SeasonalDiscount s;
s.code = "FALL10";
s.season = "Winter";
cout << l.code << " " << l.pointsNeeded;
cout << s.code << " " << s.season;

MaintenanceAlert : public Alert

  • MaintenanceAlert: a reminder
  • MaintenanceAlert IS-A Alert
  • Adds: mileageDue
class Alert {
public:
  string message;
  string level;
};
class MaintenanceAlert : public Alert {
public:
  int mileageDue;
};

RecallAlert : public Alert

  • RecallAlert: a safety recall
  • RecallAlert IS-A Alert
  • Adds: recallId
class Alert {
public:
  string message;
  string level;
};
class RecallAlert : public Alert {
public:
  string recallId;
};

main(): MaintenanceAlert and RecallAlert

  • One object of each class
  • Both inherit from Alert
  • Own field set separately
MaintenanceAlert m;
m.message = "Oil due";
m.mileageDue = 60000;
RecallAlert r;
r.message = "Recall";
r.recallId = "R-22";
cout << m.message << " " << m.mileageDue;
cout << r.message << " " << r.recallId;

LeaseContract : public Contract

  • LeaseContract: leases a car
  • LeaseContract IS-A Contract
  • Adds: monthsTerm
class Contract {
public:
  string date;
  string buyer;
};
class LeaseContract : public Contract {
public:
  int monthsTerm;
};

FinanceContract : public Contract

  • FinanceContract: a loan
  • FinanceContract IS-A Contract
  • Adds: apr
class Contract {
public:
  string date;
  string buyer;
};
class FinanceContract : public Contract {
public:
  double apr;
};

main(): LeaseContract and FinanceContract

  • One object of each class
  • Both inherit from Contract
  • Own field set separately
LeaseContract l;
l.date = "Oct 13";
l.monthsTerm = 36;
FinanceContract f;
f.date = "Oct 13";
f.apr = 4.90;
cout << l.date << " " << l.monthsTerm;
cout << f.date << " " << f.apr;

ParkingSpot : public Space

  • ParkingSpot: holds one car
  • ParkingSpot IS-A Space
  • Adds: occupied
class Space {
public:
  int number;
  bool covered;
};
class ParkingSpot : public Space {
public:
  bool occupied;
};

LoadingDock : public Space

  • LoadingDock: loads a truck
  • LoadingDock IS-A Space
  • Adds: maxWeight
class Space {
public:
  int number;
  bool covered;
};
class LoadingDock : public Space {
public:
  double maxWeight;
};

main(): ParkingSpot and LoadingDock

  • One object of each class
  • Both inherit from Space
  • Own field set separately
ParkingSpot p;
p.number = 12;
p.occupied = false;
LoadingDock l;
l.number = 3;
l.maxWeight = 5000.00;
cout << p.number << " " << p.occupied;
cout << l.number << " " << l.maxWeight;

RepairTicket : public Ticket

  • RepairTicket: a repair job
  • RepairTicket IS-A Ticket
  • Adds: issue
class Ticket {
public:
  string date;
  string status;
};
class RepairTicket : public Ticket {
public:
  string issue;
};

WarrantyTicket : public Ticket

  • WarrantyTicket: a claim
  • WarrantyTicket IS-A Ticket
  • Adds: claimType
class Ticket {
public:
  string date;
  string status;
};
class WarrantyTicket : public Ticket {
public:
  string claimType;
};

main(): RepairTicket and WarrantyTicket

  • One object of each class
  • Both inherit from Ticket
  • Own field set separately
RepairTicket r;
r.date = "Oct 13";
r.issue = "Brakes";
WarrantyTicket w;
w.date = "Oct 13";
w.claimType = "Engine";
cout << r.date << " " << r.issue;
cout << w.date << " " << w.claimType;

SalesReport : public Report

  • SalesReport: tracks sales
  • SalesReport IS-A Report
  • Adds: unitsSold
class Report {
public:
  string title;
  string date;
};
class SalesReport : public Report {
public:
  int unitsSold;
};

ServiceReport : public Report

  • ServiceReport: tracks repairs
  • ServiceReport IS-A Report
  • Adds: jobsDone
class Report {
public:
  string title;
  string date;
};
class ServiceReport : public Report {
public:
  int jobsDone;
};

main(): SalesReport and ServiceReport

  • One object of each class
  • Both inherit from Report
  • Own field set separately
SalesReport sa;
sa.title = "Q3 Sales";
sa.unitsSold = 45;
ServiceReport se;
se.title = "Q3 Jobs";
se.jobsDone = 88;
cout << sa.title << " " << sa.unitsSold;
cout << se.title << " " << se.jobsDone;

MechanicBadge : public Badge

  • MechanicBadge: a repair cert
  • MechanicBadge IS-A Badge
  • Adds: specialty
class Badge {
public:
  string holder;
  string level;
};
class MechanicBadge : public Badge {
public:
  string specialty;
};

SafetyBadge : public Badge

  • SafetyBadge: a safety cert
  • SafetyBadge IS-A Badge
  • Adds: course
class Badge {
public:
  string holder;
  string level;
};
class SafetyBadge : public Badge {
public:
  string course;
};

main(): MechanicBadge and SafetyBadge

  • One object of each class
  • Both inherit from Badge
  • Own field set separately
MechanicBadge m;
m.holder = "Ana";
m.specialty = "Brakes";
SafetyBadge s;
s.holder = "Raj";
s.course = "CPR";
cout << m.holder << " " << m.specialty;
cout << s.holder << " " << s.course;

TrainingSession : public Session

  • TrainingSession: for staff
  • TrainingSession IS-A Session
  • Adds: topic
class Session {
public:
  string start;
  string end;
};
class TrainingSession : public Session {
public:
  string topic;
};

DemoSession : public Session

  • DemoSession: a product demo
  • DemoSession IS-A Session
  • Adds: model
class Session {
public:
  string start;
  string end;
};
class DemoSession : public Session {
public:
  string model;
};

main(): TrainingSession and DemoSession

  • One object of each class
  • Both inherit from Session
  • Own field set separately
TrainingSession t;
t.start = "9:00";
t.topic = "EVs";
DemoSession d;
d.start = "9:00";
d.model = "F-150";
cout << t.start << " " << t.topic;
cout << d.start << " " << d.model;

MaintenanceLog : public Log

  • MaintenanceLog: tracks service
  • MaintenanceLog IS-A Log
  • Adds: mileage
class Log {
public:
  string date;
  string entry;
};
class MaintenanceLog : public Log {
public:
  int mileage;
};

IncidentLog : public Log

  • IncidentLog: tracks a problem
  • IncidentLog IS-A Log
  • Adds: severity
class Log {
public:
  string date;
  string entry;
};
class IncidentLog : public Log {
public:
  string severity;
};

main(): MaintenanceLog and IncidentLog

  • One object of each class
  • Both inherit from Log
  • Own field set separately
MaintenanceLog m;
m.date = "Oct 13";
m.mileage = 42000;
IncidentLog i;
i.date = "Oct 13";
i.severity = "Low";
cout << m.date << " " << m.mileage;
cout << i.date << " " << i.severity;

PartsBudget : public Budget

  • PartsBudget: tracks parts cost
  • PartsBudget IS-A Budget
  • Adds: spent
class Budget {
public:
  string quarter;
  double total;
};
class PartsBudget : public Budget {
public:
  double spent;
};

MarketingBudget : public Budget

  • MarketingBudget: ad spend
  • MarketingBudget IS-A Budget
  • Adds: spent
class Budget {
public:
  string quarter;
  double total;
};
class MarketingBudget : public Budget {
public:
  double spent;
};

main(): PartsBudget and MarketingBudget

  • One object of each class
  • Both inherit from Budget
  • Own field set separately
PartsBudget p;
p.quarter = "Q3";
p.spent = 8200.00;
MarketingBudget m;
m.quarter = "Q3";
m.spent = 3100.00;
cout << p.quarter << " " << p.spent;
cout << m.quarter << " " << m.spent;

ServiceZone : public Zone

  • ServiceZone: the repair area
  • ServiceZone IS-A Zone
  • Adds: baysOpen
class Zone {
public:
  string name;
  int capacity;
};
class ServiceZone : public Zone {
public:
  int baysOpen;
};

ShowroomZone : public Zone

  • ShowroomZone: the sales floor
  • ShowroomZone IS-A Zone
  • Adds: carsOnFloor
class Zone {
public:
  string name;
  int capacity;
};
class ShowroomZone : public Zone {
public:
  int carsOnFloor;
};

main(): ServiceZone and ShowroomZone

  • One object of each class
  • Both inherit from Zone
  • Own field set separately
ServiceZone se;
se.name = "Ana";
se.baysOpen = 4;
ShowroomZone sh;
sh.name = "Raj";
sh.carsOnFloor = 9;
cout << se.name << " " << se.baysOpen;
cout << sh.name << " " << sh.carsOnFloor;

PartsShipment : public Shipment

  • PartsShipment: parts arriving
  • PartsShipment IS-A Shipment
  • Adds: itemCount
class Shipment {
public:
  string date;
  string carrier;
};
class PartsShipment : public Shipment {
public:
  int itemCount;
};

CarShipment : public Shipment

  • CarShipment: cars arriving
  • CarShipment IS-A Shipment
  • Adds: vehicleCount
class Shipment {
public:
  string date;
  string carrier;
};
class CarShipment : public Shipment {
public:
  int vehicleCount;
};

main(): PartsShipment and CarShipment

  • One object of each class
  • Both inherit from Shipment
  • Own field set separately
PartsShipment p;
p.date = "Oct 13";
p.itemCount = 250;
CarShipment c;
c.date = "Oct 13";
c.vehicleCount = 8;
cout << p.date << " " << p.itemCount;
cout << c.date << " " << c.vehicleCount;

Protected Members

private vs protected vs public

  • private: this class only
  • protected: class + children
  • public: anyone
private: locked to this classprotected: + derived classespublic: anyone at all

Step 4: Use protected

  • mileage: visible to Car, Truck
  • Still hidden from outside code
  • The middle ground of the three
class Vehicle {
protected:
  double mileage;
public:
  string make, model;
};

Check: Can Car Reach It?

mileage is protected in Vehicle. Can a Car member function read mileage directly?

Yes. protected is visible inside the class itself and any class that inherits from it.

Overriding Functions

Same Name, New Behavior

  • Vehicle has a describe()
  • Car can define its own version
  • Car's version runs for a Car
🚗Vehicle::describe()🚘Car overrides it✅Car gets its own wording

Step 5: Base Version

  • Generic, works for any vehicle
  • Returns a plain description
  • Car can replace this
string describe() {
  return "A vehicle";
}

Step 6: Override in Car

  • Same name, same return type
  • Defined again, inside Car
  • Runs for Car objects now
string describe() {
  return "A car";
}

Check: Which Version Runs?

Car c; c.describe();. Does this call Vehicle's describe() or Car's?

Car's. When Car defines its own describe(), it replaces (overrides) Vehicle's for Car objects.

Constructors in Inheritance

Base Runs First

  • Vehicle's own ctor runs first
  • Then Car's own constructor
  • Base is always set up first
🚗Vehicle() runs🚘Car() runs next✅Object fully built

Step 7: Pass to the Base

  • Vehicle(mk, md) : runs first
  • Car adds doors on top
  • Colon syntax calls the base
Car(string mk, string md, int d)
  : Vehicle(mk, md) {
  doors = d;
}

Check: Order of Execution

Car c("Honda", "Civic", 4);. Which constructor body runs first: Vehicle's or Car's?

Vehicle's. The base class is always fully constructed before the derived class body runs.

More Derived Classes

Step 8: A Second Derived Class

  • Truck also IS-A Vehicle
  • Gets make, model, mileage
  • Adds its own towCapacity
class Truck : public Vehicle {
public:
  double towCapacity;
};

One Base, Many Children

  • Car and Truck both reuse it
  • Each adds its own extra field
  • Fix Vehicle once, both benefit
VehicleCarTruck

Check: Fix in One Place

A bug in Vehicle's mileage logic is fixed inside Vehicle itself. Does Truck need its own fix too?

No. Truck inherits Vehicle's code, not a copy of it, so the one fix in Vehicle covers Truck automatically.

Practice Lab

Requirements: Dealership Fleet

  • Vehicle: make, model, year
  • Car adds doors
  • Truck adds towCapacity
🚗Vehicle: shared fields🚔Car and Truck: extras✅Both work through Vehicle

Step 1: Vehicle Base

  • protected mileage
  • public make, model, year
  • A describe() to override later
class Vehicle {
protected:
  double mileage;
public:
  string make, model;
  int year;
};

Step 2: Car and Truck

  • Both inherit from Vehicle
  • Car adds doors
  • Truck adds towCapacity
class Car : public Vehicle {
public: int doors;
};
class Truck : public Vehicle {
public: double towCapacity;
};

Step 3: Build Both Objects

  • Each gets make/model/year free
  • Plus its own extra field
  • Two distinct types, one base
Car c;
c.make = "Honda"; c.doors = 4;
Truck t;
t.make = "Ford"; t.towCapacity = 5000;

Check: Shared or Separate?

c.make and t.make: do they share one variable, or does each object have its own?

Each object has its own separate copy of make, exactly like any other member variable.

Deliverable

  • Write Vehicle, Car, Truck
  • Build one of each
  • Print both, show they differ
✏️Write all three classes🚗🚛Build a Car and a Truck✅Show both work correctly

Practice Lab Part 2

Scenario: Override describe()

  • Vehicle::describe() is generic
  • Car and Truck each override it
  • Same call, different wording
🚗Vehicle: "A vehicle"🚘🚛Car, Truck override it✅Each prints its own text

Step 1: Override in Car

  • Car's own describe()
  • Mentions doors specifically
  • Replaces Vehicle's version
string describe() {
  return "A car with " +
    to_string(doors) + " doors";
}

Step 2: Override in Truck

  • Truck's own describe()
  • Mentions towCapacity instead
  • A third, different wording
string describe() {
  return "A truck that tows " +
    to_string(towCapacity);
}

Extension: Motorcycle

Add a third class, Motorcycle, with its own hasSidecar and its own describe().

class Motorcycle : public Vehicle {
public: bool hasSidecar;
};

Check: Three Calls, Three Answers

c.describe(); t.describe(); m.describe();. Do all three print the same text?

No. Each class overrides describe() with its own version, so each object prints its own wording.

Deliverable

  • Override describe() x3
  • Build one of each class
  • Show all 3 outputs
✏️Override describe() x3🚗🚛🏍Build one of each✅Three different outputs

Word Origin: "Inheritance"

  • Latin "heres": an heir
  • A legal term: passing property
  • Borrowed by Simula, 1967
A derived class inherits its base class's members, the same way a child inherits from a parent

Practice Quiz

Practice Quiz: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question.

Inheritance
Base Class
Derived Class
Protected
Accessible to the class and its derived classes
Redefining a base class function in a derived class
Describes inheritance, e.g. a Car is-a Vehicle
Inheriting from more than one base class
public, protected, or private on a base class
A class reuses another class's members
The class being inherited from
The class that inherits from another
Override
is-a
Multiple Inheritance
Access Specifier

Questions?

Looking Ahead: Module 9

Module 9

Data Streams

inventory.txt ifstream your program A stream connects a file to your code.

Why This Matters

  • One interface, many sources
  • Files outlive the program
  • Same >> you already know
1964: Multics stream-based I/O1973: Unix pipes (Doug McIlroy,Bell Labs): chain streams together1985: C++ iostream, cin/coutToday: files and console sharethe same stream interface

What Are Streams?

What Are Streams?

  • Flows in order, like water
  • Source: keyboard, file, text
  • Same << and >> for all of them
cinifstreamstringstream>> and <<The same operators work on every kind of stream.

Check: What Changes?

cin >> x; reads from the keyboard. file >> x; reads from a file. What actually changed?

Only the stream object, cin vs file. The >> operator and the rest of the code stay identical.

cin and cout, Revisited

Already Streams All Along

  • cout: the console output
  • cin: the console input stream
  • From iostream, Module 2
⌨️cin: keyboard in🖥️cout: screen out✅Both real streams

Step 1: Reading Multiple Values

  • Two >> in one line
  • Reads make, then mileage
  • Whitespace separates each read
#include <iostream>
string make;
double mileage;
std::cin >> make >> mileage;

Check: What If Input Has a Space?

cin >> make expects one word. Typing "Honda Civic" as the make, what happens?

cin only reads up to the space: make becomes "Honda", and "Civic" is left waiting for the next read.

Writing to a File

ofstream: Output to a File

  • o for output, like ostream
  • Opens, or creates, the file
  • Same << syntax as cout
ofstream outinventory.txt

Step 2: Open and Write

  • Constructor takes the filename
  • << writes just like cout
  • File closes automatically
#include <fstream>
std::ofstream out("inventory.txt");
out << "Honda" << " " << 12000;

Check: What If the File Exists?

inventory.txt already has old data. Opening it with ofstream the normal way, what happens to that data?

It is overwritten by default. ofstream truncates an existing file unless told to append instead.

trunc vs. app: Two Open Modes

  • Default mode erases first
  • ios::app keeps old data
  • Pick based on what you need
old: Honda 23000trunc (default)wiped, then writtenold: Honda 23000ios::appold stays, new is added

Word Origin: "Buffer"

  • Early 1800s: cushions a shock
  • From buff: a dull, soft blow
  • A memory area that softens I/O
Buffercushions a speed mismatch

Source: etymonline.com

Reading from a File

ifstream: Input from a File

  • i for input, like istream
  • Opens an existing file
  • Same >> syntax as cin
inventory.txtifstream in

Step 1: Open and Check

  • Constructor opens the file
  • if(!in) catches a bad open
  • Guards against a missing file
#include <fstream>
#include <iostream>
std::ifstream in("inventory.txt");
if (!in) {
  std::cout << "Missing file";
}

Step 2: Read Values Back

  • Same >> pattern as cin
  • Reads one make, one mileage
  • Order must match the write
string make;
double mileage;
in >> make >> mileage;

Step 3: Loop Until Done

  • while(in >> x) reads each row
  • Loop ends at end of file
  • A clean way to read every row
while (in >> make >> mileage) {
  std::cout << make << "\\n";
}

Reading a File, Step by Step

  • Each pass tries one read
  • Success keeps the loop going
  • Failure (EOF) ends it cleanly
Try to read a valueDid it succeed?yes: process it,loop back upno: stopthe loop

Check: Why while(in >> make)?

The loop condition reads a value AND checks it worked. Why combine both in one expression?

The read itself returns the stream, which is false once input runs out: one expression reads and tests.

Formatting Output

Manipulators Shape the Output

  • fixed: no scientific notation
  • setprecision(2): two decimals
  • Both live in <iomanip>
🔢raw double: 23500⚙️fixed + setprecision(2)💵printed: 23500.00

Step 1: Fixed Decimal Places

  • #include <iomanip>
  • fixed locks decimal format
  • setprecision picks the count
#include <iomanip>
std::cout << std::fixed
  << std::setprecision(2);
std::cout << price;

Step 2: Column Width

  • setw(10) pads the next field
  • Right-aligns by default
  • Applies to one field only
#include <iomanip>
std::cout << std::setw(10)
  << price;

setw Affects One Field Only

  • setw(10) targets price here
  • Just the one field after it
  • Repeat it before each field
setw(10)pricepadded to 10 widenextplain cout, no setwsetw only affects the field right after it.

Word Origin: "Manipulator"

  • Latin manus: hand
  • manipulus: a handful
  • To handle, operate skillfully
Manipulatorfixed, setw: handle formatting

Source: cppreference.com

Check: setw Resets Each Time?

setw(10) is used once, then a plain cout << next_value; follows. Is next_value also padded to 10?

No: setw only affects the very next inserted value, so it must be repeated before each field that needs it.

Parsing with stringstream

stringstream: A String You Can Read

  • Wraps a string like a stream
  • Same >> pulls out pieces
  • From <sstream>
"Honda 23500"stringstream ssss >> make >> mileage;

Step 1: Build and Read

  • #include <sstream>
  • Constructor takes the string
  • Pull fields out with >>
#include <sstream>
std::stringstream ss(line);
string make;
double mileage;
ss >> make >> mileage;

Check: Why Parse This Way?

A line "Honda 23500" needs splitting into a make and a mileage. Why use stringstream instead of substr?

stringstream reuses the same reliable >> parsing already trusted for cin and files, no manual index math.

Word Origin: "Parse"

  • Latin pars orationis: part
  • Grammar: naming word parts
  • Now: breaking text into pieces
Parsesplits raw text into fields

Source: etymonline.com

Practice Lab

Scenario: Save the Lot

  • Dealership tracks cars
  • Save each car to a real file
  • Read it back to check it
📄💾Program state becomes a real file on disk.

Step 1: Declare the Fields

  • make, model, mileage, price
  • Four values describe one car
string make = "Honda", model = "Civic";
int mileage = 23000;
double price = 18500.0;

Step 2: Open the File

  • ofstream opens for writing
  • Check it opened correctly
#include <fstream>
std::ofstream out("lot.txt");
if (!out) {
  std::cout << "Open failed";
}

Step 3: Write the Car

  • Space-separate each field
  • One row per car
out << make << " " << model << " "
    << mileage << " " << price << "\\n";

Step 4: Close and Reopen

  • out.close() flushes the file
  • ifstream opens it for reading
#include <fstream>
out.close();
std::ifstream in("lot.txt");

Step 5: Read It Back

  • Same four variables
  • Order matches write order
string m2, mo2;
int mi2;
double p2;
in >> m2 >> mo2 >> mi2 >> p2;

Step 6: Print to Confirm

  • Prove the round trip worked
  • Values should match originals
std::cout << m2 << " " << mo2
     << " " << mi2 << " " << p2;

Check: Reading Order

The file was written make, model, mileage, price. What happens if the read order is swapped?

Each >> just grabs the next token: swapping the order reads price into make, mileage into model, and so on.

Check: Why Check if(!out)?

ofstream out("inventory.txt"); might fail, e.g. a bad path. Why check it before writing?

Writing to a broken stream silently does nothing: checking first catches the problem right away.

Check: One Car or Many?

The lab writes make, model, mileage, price all on one line. Could you store 10 cars this way?

Yes: write one line per car, then read with the same while(in >> ...) loop from Reading a File.

Deliverable

  • A real lot.txt file written
  • Printed proof it read back
  • Submit source and screenshot
Honda Civic 23000 18500.00

Practice Lab Part 2

Scenario: The Lot Report

  • lot.txt now holds many cars
  • Read every row in a loop
  • Print a formatted total value
💾lot.txt: many rows🔄Loop: read each row💵Formatted total

Step 1: Open for Reading

  • ifstream opens lot.txt
  • double total starts at zero
#include <fstream>
std::ifstream in("lot.txt");
double total = 0.0;

Step 2: Loop Over Every Row

  • while reads to end of file
  • Four fields match write order
string make, model;
int mileage;
double price;
while (in >> make >> model
       >> mileage >> price) {

Step 3: Add to the Running Total

  • total += price each pass
  • Closes the while loop
  total += price;
}

Step 4: Format the Total

  • fixed and setprecision(2)
  • Reads like real currency
#include <iomanip>
std::cout << std::fixed
  << std::setprecision(2);
std::cout << "Total: $" << total;

Check: Precision Before the Loop

setprecision(2) is set once, before the loop runs. Does every cout inside the loop stay affected?

Yes: fixed and setprecision are sticky settings on the stream, they stay until explicitly changed again.

Step 5: Parsing a Mixed Line

  • A pasted line of fields
  • stringstream splits fields
#include <sstream>
std::stringstream ss("Honda 23000 18500");
string mk; int mi; double pr;
ss >> mk >> mi >> pr;

Check: Reusing >>

stringstream, ifstream, and cin all support >>. Why does learning one stream type teach you all three?

They all inherit the same istream interface, so >> behaves identically regardless of where data comes from.

Check: What if a Row Is Bad?

One row in lot.txt is missing its price field. What happens to the while(in >> ...) loop?

That read fails, the stream enters a fail state, and the loop condition goes false, ending early.

Check: total Starts at 0.0

double total = 0.0; is declared before the loop, not inside it. Why does that placement matter?

Declaring it inside the loop would reset total to 0 on every pass, losing the running sum.

Deliverable

  • A loop that totals every row
  • Total printed as real currency
  • One line parsed via ss
Total: $42000.00

Questions?

Use Case: Saving a High Score

  • ofstream writes one number
  • Survives closing the game
  • Next run reads it back
Game endsofstreamscore.txt saved

Use Case: Reading a Config File

  • Settings live outside the code
  • ifstream loads them at start
  • No recompile to change them
config.txtifstreamsettings loaded

Use Case: Logging Errors

  • cerr is a separate stream
  • Keeps errors off normal output
  • Easy to redirect separately
Bad input foundcerrerror printed

Use Case: Parsing CSV-like Data

  • One line, several fields
  • stringstream splits by token
  • Same >> pattern each time
"A,23,4.5"stringstream3 separate values

Use Case: Appending to a Log

  • Each run adds new lines
  • ios::app never erases old ones
  • The file grows over time
App startsios::appline appended

Use Case: Building a Report

  • Pieces joined with <<
  • Stays in memory, not a file
  • str() returns the result
Several valuesostringstreamone text string

More Stream Tools

getline() Reads a Full Line

  • getline stops at the newline
  • >> alone would stop at a space
#include <fstream>
string line;
getline(in, line);

ios::app: Append, Don't Erase

  • Second argument picks the mode
  • New writes go after old data
#include <fstream>
std::ofstream out("lot.txt", std::ios::app);

eof(): Did the File Run Out?

  • True once reading hits the end
  • Common loop-ending check
#include <fstream>
while (!in.eof()) { ... }

The Read Cursor at EOF

  • Reading moves a cursor forward
  • eof() checks: past the end?
  • True only once it is
HONDAEOF▲eof() is true: cursor sits past the last char.

clear(): Reset a Bad Read

  • A failed read sets a flag
  • clear() lets reading continue
#include <fstream>
in.clear();

A Fail Flag Blocks Reading

  • A bad read sets a fail flag
  • Every read after it fails too
  • clear() wipes the flag away
HONDAEOFfail flag: SETclear() resets itA bad read sets a flag; clear() lets reading resume.

ignore(): Skip Ahead

  • Skips a count of characters
  • Clears a leftover newline
#include <fstream>
in.ignore(100, '\\n');

The Cursor Jumps Ahead

  • ignore() moves past N chars
  • Those chars are never read
  • The cursor lands after them
HONDAEOFskipped▲ignore(3) skips 3 chars; cursor lands after them.

peek(): Look, Don't Take

  • Shows the next character
  • Leaves it in the stream
#include <fstream>
char c = in.peek();

Looking Without Moving

  • peek() reads the next char
  • But the cursor stays put
  • The next real read sees it too
HONDAEOF▲looks herepeek() looks ahead one char; the cursor doesn't move.

get(): One Character at a Time

  • Reads one char, even a space
  • >> would skip the space
#include <fstream>
char c;
in.get(c);

get() Moves One Box at a Time

  • get() reads exactly one char
  • Spaces count as real chars too
  • Cursor moves ahead by one
HONDAEOF▲get() reads exactly one char, even a space.

boolalpha: Print true, Not 1

  • Spells out true and false
  • Without it, bools print 0/1
#include <iostream>
std::cout << std::boolalpha;
std::cout << sold;

setfill(): Pick the Pad Character

  • Pairs with setw() for padding
  • Default pad is a plain space
#include <iomanip>
std::cout << std::setfill('0')
  << std::setw(5) << id;

left: Align Text to the Left

  • setw() right-aligns by default
  • left flips that alignment
#include <iomanip>
std::cout << std::left
  << std::setw(10) << make;

hex: Print Integers in Hex

  • Switches the base for integers
  • dec switches it back
#include <iostream>
std::cout << std::hex << id;

cerr: A Separate Error Stream

  • Same syntax as cout
  • Meant for error messages only
#include <iostream>
std::cerr << "Price can't be negative";

endl vs "\\n"

  • endl also flushes the buffer
  • "\\n" alone is faster
#include <iostream>
std::cout << "Done" << std::endl;

is_open(): Did It Really Open?

  • Checks the file opened
  • A safer check than just !in
#include <fstream>
if (!in.is_open()) { ... }

close(): Release the File

  • Frees the file for others
  • Auto-called at scope end
#include <fstream>
in.close();

tellg() / seekg(): Stream Position

  • tellg() reports where you are
  • seekg() jumps to a position
  • Lets you re-read earlier data
#include <fstream>
int pos = in.tellg();
in.seekg(0);  // back to the start

ostringstream: Build a String

  • Writes with <<, like cout
  • Collects it all in memory
  • str() hands back one string
#include <sstream>
std::ostringstream oss;
oss << make << ": " << price;
string report = oss.str();

Three Stream Types, One Pattern

  • ifstream reads a real file
  • ofstream writes a real file
  • stringstream works on a string
ifstreamfile → programofstreamprogram → filestringstreamstring ↔ programAll three use >> and << the same way

Questions?

Practice Quiz

Practice Quiz: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question.

ifstream
ofstream
Stream
Open
Connects a stream to an actual file
Releases a file once a program is done with it
Character marking where one value ends
Reads a full line of text from a stream
The location of a file on disk
Object used to read from a file
Object used to write to a file
A flow of data between a program and a source
Close
Delimiter
getline
File Path

Questions?

Practice Lab Part 3

Scenario: Stockton Weather

  • A real JSON file, 31 days
  • Parse it, don't just read it
  • Answer 10 real questions
weather.json31 days of real-looking data,made up for this lab

Get the Data

  • No install needed
  • One JSON file on GitHub
  • Save it next to your .cpp
$ git clone https://github.com/SE4CPS/\
2026-COMP-051.git
$ cd 2026-COMP-051/practice-lab-weather
$ ls
weather.json

The Data Format

  • One object per line
  • date, high, low, condition
  • Still valid JSON overall
{"date": "2026-07-11","high": 104.9, "low": 72.0,"condition": "Sunny"}

The Fast Way: No Objects

  • No struct, no class, no vector
  • Just a few running totals
  • One pass, done when it ends
Read One LinePull Out the NumberUpdate the Running AnswerRepeat for every line

Fast Way: What You Need

  • fstream: read the file
  • string: stod, getline too
  • algorithm: for max()
#include <fstream>   // file I/O: ifstream
#include <string>    // string, stod, getline
#include <algorithm> // max()
using namespace std;

Fast Q1: Hottest High

  • Scan every line's high
  • Keep the biggest so far
  • No object, just one double
Which bar is tallest?31 lines, read one at a time

Fast Answer: Hottest High

  • Output: 104.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);
  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
Which bar is shortest?31 lines, read one at a time

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
sum+count

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
sum+count

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
Count the Sunny squares

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
Count squares over 95°F

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
Which gap is widest?31 lines, read one at a time

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
Which bar is shortest?31 lines, read one at a time

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
SunSunCloSunStoCloUnique Values OnlyDuplicates collapse into one

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
Coldest LowHottest High? degrees apart

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;

WeatherDay: Now an Object

  • A class, not a bare struct
  • The constructor builds one
  • Each day is its own object
class WeatherDay {
public:
  string date;
  double high, low;
  string condition;
  WeatherDay(string d, double h, double l,
             string c) : date(d), high(h),
             low(l), condition(c) {}
};

field(): Pulling Out a Value

  • Finds text after a key
  • Stops at a comma or brace
  • Skips the opening quote
string field(string line, string key) {
  int p = line.find(key) + key.length();
  if (line[p] == '"') p++;
  int q = line.find_first_of("\",}", p);
  return line.substr(p, q - p);
}

parseLine(): Build One Object

  • Calls field() four times
  • Converts numbers with stod()
  • Returns a new WeatherDay
WeatherDay parseLine(string line) {
  string ck = "\"condition\": ";
  return WeatherDay(
    field(line, "\"date\": "),
    stod(field(line, "\"high\": ")),
    stod(field(line, "\"low\": ")),
    field(line, ck));
}

loadWeather(): Read Every Line

  • getline() reads one row
  • Skip the [ and ] lines
  • parseLine() does the work
vector<WeatherDay> loadWeather(string file) {
  vector<WeatherDay> days;
  ifstream in(file);
  string line;
  while (getline(in, line)) {
    if (line.size() < 20) continue;
    days.push_back(parseLine(line));
  }
  return days;
}

main.cpp: Loading the File

  • One call loads every day
  • days.size() confirms it read
  • Now ready for Q1-Q10
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
Which bar is tallest?31 days, one bar each

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
Which bar is shortest?31 days, one bar each

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()
sum+count

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
sum+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
Count the Sunny squares

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
Count squares over 95°F

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
Which gap is widest?31 days, one bar each

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
Which bar is shortest?31 days, one bar each

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
SunSunCloSunStoCloUnique Values OnlyDuplicates collapse into one

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
Coldest LowHottest High? degrees apart

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;

Deliverable

  • Your 10 answers, with code
  • weather.json, not hardcoded
  • Submit source and output
2026-07-11: 104.9
2026-07-27: 57.9
Avg high: 93.47
...

Header Files Used

Why #include Matters

  • Each library has its header
  • #include adds declarations
  • Missing one won't compile

Header Files Used in This Module

HeaderProvidesUsed For
#include <iostream>cin, cout, cerrBasic console input/output
#include <fstream>ifstream, ofstreamReading and writing files
#include <sstream>stringstream, ostringstreamParsing and building strings
#include <iomanip>setw, setprecision, setfillFormatting printed output
#include <string>std::string, getline()Storing and reading text

Word Origin: "Stream"

  • Old English: a course of water
  • Borrowed as a computing metaphor
  • Continuous, ordered data flow
Data flows, in order, like water

Looking Ahead: Module 10

Vehicle* p p->describe() "A car..." "A truck..." One call. Different behavior.

What Is Polymorphism?

What Is Polymorphism?

  • Greek: poly + morph
  • One call, many behaviors
  • Depends on the real object
v->describe()"A car""A truck""A bike"The exact same line of code runs adifferent describe() depending on the real object.

Check: Overriding or Polymorphism?

Writing Car's own describe() is overriding. What is it called when one line of code picks the right one at runtime?

Polymorphism. Overriding sets up the different versions; polymorphism is choosing the right one automatically.

Virtual Functions

Why virtual Matters

  • No virtual: base version runs
  • With virtual: real object wins
  • One keyword changes everything
❌No virtual: always base✅virtual: the real type🎯Matches what you expect

Step 1: Mark It virtual

  • virtual goes in the base class
  • Signals: children may override
  • Only needs it once, in Vehicle
class Vehicle {
public:
  virtual string describe() {
    return "A vehicle";
  }
};

Check: Where Does virtual Go?

Does virtual need to be repeated on Car's own describe(), or only on Vehicle's?

Only on Vehicle's. Once a function is virtual in the base class, every override stays virtual automatically.

Mechanic::role()

Mechanic overrides role().
Base: a general staff role.
Mechanic: certified repair technician.

virtual string role() {
  return "a general staff role";
}
// in Mechanic:
string role() {
  return "certified repair technician";
}

Salesperson::role()

Salesperson overrides role().
Base: a general staff role.
Salesperson: vehicle sales specialist.

virtual string role() {
  return "a general staff role";
}
// in Salesperson:
string role() {
  return "vehicle sales specialist";
}

CustomerAccount::summary()

CustomerAccount overrides summary().
Base: a generic account summary.
CustomerAccount: buyer purchase history.

virtual string summary() {
  return "a generic account summary";
}
// in CustomerAccount:
string summary() {
  return "buyer purchase history";
}

DealerAccount::summary()

DealerAccount overrides summary().
Base: a generic account summary.
DealerAccount: seller commission record.

virtual string summary() {
  return "a generic account summary";
}
// in DealerAccount:
string summary() {
  return "seller commission record";
}

Invoice::details()

Invoice overrides details().
Base: a generic document.
Invoice: amount due and due date.

virtual string details() {
  return "a generic document";
}
// in Invoice:
string details() {
  return "amount due and due date";
}

Warranty::details()

Warranty overrides details().
Base: a generic document.
Warranty: months of coverage left.

virtual string details() {
  return "a generic document";
}
// in Warranty:
string details() {
  return "months of coverage left";
}

Tire::status()

Tire overrides status().
Base: a generic part status.
Tire: tread depth reading.

virtual string status() {
  return "a generic part status";
}
// in Tire:
string status() {
  return "tread depth reading";
}

Battery::status()

Battery overrides status().
Base: a generic part status.
Battery: voltage reading.

virtual string status() {
  return "a generic part status";
}
// in Battery:
string status() {
  return "voltage reading";
}

Garage::info()

Garage overrides info().
Base: a generic facility.
Garage: open repair bays.

virtual string info() {
  return "a generic facility";
}
// in Garage:
string info() {
  return "open repair bays";
}

Dealership::info()

Dealership overrides info().
Base: a generic facility.
Dealership: cars in inventory.

virtual string info() {
  return "a generic facility";
}
// in Dealership:
string info() {
  return "cars in inventory";
}

Sale::detail()

Sale overrides detail().
Base: a generic transaction.
Sale: final sale price.

virtual string detail() {
  return "a generic transaction";
}
// in Sale:
string detail() {
  return "final sale price";
}

TradeIn::detail()

TradeIn overrides detail().
Base: a generic transaction.
TradeIn: appraised value.

virtual string detail() {
  return "a generic transaction";
}
// in TradeIn:
string detail() {
  return "appraised value";
}

Insurance::terms()

Insurance overrides terms().
Base: generic policy terms.
Insurance: premium and coverage.

virtual string terms() {
  return "generic policy terms";
}
// in Insurance:
string terms() {
  return "premium and coverage";
}

ReturnPolicy::terms()

ReturnPolicy overrides terms().
Base: generic policy terms.
ReturnPolicy: days allowed to return.

virtual string terms() {
  return "generic policy terms";
}
// in ReturnPolicy:
string terms() {
  return "days allowed to return";
}

Inspection::note()

Inspection overrides note().
Base: a generic record.
Inspection: pass or fail result.

virtual string note() {
  return "a generic record";
}
// in Inspection:
string note() {
  return "pass or fail result";
}

Registration::note()

Registration overrides note().
Base: a generic record.
Registration: expiration date.

virtual string note() {
  return "a generic record";
}
// in Registration:
string note() {
  return "expiration date";
}

GPS::status()

GPS overrides status().
Base: a generic device status.
GPS: signal strength.

virtual string status() {
  return "a generic device status";
}
// in GPS:
string status() {
  return "signal strength";
}

KeyFob::status()

KeyFob overrides status().
Base: a generic device status.
KeyFob: battery level.

virtual string status() {
  return "a generic device status";
}
// in KeyFob:
string status() {
  return "battery level";
}

Receptionist::duty()

Receptionist overrides duty().
Base: a generic staff duty.
Receptionist: desk and phone duty.

virtual string duty() {
  return "a generic staff duty";
}
// in Receptionist:
string duty() {
  return "desk and phone duty";
}

Manager::duty()

Manager overrides duty().
Base: a generic staff duty.
Manager: oversees the floor.

virtual string duty() {
  return "a generic staff duty";
}
// in Manager:
string duty() {
  return "oversees the floor";
}

UsedCarListing::pitch()

UsedCarListing overrides pitch().
Base: a generic listing pitch.
UsedCarListing: mileage and history.

virtual string pitch() {
  return "a generic listing pitch";
}
// in UsedCarListing:
string pitch() {
  return "mileage and history";
}

NewCarListing::pitch()

NewCarListing overrides pitch().
Base: a generic listing pitch.
NewCarListing: trim and color options.

virtual string pitch() {
  return "a generic listing pitch";
}
// in NewCarListing:
string pitch() {
  return "trim and color options";
}

ServiceReview::summary()

ServiceReview overrides summary().
Base: a generic review summary.
ServiceReview: rates the repair work.

virtual string summary() {
  return "a generic review summary";
}
// in ServiceReview:
string summary() {
  return "rates the repair work";
}

SalesReview::summary()

SalesReview overrides summary().
Base: a generic review summary.
SalesReview: rates the sale process.

virtual string summary() {
  return "a generic review summary";
}
// in SalesReview:
string summary() {
  return "rates the sale process";
}

RentalCar::use()

RentalCar overrides use().
Base: generic vehicle use.
RentalCar: daily rental use.

virtual string use() {
  return "generic vehicle use";
}
// in RentalCar:
string use() {
  return "daily rental use";
}

DemoCar::use()

DemoCar overrides use().
Base: generic vehicle use.
DemoCar: showroom test drives.

virtual string use() {
  return "generic vehicle use";
}
// in DemoCar:
string use() {
  return "showroom test drives";
}

MechanicShift::plan()

MechanicShift overrides plan().
Base: a generic shift plan.
MechanicShift: bays assigned today.

virtual string plan() {
  return "a generic shift plan";
}
// in MechanicShift:
string plan() {
  return "bays assigned today";
}

FrontDeskShift::plan()

FrontDeskShift overrides plan().
Base: a generic shift plan.
FrontDeskShift: calls handled today.

virtual string plan() {
  return "a generic shift plan";
}
// in FrontDeskShift:
string plan() {
  return "calls handled today";
}

LoyaltyDiscount::rule()

LoyaltyDiscount overrides rule().
Base: a generic discount rule.
LoyaltyDiscount: points required.

virtual string rule() {
  return "a generic discount rule";
}
// in LoyaltyDiscount:
string rule() {
  return "points required";
}

SeasonalDiscount::rule()

SeasonalDiscount overrides rule().
Base: a generic discount rule.
SeasonalDiscount: season it applies.

virtual string rule() {
  return "a generic discount rule";
}
// in SeasonalDiscount:
string rule() {
  return "season it applies";
}

MaintenanceAlert::message()

MaintenanceAlert overrides message().
Base: a generic alert message.
MaintenanceAlert: mileage due for service.

virtual string message() {
  return "a generic alert message";
}
// in MaintenanceAlert:
string message() {
  return "mileage due for service";
}

RecallAlert::message()

RecallAlert overrides message().
Base: a generic alert message.
RecallAlert: the recall identifier.

virtual string message() {
  return "a generic alert message";
}
// in RecallAlert:
string message() {
  return "the recall identifier";
}

LeaseContract::summary()

LeaseContract overrides summary().
Base: a generic contract summary.
LeaseContract: months of the term.

virtual string summary() {
  return "a generic contract summary";
}
// in LeaseContract:
string summary() {
  return "months of the term";
}

FinanceContract::summary()

FinanceContract overrides summary().
Base: a generic contract summary.
FinanceContract: the interest rate.

virtual string summary() {
  return "a generic contract summary";
}
// in FinanceContract:
string summary() {
  return "the interest rate";
}

ParkingSpot::note()

ParkingSpot overrides note().
Base: a generic space note.
ParkingSpot: occupied or open.

virtual string note() {
  return "a generic space note";
}
// in ParkingSpot:
string note() {
  return "occupied or open";
}

LoadingDock::note()

LoadingDock overrides note().
Base: a generic space note.
LoadingDock: max load weight.

virtual string note() {
  return "a generic space note";
}
// in LoadingDock:
string note() {
  return "max load weight";
}

RepairTicket::status()

RepairTicket overrides status().
Base: a generic ticket status.
RepairTicket: the issue reported.

virtual string status() {
  return "a generic ticket status";
}
// in RepairTicket:
string status() {
  return "the issue reported";
}

WarrantyTicket::status()

WarrantyTicket overrides status().
Base: a generic ticket status.
WarrantyTicket: the claim type.

virtual string status() {
  return "a generic ticket status";
}
// in WarrantyTicket:
string status() {
  return "the claim type";
}

SalesReport::title()

SalesReport overrides title().
Base: a generic report title.
SalesReport: units sold this period.

virtual string title() {
  return "a generic report title";
}
// in SalesReport:
string title() {
  return "units sold this period";
}

ServiceReport::title()

ServiceReport overrides title().
Base: a generic report title.
ServiceReport: jobs closed this period.

virtual string title() {
  return "a generic report title";
}
// in ServiceReport:
string title() {
  return "jobs closed this period";
}

MechanicBadge::label()

MechanicBadge overrides label().
Base: a generic badge label.
MechanicBadge: the repair specialty.

virtual string label() {
  return "a generic badge label";
}
// in MechanicBadge:
string label() {
  return "the repair specialty";
}

SafetyBadge::label()

SafetyBadge overrides label().
Base: a generic badge label.
SafetyBadge: the safety course taken.

virtual string label() {
  return "a generic badge label";
}
// in SafetyBadge:
string label() {
  return "the safety course taken";
}

TrainingSession::topic()

TrainingSession overrides topic().
Base: a generic session topic.
TrainingSession: the staff training topic.

virtual string topic() {
  return "a generic session topic";
}
// in TrainingSession:
string topic() {
  return "the staff training topic";
}

DemoSession::topic()

DemoSession overrides topic().
Base: a generic session topic.
DemoSession: the model being shown.

virtual string topic() {
  return "a generic session topic";
}
// in DemoSession:
string topic() {
  return "the model being shown";
}

MaintenanceLog::entry()

MaintenanceLog overrides entry().
Base: a generic log entry.
MaintenanceLog: the mileage recorded.

virtual string entry() {
  return "a generic log entry";
}
// in MaintenanceLog:
string entry() {
  return "the mileage recorded";
}

IncidentLog::entry()

IncidentLog overrides entry().
Base: a generic log entry.
IncidentLog: the severity recorded.

virtual string entry() {
  return "a generic log entry";
}
// in IncidentLog:
string entry() {
  return "the severity recorded";
}

PartsBudget::line()

PartsBudget overrides line().
Base: a generic budget line.
PartsBudget: amount spent on parts.

virtual string line() {
  return "a generic budget line";
}
// in PartsBudget:
string line() {
  return "amount spent on parts";
}

MarketingBudget::line()

MarketingBudget overrides line().
Base: a generic budget line.
MarketingBudget: amount spent on ads.

virtual string line() {
  return "a generic budget line";
}
// in MarketingBudget:
string line() {
  return "amount spent on ads";
}

ServiceZone::label()

ServiceZone overrides label().
Base: a generic zone label.
ServiceZone: bays currently open.

virtual string label() {
  return "a generic zone label";
}
// in ServiceZone:
string label() {
  return "bays currently open";
}

ShowroomZone::label()

ShowroomZone overrides label().
Base: a generic zone label.
ShowroomZone: cars on the floor.

virtual string label() {
  return "a generic zone label";
}
// in ShowroomZone:
string label() {
  return "cars on the floor";
}

PartsShipment::note()

PartsShipment overrides note().
Base: a generic shipment note.
PartsShipment: items in this shipment.

virtual string note() {
  return "a generic shipment note";
}
// in PartsShipment:
string note() {
  return "items in this shipment";
}

CarShipment::note()

CarShipment overrides note().
Base: a generic shipment note.
CarShipment: vehicles in this shipment.

virtual string note() {
  return "a generic shipment note";
}
// in CarShipment:
string note() {
  return "vehicles in this shipment";
}

ServiceAppt::focus()

ServiceAppt overrides focus().
Base: a generic appointment focus.
ServiceAppt: the service requested.

virtual string focus() {
  return "a generic appointment focus";
}
// in ServiceAppt:
string focus() {
  return "the service requested";
}

TestDrive::focus()

TestDrive overrides focus().
Base: a generic appointment focus.
TestDrive: the planned route.

virtual string focus() {
  return "a generic appointment focus";
}
// in TestDrive:
string focus() {
  return "the planned route";
}

Pointers to the Base Class

A Base Pointer, Many Objects

  • Vehicle* points to any child
  • Legal, since Car IS-A Vehicle
  • The pointer stays Vehicle*
Vehicle* va real Car objectpoints to anyVehicle-derived type

Step 2: Point at a Car

  • Vehicle* holds a Car's address
  • &c: the address-of operator
  • Legal because Car IS-A Vehicle
Car c;
Vehicle* v = &c;

Check: Is This Legal?

Truck t; Vehicle* v = &t;. Is this legal, given Truck also inherits from Vehicle?

Yes. Any class that inherits from Vehicle can have its address stored in a Vehicle pointer.

Calling Through a Pointer

Step 3: Call Through v

  • v->describe() uses an arrow
  • virtual runs Car's version
  • Not Vehicle's version
Vehicle* v = &c;
std::cout << v->describe();
// prints Car's version

Without virtual: The Old Behavior

  • No virtual: always Vehicle's
  • The pointer type wins here
  • This is why virtual matters
🚗Vehicle* v = &c❌No virtual on describe()🚫Always prints "A vehicle"

Check: Same Call, Different Object

Vehicle* v; v points first at a Car, then at a Truck. Does v->describe() print the same thing both times?

No, if describe() is virtual: it prints Car's version first, then Truck's, matching the real object each time.

Abstract Classes

A Class You Can Never Build

  • = 0 means pure virtual
  • No body at all in Vehicle
  • Every child MUST provide one
Vehicle v; // will not compileCar c; // fine, Car is concrete

Step 4: A Pure Virtual Function

  • = 0 instead of a body
  • Vehicle becomes abstract
  • Only children can be built
class Vehicle {
public:
  virtual string describe() = 0;
};

Check: What Must Car Do Now?

Vehicle::describe() is pure virtual. What happens if Car does not define its own describe()?

Car itself becomes abstract too, and cannot be built, until it provides its own describe().

Arrays of Base Pointers

One Array, Mixed Objects

  • Vehicle* fleet[3]
  • Each slot: any real type
  • Loop once, every type handled
Vehicle* fleet[3]-> Car-> Truck-> Motorcycle

Step 5: Build the Array

  • Three different real types
  • All stored as Vehicle pointers
  • One array holds them all
Car c;
Truck t;
Motorcycle m;
Vehicle* fleet[3] = {&c, &t, &m};

Step 6: Loop and Call

  • One loop, three outputs
  • Picks the real describe()
  • Polymorphism, in practice
for (int i = 0; i < 3; i++) {
  std::cout << fleet[i]->describe();
}

Check: Three Calls, One Line

The loop above runs fleet[i]->describe() for i = 0, 1, 2. Does it print the same text three times?

No. Each slot points at a different real object, so each call prints that object's own describe().

Practice Lab

Requirements: Make describe() virtual

  • Start from Module 8's classes
  • Add virtual to describe()
  • Car/Truck still override it
🚗Vehicle: virtual describe()🚘🚛Car, Truck already override✅Now it is real polymorphism

Step 1: Mark Vehicle Virtual

  • Just one keyword added
  • No other code needs to change
  • Car, Truck already override
class Vehicle {
public:
  virtual string describe() {
    return "A vehicle";
  }
};

Step 2: Build Three Objects

  • One Car, Truck, base pointer
  • Point it at each in turn
  • Call describe() each time
Car c;
Truck t;
Vehicle* v = &c;
std::cout << v->describe();
v = &t;
std::cout << v->describe();

Check: Prove It Is Real

How could you prove to a classmate that this is really calling Car and Truck's own versions, not Vehicle's?

Make Vehicle's own text obviously different, like "A vehicle (base)", and show it never actually prints.

Deliverable

  • Add virtual to Vehicle
  • Point at Car, then Truck
  • Show both real versions print
✏️Add virtual👈Point at each object✅Show both outputs

Practice Lab Part 2

Scenario: The Whole Fleet, Polymorphically

  • An array of Vehicle pointers
  • Car, Truck, Motorcycle, mixed
  • One loop, every real type
🚗🚛🏍Three real objects📊One Vehicle* array✅One loop, three outputs

Step 1: Build the Fleet Array

  • One of each real vehicle type
  • Stored as Vehicle pointers
  • The array type never changes
Car c;
Truck t;
Motorcycle m;
Vehicle* fleet[3] = {&c, &t, &m};

Step 2: Print the Whole Fleet

  • One loop handles every type
  • No if/else needed at all
  • Polymorphism, not branching
for (int i = 0; i < 3; i++)
  std::cout << fleet[i]->describe()
       << "\n";

Extension: Add a Fourth Type

Add an RV class with its own describe(), then add it to the fleet array.

class RV : public Vehicle {
public:
  string describe() {
    return "An RV";
  }
};

Check: Why No if/else?

The loop in Step 2 never checks what type each fleet[i] really is. Why does it still print the right thing?

Because describe() is virtual: the correct version runs automatically based on the real object, no if/else needed.

Deliverable

  • Build the 3-vehicle fleet
  • Loop, print every describe()
  • Show one output per real type
✏️Build the fleet array🔄Loop through it once✅Show 3 distinct outputs

Word Origin: "Polymorphism"

  • Greek "poly": many
  • Greek "morphe": form, shape
  • Together: "many forms"
One base pointer, many real shapes: the same call takes a different form each time

Looking Ahead: Module 11

Why This Matters

  • PL/I had early error handling
  • CLU formalized signaling
  • Separates errors from logic
1964PL/I (IBM) adds ON-conditions,early error handling 1975CLU (Barbara Liskov, MIT):structured exception signaling 1983Ada adds exceptions to thelanguage standard 1990C++ standardizes try / catch/ throw TodayExceptions separate errorhandling from normal logic
try { setMileage(-5); } throw catch (BadMileage& e) A thrown error jumps straight to catch.

What Is an Exception?

What Is an Exception?

  • An error, raised at runtime
  • Separates errors from the flow
  • Handled far from the origin
🚨Something goes wrong✈️Thrown up the call stack🛡️Caught, handled safely

Why Automotive Code Avoids Exceptions

Unpredictable TimingUnwinding can't meet a hard deadlineExtra Memory CostUnwind tables cost scarce flash/RAMMISRA / AUTOSAR BansMany ECU rulesets restrict throw

Word Origin: "Fault"

  • Latin "fallere": to deceive
  • Entered auto repair, 1960s
  • OBD-II made it a code
A fault names a detected defect,formalized by SAE J2012's ownDiagnostic Trouble Code standard

Source: SAE J2012 (Diagnostic Trouble Codes)

Real-World Example: Toyota (2009-2010)

  • NASA probe ran 2011-2013
  • Found a stack overflow bug
  • No isolation caught the fault
⚠️A software fault occurs🚫No layer isolates it🚗Throttle control corrupted

Source: NASA Engineering & Safety Center; Barr Group testimony (2013)

History: Fault Codes to Exceptions

  • OBD-I: basic fault lamp, 1988
  • OBD-II: standard codes, 1996
  • Now: C++ exceptions inside
1988OBD-I: California mandates basiconboard fault detection1996OBD-II standardizes DiagnosticTrouble CodesTodayECUs pair DTCs with internalC++ exceptions

Automotive Use Case: Fuel Level Fault

  • Sensor reads below empty
  • FuelFault exception thrown
  • Dashboard warning lit
⚙️Sensor reads below empty🚨FuelFault exception thrown🔈Warning lamp, fault logged

Automotive Use Case: ABS Sensor Dropout

  • Wheel-speed signal lost
  • SensorFault exception thrown
  • ABS disables, lamp lit
🚘Wheel-speed signal lost⚠️SensorFault exception thrown💡ABS disabled, lamp lit

Word Origin: "Diagnostic"

  • Greek "diagnostikos": able
  • to distinguish, 19th century
  • Entered OBD scan tools, 1980s
A diagnostic distinguishes whichfault actually occurred, the samejob a caught exception type does

Source: Oxford English Dictionary (etymology)

Automotive Use Case: Airbag Fault

  • Squib circuit reads open
  • AirbagFault exception thrown
  • SRS lamp, fault stored
🚧Squib circuit reads open🚨AirbagFault exception thrown📌SRS lamp, code stored

Fault Propagation Through ECU Layers

Sensor DriverReads the raw out-of-range valueFault DetectionClassifies it as a specific faultDiagnostic ManagerLogs a Diagnostic Trouble CodeDashboard TelltaleShows the driver a warning lamp

Automotive Use Case: Brake Pressure Fault

  • Line pressure reads too low
  • BrakeFailure exception thrown
  • ABS limited, lamp lit
🚗Brake line pressure too low⚠️BrakeFailure exception thrown🚨ABS limited, driver warned

Real-World Example: SAE J1939 Codes

  • Trucks and buses use these too
  • SPN/FMI codes name the fault
  • Kept off normal CAN traffic
🚗SPN: which component🔍FMI: what kind of failure✅Same split as throw/catch

Source: SAE J1939 (Diagnostic Messages)

Real-World Example: Why ECUs Log Faults

  • Fault code stored in NVRAM
  • Survives a reboot or power cut
  • Pulled later by a scan tool
🚨Fault detected, code stored💾Stays in NVRAM through reboot🔍Scan tool reads it at service

Automotive Use Case: Engine Overheat

  • Coolant runs hotter than safe
  • SensorFault exception thrown
  • Power limited, lamp lit
🌡️Coolant temperature too high⚠️SensorFault exception thrown🚨Engine power limited, lamp lit

Check: Why Not Just Return -1?

A function could return -1 to signal an error, instead of throwing. What does that approach miss?

A caller can silently ignore a return value; a thrown exception cannot be ignored, it must be handled.

Errors Without Exceptions

🚔setMileage(-5) runs➡️Returns -1, caller ignores it🚨Car saves mileage: -5

Questions?

throw and catch

throw Raises It

  • throw sends a value upward
  • Can throw almost any type
  • A string, or an exception type
🚨if (mileage < 0)✈️throw std::string(...)🛡️Caught somewhere above

Step 1: throw

  • Guard the bad input
  • throw exits the function here
if (mileage < 0) {
  throw std::string("Bad mileage");
}

Step 2: try and catch

  • try wraps risky code
  • catch handles a matching throw
try {
  setMileage(-500);
} catch (std::string& msg) {
  std::cout << msg;
}

Check: What If Nothing Catches It?

A thrown exception has no matching catch anywhere up the call stack. What happens to the program?

The runtime calls std::terminate and the program crashes: an uncaught exception always ends execution.

Word Origin: "Throw"

  • From Old Norse "thrawa"
  • CLU (1975) called it "signal"
  • C++ chose the ball metaphor
A thrown exception is launchedup the call stack, like tossinga ball for someone else to catch

What Can You Throw?

  • Any type: int, string, class
  • Usually an exception type
  • Never a raw pointer, by habit
📄throw BadMileage()📄throw std::string(...)⚠️throw 42; (legal, unclear)

Word Origin: "Catch"

  • Matches "throw"'s metaphor
  • You "catch" what was thrown
  • By reference, to avoid a copy
Catching completes the throw/catchmetaphor: a handler interceptsthe exception before it falls

Questions?

Multiple catch Blocks

Catching Different Types

  • Each catch checks one type
  • First matching catch runs
try { ... }
catch (int& code) { ... }
catch (std::string& msg) { ... }

catch (...): Catch Anything

  • Three dots: matches any type
  • A last-resort safety net
try { ... }
catch (...) {
  std::cout << "Unknown error";
}

Check: Order Matters

catch(...) is written BEFORE catch(std::string&) in the same try. Does the string catch ever run?

No: catch(...) matches everything and runs first, so the more specific catch below it is unreachable.

Exception Propagation: First Match Wins

🚨BrakeFailure is thrown🔍catch(int): no match, skipped🛡️catch(BrakeFailure&): matches

Questions?

Standard Exception Types

The <stdexcept> Family

  • All derive from std::exception
  • what() returns the message
  • Built-in, ready to throw
📊std::out_of_range❌std::invalid_argument⚠️std::runtime_error

Using a Standard Type

  • #include <stdexcept>
  • Carries a real message string
if (mileage < 0) {
  throw std::invalid_argument("Bad mileage");
}

Reading the Message: what()

  • what() returns a C-string
  • Works on any std::exception
catch (std::exception& e) {
  std::cout << e.what();
}

Check: Why catch(std::exception&)?

invalid_argument, out_of_range, and runtime_error are all different types. Why does one catch handle them all?

They all inherit from std::exception, so a reference to the base class matches any of its derived types.

Check: Which Type Fits Best?

A fuel gauge reads a value outside 0–100%. Which standard type names that problem best?

std::out_of_range: the value is outside the domain a valid reading can ever have.

Questions?

Custom Exception Classes

Your Own Exception Type

  • Inherit from std::exception
  • Override what() yourself
  • Reuses Module 8/9's own ideas
📄class BadVin🔗: public std::exception✅Overrides what()

Step 1: Declare the Class

  • Inherits from std::exception
  • override marks the real match
class BadVin : public std::exception {
public:
  const char* what() const override {
    return "Invalid VIN";
  }
};

Step 2: Throw and Catch It

  • Same try/catch pattern
  • catch by reference, not value
try {
  throw BadVin();
} catch (BadVin& e) {
  std::cout << e.what();
}

Check: Why catch by Reference?

catch (BadVin& e) uses a reference. What could go wrong with catch (BadVin e) instead, by value?

A by-value catch copies (and can slice) the object; a reference avoids the copy and preserves the real type.

Step 3: Add Context to what()

  • Store the bad value itself
  • Build the message in the ctor
class BadVin : public std::exception {
  std::string msg;
public:
  BadVin(std::string v) {
    msg = "Bad VIN: " + v;
  }
  const char* what() const override {
    return msg.c_str();
  }
};

Check: Why Include the Value?

Both messages say "bad VIN". Why is printing the actual VIN worth the extra code?

A tech reading the log sees exactly which VIN failed, not just that some VIN failed.

Questions?

Cleanup: What Gets Skipped

A throw Skips Ahead

  • Code after a throw never runs
  • Local objects still destruct
  • Stack unwinding, automatic
✏️Open a file🚨throw happens here✅File still closes (RAII)

Check: What Still Runs?

A function opens a file, then throws before closing it manually. Does the file leak open?

Not if it is a proper RAII object (like ofstream): its destructor still runs during stack unwinding.

RAII vs. Manual Cleanup

📂Diagnostic session opened🚨throw before manual close()✅RAII destructor closes it

Word Origin: "Invariant"

  • Latin: invariant = unchanging
  • Hoare's 1969 loop invariant
  • Meyer's class invariant, 1986
A condition that must still holdtrue even after a throw, which isexactly what exception safety means

Source: Hoare, "An Axiomatic Basis for Computer Programming" (1969); Meyer, Eiffel Design by Contract (1986)

Questions?

Exception Safety & noexcept

Exception Safety Levels

No-Throw Guarantee readSensor() never throws, ever Strong Guarantee setMileage() succeeds, or state is unchanged Basic Guarantee Car stays valid, but one field is unspecified No Guarantee Avoid: a leaked lock, a half-written record

Check: Which Level Is Safest?

A no-throw function and a strong-guarantee function both look safe. Which is actually safer?

No-throw: it can never leave the caller handling an exception at all, the strongest promise there is.

Existing Software: MISRA C++

  • MISRA C++: real auto standard
  • Restricts exceptions in ECUs
  • Predictable timing matters
🚗Automotive ECU code📋MISRA C++ / AUTOSAR C++14⚠️Exceptions restricted, banned

Source: MISRA C++ / AUTOSAR C++14 guidelines

Word Origin: "Exception Safety"

  • Formalized by David Abrahams
  • Defines what survives a throw
  • Boost project, mid-1990s
Exception safety names how muchof a program's state survivesintact after a throw occurs

noexcept: Promise No Throw

  • Marks a function throw-free
  • Breaking it calls terminate
void readSensor() noexcept {
  // promise: this never throws
  return lastGoodValue();
}

Word Origin: "noexcept"

  • Added in C++11 (2011)
  • Proposal N3050
  • Replaces old throw() specs
noexcept promises a functionwill never let an exceptionescape; breaking it calls terminate

Check: What If noexcept Throws?

A function marked noexcept throws anyway, by mistake. What does the runtime do?

It calls std::terminate immediately: noexcept is a promise the compiler trusts without checking.

The Exception Class Hierarchy

std::exception logic_error runtime_error BadMileage BadVin SensorFault BrakeFailure A catch(std::exception&) matches every leaf below it

The Hierarchy in Code

  • Inherit from a std:: type
  • Call its constructor, too
class SensorFault
  : public std::runtime_error {
public:
  SensorFault()
    : runtime_error("Sensor fault") {}
};

Word Origin: "RAII"

  • Coined by Bjarne Stroustrup
  • Resource Acquisition Is Init.
  • Ctor acquires, dtor releases
RAII ties a resource's lifetimeto an object's own lifetime,so cleanup can never be skipped

Try, Throw, Catch: Step by Step

try { readSensor() } 🚨 Out of range throw SensorFault () ✈️ Stack unwinds 🛡️ catch (SensorFault&) Everything between throw and catch is skipped

Check: Where Does Control Jump?

The throw happens inside readSensor(), three calls deep. Where does execution go next?

Straight to the nearest enclosing catch that matches, skipping every line in between.

Stack Unwinding, Step by Step

BEFORE: call stack grows main() runDiagnostics() readSensor() throws AFTER: frames pop, dtors run main() catches it runDiagnostics() locals destruct, popped readSensor() already gone, popped first

Word Origin: "Stack Unwinding"

  • "Stack": a LIFO structure
  • "Unwinding": reversing it
  • Named in early C++ (ARM, 1990)
Unwinding pops each stack framein reverse order, running everylocal object's destructor

RAII: Cleanup on Exception

WITHOUT RAII: manual unlock lock.acquire() throw SensorFault() lock.release() // skipped! LOCK LEAKED WITH RAII: EngineLock guard EngineLock g(car); throw SensorFault() ~EngineLock() runs during unwinding, automatic LOCK RELEASED

EngineLock, an RAII Guard

  • Ctor locks, dtor unlocks
  • Runs even if a throw happens
class EngineLock {
  Car& car;
public:
  EngineLock(Car& c) : car(c) {
    car.lockForDiagnostics();
  }
  ~EngineLock() {
    car.unlock();
  }
};

Check: Does the Lock Ever Leak?

A diagnostic throws midway through, with an EngineLock guard already in scope. Does the lock leak?

No: ~EngineLock() still runs during stack unwinding, so the engine is always unlocked again.

Word Origin: "Guard"

  • From the "scope guard" idiom
  • Popularized by Boost, 2000s
  • An RAII object with one job
A guard object's only purposeis to run cleanup code whenit goes out of scope

Questions?

Practice Lab

Scenario: Validate Before Saving

  • A new record: make, mileage
  • Reject bad data before saving
  • Report exactly what went wrong
💾New car record entered🔍Validate mileage, make✅Save, or report the error

Step 1: Declare BadMileage

  • Inherits from std::exception
  • Message names the real problem
class BadMileage : public std::exception {
public:
  const char* what() const override {
    return "Mileage can't be negative";
  }
};

Step 2: Validate the Input

  • Check before accepting it
  • throw on the bad case
void setMileage(int m) {
  if (m < 0) throw BadMileage();
  mileage = m;
}

Step 3: Wrap the Call Site

  • try around the risky call
  • catch reports, doesn't crash
try {
  car.setMileage(-200);
} catch (BadMileage& e) {
  std::cout << e.what();
}

Check: Save Still Happens?

setMileage throws before the assignment runs. Does the car's mileage field change at all?

No: the throw happens on the line before the assignment, so mileage keeps its old, valid value.

Deliverable

  • A BadMileage exception class
  • setMileage() that validates
  • A try/catch that reports it
Mileage can't be negative

Step 4: Test Valid and Invalid

  • Call with a valid value
  • Call with an invalid one
try {
  car.setMileage(5000);  // valid
  car.setMileage(-50);   // invalid
} catch (BadMileage& e) {
  std::cout << e.what();
}

Check: What Prints for Valid Input?

setMileage(5000) runs first and succeeds. Does anything print for that call?

No: nothing throws, so the catch block never runs and that call prints nothing at all.

Questions?

Practice Lab Part 2

Scenario: Multiple Bad Fields

  • A record can fail two ways now
  • Bad mileage, or a bad VIN
  • One catch per failure type
📄Record: mileage + VIN🔍Two checks, two throws🛡️Two catches, one handler

Step 1: Declare BadVin

  • Second custom exception type
  • Same pattern as BadMileage
class BadVin : public std::exception {
public:
  const char* what() const override {
    return "VIN must be 17 characters";
  }
};

Step 2: Validate the VIN

  • Length check before accepting
void setVin(std::string v) {
  if (v.size() != 17) throw BadVin();
  vin = v;
}

Step 3: Catch Both Types

  • One try, two catch blocks
  • Each reports its own message
try {
  car.setMileage(-50);
  car.setVin("TOOSHORT");
} catch (BadMileage& e) { ... }
catch (BadVin& e) { ... }

Check: Which catch Runs First?

setMileage throws on the very first call in the try block. Does setVin's own check ever run?

No: the throw jumps straight to the matching catch, so every line after it inside the try is skipped.

Deliverable

  • A BadVin exception class
  • setVin() that checks length
  • Both catch blocks reachable
Mileage can't be negative

Step 4: Add a Third Field

  • Third field: fuel level
  • Same custom-exception shape
class BadFuelLevel : public
  std::exception {
public:
  const char* what() const
    override {
    return "Fuel level invalid";
  }
};

Check: How Many catch Blocks Now?

The try block can now throw BadMileage, BadVin, or BadFuelLevel. How many catch blocks does it need?

Three: one per exception type, each catching its own type by reference.

Step 5: Add a Fourth Field

  • Fourth field: brake pressure
  • Same custom-exception shape
class BrakeFailure : public
  std::exception {
public:
  const char* what() const
    override {
    return "Brake pressure low";
  }
};

Check: Catch-All for the Rest?

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

Basics Modules 1-2 Logic Modules 3-4 Structure Modules 5-7 Behavior Modules 8-11 🚗 🚗 🚗 🚗 Vehicle 2 variables + 1 function speed, fuel, drive()

Use Case: Fleet Health Check

  • Dealership checks 5 cars
  • Same drive() call each time
  • Bad data caught, not crashed
5 cars, one drive() check drive() 🚗 🚗 🚗 🚗 🚗 ❌ bad fuel caught everyone else drives through

The Vehicle Class

  • Two variables: speed, fuel
  • One function: drive()
  • Everything else calls it
class Vehicle fuel speed drive() turns the wheels

Step 1: Declare the Class

  • Two variables, nothing else
  • No function defined yet
class Vehicle {
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.

Step 2: Add drive() With a Check

  • if checks before driving
  • Updates both variables
void drive() {
  if (fuel <= 0) return;
  speed += 10;
  fuel -= 5;
}

Check: Which Module Taught if?

drive() checks fuel with an if before it does anything else. Which earlier module introduced if?

Module 3: Branches, so drive() is reusing one of the very first ideas this course taught.

Step 3: Guard With an Exception

  • Same shape as earlier classes
  • Names the real problem
class EmptyTank : public
  std::exception {
public:
  const char* what() const
    override {
    return "Tank is empty";
  }
};

Step 4: Throw It From drive()

  • throw, not a silent return
  • Caller finds out what failed
void drive() {
  if (fuel <= 0)
    throw EmptyTank();
  speed += 10;
  fuel -= 5;
}

Step 5: Call It in a Loop

  • for loop calls drive() 3 times
  • catch sits outside the loop
try {
  for (int i = 0; i < 3; i++) {
    car.drive();
  }
} catch (EmptyTank& e) {
  std::cout << e.what();
}

Check: Does the Loop Stop on Error?

The loop calls drive() three times and the second call throws. Does the third call still happen?

No: the throw exits the loop immediately and jumps to catch, so the third call never runs.

Step 6: A Fleet of Vehicles

  • One vector, many Vehicles
  • Same drive() for each car
std::vector<Vehicle> fleet(3);
for (auto& car : fleet) {
  car.fuel = 20;
  car.drive();
}

Check: Which Module Taught vector?

fleet holds several Vehicle objects under one name. Which earlier module introduced that idea?

Module 5: Arrays & Vectors, so fleet is really just many Vehicles stored under one name.

Check: Printing a Car's Speed?

To show car.speed on screen we'd write std::cout << car.speed. What module taught cout?

Module 9: Data Streams, which showed how cout sends a value out to the screen.

Check: A Truck That Inherits drive()?

Suppose class Truck : public Vehicle. Does Truck get drive() for free, with no new code?

Yes: Module 8's Inheritance means Truck already has every field and function Vehicle defined.

Check: Two Types, One Call?

fleet holds Cars and Trucks through Vehicle references, and each drive() behaves differently. What's that called?

Polymorphism (Module 10): the same call runs whichever drive() matches the real object's type.

Deliverable

  • A Vehicle class, two fields
  • One drive() function
  • An EmptyTank exception
  • A loop over a small fleet
Car 1: speed 10, fuel 15
Car 2: speed 10, fuel 15
Tank is empty

Coding Practice: One per Module

  • One prompt per module, 1-11
  • Full answer shown right away
  • A quick reference sheet

Practice 1 (Module 1): Print & Return

  • Print a greeting
  • Return 0 from main
#include <iostream>
int main() {
  std::cout << "Hi, Vehicle!";
  return 0;
}

Practice 2 (Module 2): Declare speed & fuel

  • Two int variables
  • fuel starts at 20
int speed = 0;
int fuel = 20;

Practice 3 (Module 3): Low Fuel Check

  • if/else on fuel
  • Print a status message
if (fuel < 10) {
  std::cout << "Low fuel";
} else {
  std::cout << "OK";
}

Practice 4 (Module 4): Loop drive() 3 Times

  • for loop, 3 times
  • Call drive() each time
for (int i = 0; i < 3; i++) {
  car.drive();
}

Practice 5 (Module 5): A Vector of Fuel Levels

  • One vector, 3 values
  • No loop needed
std::vector<int> fuelLevels =
  {20, 15, 10};

Practice 6 (Module 6): isLowFuel() Function

  • Returns true or false
  • Takes fuel as a parameter
bool isLowFuel(int fuel) {
  return fuel < 10;
}

Practice 7 (Module 7): The Vehicle Class

  • Two public variables
  • No function yet
class Vehicle {
public:
  int speed;
  int fuel;
};

Practice 8 (Module 8): Truck Inherits Vehicle

  • public inheritance
  • Reuses drive() for free
class Truck : public Vehicle {
};

Practice 9 (Module 9): Save to a File, Then Read It

  • Write, then read a file
  • #include <fstream>
#include <fstream>
std::ofstream out("log.txt");
out << "Drove 10 miles";
out.close();
std::ifstream in("log.txt");

Practice 10 (Module 10): A Virtual drive()

  • virtual keyword
  • Lets Truck override it
virtual void drive() {
  std::cout << "Vehicle driving";
}

Practice 11 (Module 11): try/catch Around drive()

  • try around the risky call
  • catch reports the error
try {
  car.drive();
} catch (EmptyTank& e) {
  std::cout << e.what();
}

One Vehicle, Every Module

Module 1Why the program exists
Module 2speed, fuel variables
Module 3The if check in drive()
Module 4The for loop calling drive()
Module 5vector<Vehicle> fleet
Module 6drive() itself, the one function
Module 7The Vehicle class
Module 8A Truck could inherit it
Module 9cout prints a car's data
Module 10drive() could run polymorphically
Module 11The EmptyTank exception

Questions?

Practice Quiz

Practice Quiz: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question.

throw
catch
try
Exception
An object signaling something went wrong
Marks a function as guaranteed not to throw
Tying resource cleanup to an object's lifetime
Related exception classes organized by inheritance
Destroying local objects while an exception propagates
Keyword that raises an exception
Block that handles an exception
Block where an exception might be thrown
noexcept
RAII
Exception Hierarchy
Stack Unwinding

Questions?

Word Origin: "Exception"

  • Latin "ex-": out
  • Latin "capere": to take
  • Together: "taken out"
An exception pulls error handling out of the normal, straight-line flow of code

Looking Ahead: Module 12

Module 12

Semester Review & Project

🧭
Review Every ModuleBuild One Real ProjectGridRunner: Drive & Survive

Meet GridRunner

Meet GridRunner

  • 20x20 grid, customizable size
  • Arrow keys drive the car
  • Start & dest: random

Download: gridrunner.cpp

C########D

How It Works

  • Shows the real functions
  • Click each step to reveal it
getConsoleSize() size the grid to your window Grid, Car, dest build objects: grid, car, destination _kbhit() / _getch() read a key, or wait for the next tick moveRandomCar() parallel cars roam on their own isWall() / checkWin() decide: crash, win, or keep driving

Check: Why Random Start/Destination?

If the car always started in the same corner, what would happen the second time you played?

The same route would work every time: randomizing both forces a new path each run.

Questions?

Setup: Visual Studio

What a C++ Program Needs

  • Source code: your .cpp file
  • Compiler: makes object code
  • Linker: builds the final .exe
GridRunner.cppCompilerLinker

Create the Project

  • Visual Studio does all 3 steps
  • One project holds every file
File > New > Project
Console App (C++)
Name: GridRunner

Create & Link the .cpp File

  • Add New Item adds a real file
  • Visual Studio links it for you
Project > Add New Item
C++ File (.cpp)
Name: GridRunner.cpp

Build & Run

  • Build compiles and links it
  • Start w/o Debugging runs it
Build > Build Solution
(Ctrl+Shift+B)

Debug > Start Without Debugging
(Ctrl+F5)

Command Line Alternative

  • The Developer Command Prompt
  • Same compiler, no IDE needed
cl /EHsc GridRunner.cpp
GridRunner.exe

Check: Why a Separate Compile & Link Step?

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"
Two objects meeting, unableto both occupy the same spot

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
}

Parallel Cars: Random Moves

  • Each car picks a random dir
  • Moves if it's not a wall
  • All tick on the same interval
void moveRandomCar(
    Car& c, const Grid& g) {
  // 72/80/75/77 = arrow key codes
  int dirs[4] = {72, 80, 75, 77};
  int pick = dirs[rand() % 4];
  // ...sets newRow / newCol
}

Parallel Cars: Move If Legal

  • Only moves onto open ground
  • isInBounds keeps it on grid
  • isWall blocks a crash
// move only if in-bounds
// and not a wall
if (g.isInBounds(newRow, newCol) &&
    !g.isWall(newRow, newCol)) {
  c.moveTo(newRow, newCol);
}

Timing the Run

  • A clock starts at kickoff
  • Elapsed seconds shown live
  • Shown again at game over
auto startTime =
  chrono::steady_clock::now();
// elapsed seconds, each loop:
int sec = (int)chrono::duration
  <double>(chrono::steady_clock
  ::now() - startTime).count();
cout << "Time: " << sec << "s";

Check: Why while, Not for?

A for loop needs a known number of passes up front. Does GridRunner know how many moves it will take?

No: the player decides, move by move, so while (unknown pass count) fits better than for.

Questions?

Arrays: Building the Grid

The Grid Is a 2D Vector

  • One row per vector<char>
  • Size comes from your window
  • Every cell starts as empty
int gridRows, gridCols;
getConsoleSize(gridCols, gridRows);
Grid grid(gridRows, gridCols);

Sizing to the Console

  • Reads real columns and rows
  • Falls back to 80x25 if needed
  • Caller clamps it to 5-50
bool getConsoleSize(
    int& cols, int& rows) {
  // read csbi via Win32 API
  cols = csbi.srWindow.Right -
    csbi.srWindow.Left + 1;
  rows = csbi.srWindow.Bottom -
    csbi.srWindow.Top + 1;
  return true;  // or 80x25 fallback
}

Printing the Grid

  • Nested loop: row, then column
  • One cout per row, then newline
void printGrid(const Grid& grid) {
  for (int r=0; r<grid.rows; r++) {
    for (int c=0; c<grid.cols; c++)
      cout << grid.cells[r][c];
    cout << "\n";
  }
}

Check: Why vector, Not a Plain Array?

SIZE is customizable at runtime. Can a plain C++ array be sized that way?

No: a plain array needs a fixed size at compile time; a vector can be sized at runtime.

Questions?

Functions: Organize Code

One Job per Function

  • Each function does one thing
  • main() calls them in order
bool isInBounds(int r, int c);
bool isWall(int r, int c);
void moveCar(char dir);
void printGrid();
bool checkWin();

Check: What Should randomCell() Return?

randomCell() needs to hand back both a row and a column. What should it return?

A pair (or two reference parameters): one int alone cannot hold both values at once.

Questions?

Classes: Car & Grid

Car row col moveTo(r, c) updates row and col together

The Car Class

class Car {
public:
  int row, col;
  void moveTo(int r, int c) {
    row = r; col = c;
  }
};
Grid # isWall(r, c) reads cells[r][c] isInBounds(r, c) checks limits

The Grid Class

class Grid {
public:
  int rows, cols;
  vector<vector<char>> cells;

  bool isWall(int r, int c) const;
  bool isInBounds(int r, int c) const;
};

Check: Why a Car Class Instead of 2 Ints?

carRow and carCol could just be two separate int variables. What does a class add?

It keeps them together as one unit, and lets you add methods like moveTo() right alongside the data.

Questions?

Inheritance: Obstacles

Obstacle: The Base Class

  • Every obstacle can be "hit"
  • onHit() is shared by all
class Obstacle {
public:
  virtual void onHit() {
    cout << "Hit!";
  }
};

Wall: A Derived Obstacle

  • public Obstacle reuses onHit()
  • override changes the behavior
class Wall : public Obstacle {
public:
  void onHit() override {
    cout << "Crashed into wall!";
  }
};

Check: Why Make onHit() virtual?

Without the virtual keyword, which version of onHit() would run for a Wall object?

The base Obstacle version always would: virtual is what lets a derived class override it.

Word Origin: "Obstacle"

  • Latin "ob-": in the way of
  • Latin "stare": to stand
  • Together: "stand in the way"
Anything that blocks the carfrom reaching the destination

Questions?

Streams: Saving a Maze

Loading a Custom Maze

  • ifstream opens maze.txt
  • Read one character per cell
  • Each row becomes one line
ifstream in("maze.txt");
for (int r=0; r<SIZE; r++)
  for (int c=0; c<SIZE; c++)
    // >> auto-skips newlines
    in >> grid[r][c];
in.close();

Check: What If maze.txt Is Missing?

The ifstream tries to open a file that does not exist. What should the program check before reading?

Whether the stream opened successfully, e.g. with is_open(), before trying to read from it.

Questions?

Polymorphism: Obstacles

One Vector, Many Obstacle Types

  • One vector, any Obstacle type
  • o->onHit() picks the real type
  • Decided at runtime, not build
vector<Obstacle*> obstacles;
obstacles.push_back(new Wall());
for (auto* o : obstacles) {
  o->onHit();
}

Check: What Happens Without override?

A Hazard class forgets to write override on its own onHit(). What message prints when it is hit?

The base Obstacle message, "Hit!": the Hazard never actually replaced the base behavior.

Questions?

Exceptions: Bad Input

A Custom Exception

  • A tiny or huge grid is invalid
  • BadGridSize explains why
class BadGridSize : public exception {
public:
  const char* what() const {
    return "Grid size must be 5-50";
  }
};

Throwing & Catching It

  • throw fires before it starts
  • catch reports it, safely
try {
  if (SIZE < 5 || SIZE > 50)
    throw BadGridSize();
} catch (BadGridSize& e) {
  cout << e.what();
}

Check: Why a Custom Exception Class?

Why write BadGridSize instead of just throwing a plain string or int?

Its what() message explains exactly what went wrong, which a plain value cannot do on its own.

Questions?

Putting It All Together

One Program, Every Concept

  • Classes hold the car and grid
  • Loops and branches drive it
  • Streams, exceptions: kept safe
class Car, class Gridvector&lt;Obstacle*&gt;while + switch + if/elsetry/catch at startup

main(): Everything Together

  • Same shape as every program
int main() {
  srand(time(0));
  Grid grid(20);
  Car car;
  placeRandom(car, grid);
  while (!gameOver) {
    printGrid(grid, car);
    handleInput(car, grid);
  }
}

Check: What Ties This Project Together?

This project uses classes, arrays, loops, branches, streams, and exceptions. What single idea connects them?

Every tool manages uncertainty safely: an unknown grid size, an unknown path, unknown player input.

Questions?

Practice Lab

Scenario: Build Your Own Grid

  • Pick your own grid size
  • Place a few walls by hand
  • Print a win message
Pick a Grid SizePlace Some WallsAdd a Win Message

Step 1: Pick Your Grid Size

  • Not 20: pick your own number
const int SIZE = 12;

Step 2: Place a Few Walls

  • Set a few cells to '#' by hand
grid[3][3] = '#';
grid[3][4] = '#';
grid[7][2] = '#';

Step 3: Add a Win Message

  • Print it once the car arrives
if (carRow==destRow &&
    carCol==destCol) {
  cout << "You arrived!";
  gameOver = true;
}

Check: What Did Your Grid Teach You?

After building your own grid size and walls, what part of GridRunner do you now understand best?

Answers vary: most students point to the collision check or the grid setup as the clearest piece.

Deliverable

  • Your own grid size
  • A few hand-placed walls
  • A working win message
You arrived!

Questions?

Practice Lab Part 2

Scenario: Make It Feel Real

  • Color the grid by tile type
  • Add a few special tiles
  • Let players try again
Color the TilesAdd Special TilesPlay It Again

Step 1: Color the Walls and Floor

  • A function sets text color
#.#.#walls red, floor green
setColor(RED);
cout << '#';
setColor(GREEN);
cout << '.';

Step 2: Color the Car and Goal

  • Car yellow, goal bright cyan
DCcar drives toward the goal
setColor(YELLOW);
cout << 'C';
setColor(CYAN);
cout << 'D';

Step 3: Add a Speed Tile

  • A tile marked 's' moves twice
sC's' tile: double move
if (grid[r][c]=='s') {
  move(dir);
  move(dir);
}

Step 4: Add a Tunnel Tile

  • Tile 't' hides the car
tCcar hides in the tunnel
if (grid[carRow][carCol]!='t')
  cout << 'C';
else
  cout << 't';

Step 5: Add a Pothole Obstacle

  • Tile 'p' skips your turn
pStuck!C'p' tile: skip a turn
if (grid[r][c]=='p') {
  stuck = true;
  cout << "Stuck!";
}

Step 6: Roads vs. Grass

  • Grass '.' blocks the car
  • Only roads 'o' are drivable
...CoooCgrass blocks the carroad lets the car through
if (grid[r][c]=='.') {
  cout << "Can't walk there!";
} else {
  carRow = r;
  carCol = c;
}

Step 7: Add a Crash Sound

  • Beep plays on a wall hit
#CBeep!wall hit: Beep!
if (grid[r][c]=='#') {
  Beep(200, 300);
  gameOver = true;
}

Step 8: Emoji Tiles (Optional)

  • Print an emoji instead of #
  • Needs UTF-8 console support
#🧱toggle: # or emoji
if (emojiMode)
  cout << wallEmoji;
else
  cout << '#';

Step 9: Make Roads Look Like a City

  • Every 4th row/col is a road
  • Walls line the whole border
Cgrid walled on every side
if (r==0 || r==rows-1 ||
    c==0 || c==cols-1) {
  grid[r][c] = '#';
} else if (r % 4==0 ||
           c % 4==0) {
  grid[r][c] = 'o';
}

Step 10: Add Weather Fog

  • Fog hides tiles far from car
Cfar tiles are just blank
int dr = abs(r - carRow);
int dc = abs(c - carCol);
if (max(dr, dc) > radius)
  cout << "  ";
else
  cout << grid[r][c];

Step 11: Try Again

  • A loop lets you play again
GAME OVERPlay again? (y/n)loops back to the start
char again;
do {
  playGame();
  cout << "Play again? (y/n) ";
  cin >> again;
} while (again=='y');

Check: Which Addition Surprised You?

After adding color, special tiles, and a try-again loop, which change felt like the biggest upgrade to the game?

Answers vary: color and the try-again loop are the two most often picked as "feels like a real game" moments.

Deliverable

  • Colored walls, floor, car
  • At least one special tile
  • A working try-again loop
Play again? (y/n)

Questions?

Module 13

Semester Review

📚
M1-6 M7-9 M9, 11 One Program Every module, tied together.

Variables & Types

Variables & Types

  • bool, int, double, string
  • Declare, initialize, reassign
  • A variable's type is fixed
M1-2

Check: bool vs. int for a Flag

A variable tracks whether a car sold: true or false only. Which type fits, bool or int?

bool: it only ever holds two states, and the name itself documents that it is a yes/no flag.

Conditionals & Loops

Conditionals & Loops

  • if / else if / else, switch
  • for: a known number of passes
  • while / do-while: on condition
M3-4

Check: for vs. while

Printing every car in a 10-element array needs exactly 10 passes. Which loop fits best, for or while?

for: the pass count is known up front, which is exactly what a for loop's own structure is built around.

Arrays, Vectors & Functions

Arrays, Vectors & Functions

  • Arrays: fixed size, 0-indexed
  • Vectors: grow with push_back()
  • Functions: params, return
M5-6

Check: Array or Vector?

The number of cars on the lot changes daily as some sell and new ones arrive. Array or vector fits better?

A vector: its size can grow or shrink at runtime, unlike a fixed-size array set once at declaration.

Objects, Inheritance & Polymorphism

Objects, Inheritance & Polymorphism

  • Classes bundle data, behavior
  • Inheritance: a class extends
  • Polymorphism: one call, many
M7-9

Check: Virtual or Not?

A base class pointer calls describe(), expecting each derived car type to print its own message. What keyword is required?

virtual, on the base class's describe(): without it, the base version always runs instead of the derived one.

Streams & Exceptions

Streams & Exceptions

  • ofstream/ifstream: file I/O
  • throw/try/catch: errors
  • Open, read, catch failures
M9, 11

Check: Reading an Empty File

ifstream opens a file that doesn't exist. What does the stream object evaluate to in a boolean context?

false: a failed open sets the fail bit, so checking the stream directly is the simplest way to detect it.

Putting It All Together

One Program, Every Concept

  • A Car class, with a describe()
  • A vector of Car pointers
  • Loop, print, catch a bad input
🚗class Car: fields + describe()📊vector<Car*> inventory🔄for loop, polymorphic calls✅try/catch around validation

A Familiar Shape

  • Same loop since Module 4
  • Now calling a virtual function
for (auto* c : inventory) {
  std::cout << c->describe();
}

Check: Why a Vector of Pointers?

inventory holds Car*, not plain Car objects. Why pointers, specifically for polymorphism to work here?

A plain Car object would slice away any derived class's extra data; a pointer keeps the real derived type.

Practice Lab

Scenario: The Final Inventory Report

  • A vector of Car/Truck pointers
  • Print each one polymorphically
  • Catch a bad mileage, safely
📊Build the inventory vector🔄Loop, call describe() on each✅Report the total value, safely

Step 1: Build the Inventory

  • Mix of Car and Truck pointers
std::vector<Car*> inventory;
inventory.push_back(new Car("Civic"));
inventory.push_back(new Truck("F-150"));

Step 2: Loop and Describe

  • Each call is polymorphic
for (auto* c : inventory) {
  std::cout << c->describe() << "\\n";
}

Step 3: Validate Safely

  • Bad mileage throws, is caught
try {
  c->setMileage(-50);
} catch (std::exception& e) {
  std::cout << e.what();
}

Check: What Ties These Together?

This lab uses a class hierarchy, a vector, a loop, and exception handling. What single idea connects all four?

Each tool manages uncertainty or variety safely: different types, a growing collection, repetition, and bad input.

Deliverable

  • Mixed Car/Truck pointer vector
  • Polymorphic describe(), each
  • A caught, reported bad mileage
Mileage can't be negative

Questions?

Practice Quiz

All Module Quizzes

Drag-and-drop match-the-term quizzes, one per module.

  1. Module 1: Course Overview
  2. Module 2: Variables & I/O
  3. Module 3: Branches
  4. Module 4: Loops
  5. Module 5: Arrays & Vectors
  6. Module 6: Functions
  7. Module 7: Objects & Classes
  8. Module 8: Inheritance
  9. Module 9: Data Streams
  10. Module 11: Exceptions
  11. All Modules (Final Review)

Questions?

Looking Ahead: Module 14

Module 14

Finals Preparation

📝
📚 Review the modules ✏️ Solve practice problems ✅ Walk into the final ready

What's on the Final

What's on the Final

  • Cumulative: Modules 1-11
  • Variables through exceptions
  • Same style as lab/HW questions
📚Core syntax: types, loops, functions🚗OOP: classes, inheritance, polymorphism✅Streams and exceptions

Check: Are Modules 12-13 on the Final?

Modules 12 and 13 were themselves review and project work, with no new syntax of their own. Do they add exam material?

No: they only reorganized, practiced, and applied existing content, so exam scope is still just Modules 1-11.

Study Checklist

Can You Still Do These?

  • Trace a nested loop by hand
  • Write a class, constructor
  • Explain virtual vs. plain
  • Explain throw and catch
✅Confident: move on❓Shaky: re-read that module🚨Stuck: ask before the exam

Check: Best Use of Limited Study Time

There is only a little time left before the final. Where should it go: re-reading slides, or solving practice problems?

Practice problems: they surface what you can't actually do yet, which re-reading alone tends to hide.

Mixed Practice Review

Trace This Loop

  • What does this print, and why?
for (int i = 0; i < 3; i++) {
  std::cout << i * 2 << " ";
}

Answer: Trace This Loop

Walk through i = 0, 1, 2, printing i * 2 each time.

Prints: 0 2 4, each separated by a space.

Spot the Bug

  • This class won't compile. Why?
class Car {
public:
  void describe() { ... }
  Car(std::string m) { make = m; }
private:
  std::string make;
};

Answer: Spot the Bug

Look closely at the order of the member sections.

Nothing is actually wrong: a constructor can be declared anywhere in the public section, order doesn't matter.

Trace This Exception

int x = -5; if (x < 0) throw std::runtime_error("bad"); std::cout << "ok"; What happens?

Nothing prints: throw fires before cout runs, and with no catch, the program terminates.

Exam Logistics

When & Where

  • Final Exam Period: Dec 7-11
  • Exact day/time: TBD, Canvas
  • Check the syllabus for updates
📅Final Exam Period: Dec 7-11🖥️Exact slot posted on Canvas✅Confirm before exam week

Academic Integrity

  • Same policy as every lab/HW
  • AI use disclosed, per part
  • Must be your own understanding

The syllabus policy you confirmed in Lab 1 still applies on the final: AI is fine to use, but state clearly what parts used it.

Questions?

Looking Ahead: Module 15

Module 15

Final Review

✅
Round 1: Core Syntax Round 2: Objects & OOP Round 3: Streams & Exceptions

Round 1: Core Syntax

Q1: Types

What type fits a car's mileage, a whole number that can be large?

int (or long if it could exceed about 2 billion).

Q2: Loop Choice

Printing a vector until a sentinel value -1 is found, with an unknown length. Which loop fits best?

while: the number of passes isn't known ahead of time, which is exactly what while is built for.

Q3: Switch Fallthrough

A switch statement is missing a break in one case. What actually happens?

Execution falls through into the next case's code, running it too, until a break or the switch ends.

Q4: Function Scope

A variable declared inside a function body is used outside that function. Does it compile?

No: that variable's scope ends with the function's closing brace, it does not exist outside it.

Round 2: Objects & OOP

Q5: Constructors

A class has no constructor written at all. Does the class still work?

Yes: the compiler generates a default constructor automatically when none is written.

Q6: Inheritance Access

A base class member is marked private. Can a derived class access it directly?

No: private members are never accessible to a derived class; protected would allow that instead.

Q7: Virtual Functions

A base class pointer calls a non-virtual function that's overridden in the derived class. Which version runs?

The base class's own version runs: without virtual, the call is resolved by the pointer's type, not the object's.

Q8: Abstract Classes

A class has one pure virtual function (= 0). Can you create an object of that class directly?

No: a class with any pure virtual function is abstract, and abstract classes can never be instantiated.

Round 3: Streams & Exceptions

Q9: File Streams

ofstream out("data.txt") opens a file that already has content. What happens to the old content?

It is overwritten by default: ofstream truncates an existing file unless opened in append mode.

Q10: Exception Types

A function throws std::out_of_range. Will a catch block written for std::exception& catch it?

Yes: out_of_range inherits from std::exception, so a base-class reference catches it too.

Q11: Multiple Catch Blocks

A try block can throw either std::out_of_range or std::invalid_argument. How many catch blocks handle both separately?

Two: one catch per exception type, each written separately, most specific first.

Q12: Reading Until EOF

while (inFile >> value) loops until what condition becomes true?

Until the stream read fails (end of file or bad data), which makes the extraction operator return false.

Final Tips

Before You Start

  • Read every question first
  • Trace code by hand, no guess
  • Answer the sure ones first
📄Read the whole exam first✅Answer the sure ones first🔄Come back to the hard ones

Questions?

Practice Lab

Practice Lab: Match the Term

Drag an answer from the outside onto the question it matches — one answer per question, one from each module.

Program
Compiler
bool
cin
if/else
&&
for
do-while
A set of instructions a computer executes
Position of a value inside an array
Logical AND operator
Loop that always runs at least once
Reads input from the keyboard
Blueprint for creating objects
Turns C++ source into machine code
Runs code based on a condition
Fixed-size list of same-type values
Type that stores true or false
Named block of reusable code
A class reuses another class's members
Object used to read from a file
Keyword enabling override through a base pointer
Loop with a built-in counter
Keyword that raises an exception
Array
Index
Function
Class
Inheritance
ifstream
Virtual
throw

Questions?

Looking Ahead: Module 16

Module 16

Final Exam

🎓
📅 Thu, Dec. 10, 3–5 PM 📍 Baun 214 ✅ 20 questions, every module

Exam Day Logistics

When & Where

  • Thu, Dec. 10, 3–5 PM
  • Location: Baun 214
  • Duration: 1 hour 20 minutes
📅Thursday, Dec. 10, 3-5 PM📍Baun 214⏳1 hour 20 minutes to complete

What to Bring

  • Paper exam, closed book
  • Pens only, no pencils
  • One double-sided summary sheet

The summary sheet is the one reference allowed during the exam itself: no laptops, phones, or separate notes.

Exam Format

Exam Format

  • 20 total questions
  • 18 multiple choice, 2 written
  • Each module contributes 1-2
📋18 multiple choice✎️2 written questions📚Every module represented

How to Prepare

Where to Study

  • Midterm: ~50% of the final
  • Review slides, labs, Runestone
  • Review the GitHub project too
📝Midterm questions, reused ideas📖Slides, labs, Runestone HW💻The GitHub project

Four practice sets, drawn from across the whole semester, closest in style to what the real exam will ask.

Good luck on the final!

C++, Compiler, Linker, Variables, Declare, Initialize, Reassign, Type, Data Types, bool, int, char, string, double, float, Constants, Operators, Assignments, Expressions, Conditionals, Branches, If/Else, Switch, Boolean, Loops, For, While, Do-While, Iteration, Nested Loop, Arrays, Vectors, Strings, Functions, Parameters, Return Values, Scope, Objects, Classes, Encapsulation, Constructors, Destructors, Inheritance, Polymorphism, Virtual Functions, Streams, cin, cout, File I/O, Pointers, References, Dynamic Memory, Exceptions, Try/Catch, Error Handling, Header Files, Namespaces, Standard Library, Templates, STL, Iterators, Containers, Algorithm Library, Sorting, Searching, Compilation Process, Debugging, Testing, Code Reuse, Modularization, Maintainability.

Labs & Homework

  1. Lab 1 & HW 1: Getting Started
  2. HW 2 & Lab 2: Branches
  3. HW 3 & Lab 3: Branches & Loops
  4. HW 4 & Lab 4: Arrays & Funcs
  5. HW 5 & Lab 5: Classes/Inherit
  6. HW 6 & Lab 6: Poly & Streams
  7. HW 7 & Lab 7: Except/Project
  8. Midterm: Modules 1-6
  9. Sample Final: Modules 1-9, 11

Midterm

Midterm: Modules 1-6

  • Date: Oct 15
  • 20 questions, 5 pts each
  • 18 MC, 2 written questions
  • On paper: bring a pen
  • Closed book, 1 note page OK
  • Modules 1-6, ~3 Qs each
  • Full class: 3:00-4:45

Q1

What is C++?

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

void countdown(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.

Answer

void trafficLight(string color) {
  if (color == "green") {
    cout << "Drive";
  } else if (color == "red") {
    cout << "Stop";
  }
}

Sample Final

Sample Final: Modules 1-9, 11

  • 20 questions, 5 pts each
  • 18 MC, 2 written questions
  • On paper: bring a pen
  • Closed book, 1 note page OK
  • 10 modules, 2 Qs each
  • Vehicle examples throughout

Practice Materials

General Rules

  • Closed book exam
  • One double-sided summary sheet
  • Pens only, no pencils
  • No laptops or phones
  • Same academic integrity as every lab/HW
  • AI used only to study, not during the exam

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.

Homework 1

Homework 1: Evolution of C++

  • Part 1: confirm syllabus read
  • Part 2: read C++ paper, 10 Qs

Reading: Bjarne Stroustrup, The Evolution of C++: 1985 to 1989 (first four pages)

Question

  • Why the name C++?
  • Who is Stroustrup?
  • Why 1985?

Answer

"++" 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.

Covered throughout the course

Homework 2

Homework 2: Branches

  • Answer in complete sentences

Reading: Think C++, Chapter 4

  • Complete Runestone Labs 4.0–4.5
  • Post questions here, or
  • just type "Completed."

Reading: Think C++, Chapter 4 (Runestone Academy)

Question

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!";

Run it: OnlineGDB C++ Compiler

Question: 25 pts

  • Rebuild Q1 using switch/case
  • 1=Rain 2=Cold 3=Hot 4=Other

Answer

int w;
cin >> w;
switch (w) {
  case 1: cout << "Take umbrella."; break;
  case 2: cout << "Wear jacket."; break;
  case 3: cout << "Bring water."; break;
  default: cout << "Good to go!";
}

Run it: OnlineGDB C++ Compiler

Question: 25 pts

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 check
if (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.

Run it: OnlineGDB C++ Compiler

Question: 25 pts

Ask for 5 numbers. If a number is negative, print "Skipped". Otherwise add it to a total. Print the final total.

Run it: OnlineGDB C++ Compiler

Question: 25 pts

Keep asking for a number 1–10 until a valid one is entered. Then print "Valid number entered!"

Run it: OnlineGDB C++ Compiler

Homework 4

Homework 4: Arrays & Functions

  • 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'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.

Run it: OnlineGDB C++ Compiler

Question 2: 10 pts

Declare a vector of car makes (string). Use push_back to add 3 cars.

Run it: OnlineGDB C++ Compiler

Question 3: 10 pts

Write sumPrices(arr, size) that returns the total of an array.

Run it: OnlineGDB C++ Compiler

Question 4: 10 pts

Write findMax(arr, size) that returns the highest mileage.

Run it: OnlineGDB C++ Compiler

Question 5: 10 pts

Write countCars(vector<string>& names) that returns its size.

Run it: OnlineGDB C++ Compiler

Question 6: 10 pts

Write isOverBudget(double price, double limit) returning bool.

Run it: OnlineGDB C++ Compiler

Question 7: 10 pts

Loop a vector of prices. Print "Affordable" or "Too Expensive".

Run it: OnlineGDB C++ Compiler

Question 8: 10 pts

Write average(arr, size) that returns the mean as a double.

Run it: OnlineGDB C++ Compiler

Question 9: 10 pts

Use pop_back() to remove the last car from a vector. Print new size.

Run it: OnlineGDB C++ Compiler

Question 10: 10 pts

Write printPairs(names, prices) that prints each make with its price.

Run it: OnlineGDB C++ Compiler

Homework 5

Homework 5: Classes & Inheritance

  • 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.

Resources

Reading: Think C++, Chapter 11 (Runestone Academy)

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.

Question 1: 10 pts

Declare a Car class: private make, model, price.

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 2: 10 pts

Write a Car constructor that sets all three fields.

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 3: 10 pts

Write a public getPrice() getter for Car.

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 4: 10 pts

Write setPrice() that rejects a negative price silently.

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 5: 10 pts

Create Truck : public Car, adding a towCapacity field.

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 6: 10 pts

Write a Truck constructor that calls the Car constructor.

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 7: 10 pts

Write describe() in Car; override it in Truck.

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 8: 10 pts

Make an array of 3 Car objects; print each with describe().

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 9: 10 pts

Add a Car destructor that prints "Car sold".

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Question 10: 10 pts

Write printPrice(Car& c) that prints c.getPrice().

Deliver: screenshot of your code and its output.

Run it: OnlineGDB C++ Compiler

Homework 6

Homework 6: Polymorphism & Streams

  • 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'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.

Question 1: 10 pts

Add a virtual describe() to a base Vehicle class.

Run it: OnlineGDB C++ Compiler

Question 2: 10 pts

Make Car and Truck inherit from Vehicle (Lab 5's classes).

Run it: OnlineGDB C++ Compiler

Question 3: 10 pts

Make an array of Vehicle* pointing to Car and Truck objects.

Run it: OnlineGDB C++ Compiler

Question 4: 10 pts

Loop the array, call describe() on each polymorphically.

Run it: OnlineGDB C++ Compiler

Question 5: 10 pts

Make Vehicle abstract: add a pure virtual maintenance().

Run it: OnlineGDB C++ Compiler

Question 6: 10 pts

Write a function that writes a Car's data with ofstream.

Run it: OnlineGDB C++ Compiler

Question 7: 10 pts

Write a function that reads a Car's data back with ifstream.

Run it: OnlineGDB C++ Compiler

Question 8: 10 pts

Use setprecision(2) to print a price with two decimals.

Run it: OnlineGDB C++ Compiler

Question 9: 10 pts

Parse "Honda 23000" with stringstream into make, mileage.

Run it: OnlineGDB C++ Compiler

Question 10: 10 pts

Use getline() to read one full vehicle record from a file.

Run it: OnlineGDB C++ Compiler

Homework 7

Homework 7: Exceptions & Semester Project

  • 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'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.

Run it: OnlineGDB C++ Compiler

Question 2: 10 pts

Write setPrice() that throws BadPrice on a negative value.

Run it: OnlineGDB C++ Compiler

Question 3: 10 pts

Wrap a setPrice() call in a try/catch for BadPrice.

Run it: OnlineGDB C++ Compiler

Question 4: 10 pts

Write isInBounds(row, col, size), returning a bool.

Run it: OnlineGDB C++ Compiler

Question 5: 10 pts

Write randomCell(size), returning a random row/col pair.

Run it: OnlineGDB C++ Compiler

Question 6: 10 pts

Write printGrid(vector<vector<char>>& grid) to display it.

Run it: OnlineGDB C++ Compiler

Question 7: 10 pts

Trace by hand: what happens if the car moves off the grid edge?

Run it: OnlineGDB C++ Compiler

Question 8: 10 pts

Write moveCar(int& row, int& col, char dir), updating position.

Run it: OnlineGDB C++ Compiler

Question 9: 10 pts

Add catch(...) as a fallback after a specific catch block.

Run it: OnlineGDB C++ Compiler

Question 10: 10 pts

Write checkWin(carRow, carCol, destRow, destCol), returning a bool.

Run it: OnlineGDB C++ Compiler

Final Project

Final Project: GridRunner

  • Arrays, classes, inheritance
  • Polymorphism, streams, errors
  • A full working reference build
  • Your job: extend it, your way

Minimum Requirements

  • Add a new Obstacle subtype
  • A grid size other than 20x20
  • A move counter on screen
  • A short README of your own

How the Game Works

Set Up the GridPlace Car & DestinationRead an Arrow KeyCheck for a WallWin or Crash

⚠️ Hit any wall or the grid edge and the run ends immediately: there is no bounce-back.

The Grid, Up Close

  • C: the car's current cell
  • D: the destination cell
  • #: a wall; . is open ground
C########D

Controls: Arrow Keys

  • Up/Down change the row
  • Left/Right change the column
  • One keypress, one cell moved
🚗↑row - 1↓row + 1←col - 1→col + 1

Setting Up in Visual Studio

  • File &gt; New &gt; Project
  • Console App (C++)
File > New > Project
Console App (C++)
Name: GridRunner

Create & Link the .cpp File

  • Add New Item adds a real file
  • Visual Studio links it for you
Project > Add New Item
C++ File (.cpp)
Name: GridRunner.cpp

Build & Run

  • Build compiles and links it
  • Start w/o Debugging runs it
Build > Build Solution
(Ctrl+Shift+B)

Debug > Start Without Debugging
(Ctrl+F5)

Command Line Alternative

  • The Developer Command Prompt
  • Same compiler, no IDE needed
cl /EHsc GridRunner.cpp
GridRunner.exe

Base Class: Obstacle

  • Shared onHit() behavior
  • virtual lets a child override
class Obstacle {
public:
  virtual void onHit() {
    cout << "Hit!";
  }
};

Inheritance: Wall

  • public Obstacle reuses onHit()
  • override marks the intent
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.