Pacific Seal

Welcome
Introduction to Computer Science


Image 1 Image 2 Image 3 Image 4 Image 5 Image 6
Week Meeting Dates (TR) Topic Notes Assignments
Week 1 Aug 26, Aug 28 Course Overview, What is a Program?, First C++ Program
Week 2 Sep 2, Sep 4 Variables and Basic I/O Sep 1 is Labor Day – no Monday classes Lab/H2 #1
Week 3 Sep 9, Sep 11 Branches
Week 4 Sep 16, Sep 18 Loops Lab/H2 #2
Week 5 Sep 23, Sep 25 Array/Vectors
Week 6 Sep 30, Oct 2 User Defined Functions Oct 3 is Fall Student Break Lab/H2 #3
Week 7 Oct 7, Oct 9 Objects and Classes
Week 8 Oct 14, Oct 16 Classes and Inheritance Midterm Exam: Oct. 16th, Lab/HW2 #4
Week 9 Oct 21, Oct 23 Classes and Inheritance
Week 10 Oct 28, Oct 30 Data Streams Lab/H2 #5
Week 11 Nov 4, Nov 6 Exceptions
Week 12 Nov 11, Nov 13 Recursion and Module Review Lab/H2 #6
Week 13 Nov 18, Nov 20 Module Review
Week 14 Nov 25
Nov 27 (Thanksgiving)
Finals Preparation No class Nov 27 Lab/H2 #7 (due Nov 25)
Week 15 Dec 2, Dec 4 Final Review, Student Demos, Course Wrap-up Final project presentations or quiz
Week 16 Dec 9 Final Exam Period Final Exam: Dec. 9th at 3PM in Baun 214

Before Operating Systems

  • 1940s–1950s: Computers programmed with switches, punch cards, or raw machine code.
  • Each program controlled the whole machine: no sharing, no multitasking.
  • Programmers had to include code to handle devices and stop/start jobs 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

  • 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

C Code


int add(int a, int b) {
    return a + b;
}
  

Assembly


add:
    mov eax, edi    ; move a into eax
    add eax, esi    ; add b (esi) to eax
    ret             ; return result
  

x86-64 System V calling convention

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

How C Becomes Machine Code

C Code
int add(int a, int b)
Compiler
(gcc, clang, etc.)
Assembly Code
mov eax, edi
Assembler
(part of toolchain)
Machine Code
55 89 f8 01 f0 5d c3

Source: Visualized compilation process from C to machine code

Start Engine (C Code)


#include <stdio.h>

// Simulated function to start engine
void start_engine() {
    printf("Connecting to engine...\n");
    // Simulate hardware I/O or network call
    printf("Engine started successfully!\n");
}

int main() {
    start_engine();
    return 0;
}

History of C++

  • 1980s: Bjarne Stroustrup
  • “C with Classes” → C++
(add: Stroustrup / early C++)
C++ Image
(add: OOP diagram)

Why C++?

  • Object‑oriented programming
  • Performance with abstraction

Basic I/O

#include <iostream>
int main(){
  int age; 
  std::cout << "Age? ";
  std::cin >> age;
  std::cout << "You are " << age << "\n";
}

Variables

int count = 5; 
double pi = 3.14159; 
char grade = 'A'; 
std::string name = "Alice";

Expressions

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

Decisions

if (score >= 90) {
  std::cout << "Excellent!";
} else {
  std::cout << "Keep going!";
}

Loops: for

for (int i = 1; i <= 5; ++i) {
  std::cout << i << " ";
}

Loops: while

int n = 5;
while (n > 0) {
  std::cout << n-- << " ";
}

Functions

int square(int x){ return x * x; }
int main(){ std::cout << square(5); }

Arrays

int nums[3] = {10, 20, 30};
for (int i = 0; i < 3; ++i)
  std::cout << nums[i] << " ";

Strings

#include <string>
std::string s = "Pacific";
std::cout << s.size();
std::cout << s[0];

Classes (C++)

class Student {
public:
  std::string name; int id;
};
Student s; s.name = "Bob"; s.id = 102;

How This Course Runs

  • Weekly labs + practice
  • Concept → code → feedback
  • Ask questions early & often

Today, Thursday Aug 28th

  1. Develop C++ Caclulator
  2. Develop C++ Game
  3. Introduction to zyBook
  4. Homework 1 and Lab 1

Develop C++ Caclulator


#include <iostream>
using namespace std;

int main() {
    double a, b;
    char op;

    // TODO: read a, op, b
    // TODO: compute and print result

    return 0;
}

cout << "Enter expression (e.g., 5 * 2): ";
cin >> a >> op >> b;

switch (op) {
    case '+': cout << (a + b) << "\n"; break;
    case '-': cout << (a - b) << "\n"; break;
    case '*': cout << (a * b) << "\n"; break;
    case '/':
        if (b == 0) cout << "Error: division by zero\n";
        else cout << (a / b) << "\n";
        break;
    default:
        cout << "Unknown operator\n";
}

#include <iostream>
using namespace std;

int main() {
    double a, b;
    char op;

    cout << "Enter expression (e.g., 5 * 2): ";
    if (!(cin >> a >> op >> b)) {
        cout << "Input error\n";
        return 0;
    }

    switch (op) {
        case '+': cout << (a + b) << "\n"; break;
        case '-': cout << (a - b) << "\n"; break;
        case '*': cout << (a * b) << "\n"; break;
        case '/':
            if (b == 0) cout << "Error: division by zero\n";
            else cout << (a / b) << "\n";
            break;
        default:
            cout << "Unknown operator\n";
    }

    return 0;
}

Questions?

Today, Thursday Aug 28th

  1. Develop C++ Caclulator ✓
  2. Develop C++ Game
  3. Introduction to zyBook
  4. Homework 1 and Lab 1
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
    srand(time(0));
    int player, computer;
    cout << "Enter 0=Rock, 1=Paper, 2=Scissors: ";
    cin >> player;
    computer = rand() % 3;
cout << "Computer chose: " << computer << endl;
if(player == computer) cout << "Draw!\n";
else if((player==0 && computer==2) ||
        (player==1 && computer==0) ||
        (player==2 && computer==1))
    cout << "Player wins!\n";
else
    cout << "Computer wins!\n";
return 0;
// Optional: map numbers to names
string choices[] = {"Rock", "Paper", "Scissors"};
cout << "Player chose: " << choices[player] << ", Computer chose: " << choices[computer] << endl;
// Full program copy/paste
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));
    int player, computer;
    string choices[] = {"Rock", "Paper", "Scissors"};

    cout << "Enter 0=Rock, 1=Paper, 2=Scissors: ";
    cin >> player;
    computer = rand() % 3;

    cout << "Player chose: " << choices[player] << ", Computer chose: " << choices[computer] << endl;

    if(player == computer) cout << "Draw!\n";
    else if((player==0 && computer==2) ||
            (player==1 && computer==0) ||
            (player==2 && computer==1))
        cout << "Player wins!\n";
    else
        cout << "Computer wins!\n";

    return 0;
}
// Optional: loop for multiple rounds
for(int i=0;i<3;i++) {
    // repeat input, generate computer move, decide winner
}
// Optional: add input validation
if(player <0 || player >2) cout << "Invalid choice!\n";

Questions?

Today, Tuesday Nov. 18th

  1. Introduction to Variables
  2. Variable Declaration
  3. Variable Initialization
  4. Assignment
  5. Reassignment
  6. Hands-On Practice
  7. Variable Memory Size
  8. Constants, Casting, etc.
  9. Basic Input Output (I/O)
  10. Homework 1 and Lab 1
Agenda Image

Introduction to Variables

  • Variables store data in memory
  • Each variable has a type and a name
  • Used to hold values for processing

int age = 18;
float price = 19.99;
double pi = 3.14159;
char grade = 'A';
bool passed = true;
string name = "Alice";
            

Quiz: Introduction

  • A) Variables store data in memory
  • B) Variables are constants
  • C) Variables are functions
  • D) Variables are keywords

int score = 90;
cout << "Score: " << score;
            

Common Data Types

  • int → whole numbers
  • float, double → decimals
  • char → single characters
  • bool → true/false
  • string → text

int students = 25;
float height = 5.9f;
double salary = 50000.75;
char initial = 'B';
bool isActive = false;
string city = "Stockton";
            

Quiz: Data Types

  • A) int number = 10;
  • B) float 2price = 19.99;
  • C) char = 'A';
  • D) bool = true;

// Correct variable
int number = 10;
cout << "Number: " << number;
            

Key Takeaways

  • Variables must be declared before use
  • Each has a type and name
  • Used to store and process data

string name = "John";
cout << "Hello, " << name;
            

Variable Declaration

  • Declare variables without assign value
  • Syntax: type name;
  • Example: int, float, char, bool, string

int count;
float temperature;
double distance;
char letter;
bool isReady;
string message;
            

Quiz: Declaration

  • A) int x;
  • B) float 2price;
  • C) char initial;
  • D) bool done;

// Valid declaration
float temp;
temp = 36.5f;
cout << "Temperature: " << temp;
            

Multiple Declarations

  • Declare multiple variables, same type
  • Syntax: int a, b, c;
  • Assign values later if needed

int x, y, z;
x = 5;
y = 10;
z = 15;
cout << x + y + z;
            

Quiz: Multiple Declaration

  • A) int a, b, c;
  • B) float 2x, y, z;
  • C) char = 'A';
  • D) bool flag;

// Valid multiple declaration
int a, b, c;
a = 1; b = 2; c = 3;
cout << a + b + c;
            

Key Takeaways

  • Declare variables before use
  • Can declare multiple variables at once
  • Assign values later

int score, level;
score = 10;
level = 1;
cout << "Score: " << score << ", Level: " << level;
            

Variable Initialization

  • Assign value to variable when declared
  • Simplify code + avoids garbage values
  • Works with all basic data types

int age = 20;
float height = 5.8f;
double pi = 3.14159;
char grade = 'B';
bool isPassed = true;
string name = "Bob";
            

Quiz: Initialization

  • A) int x;
  • B) float y = 9.5;
  • C) char;
  • D) bool flag;

// Correct initialization
float y = 9.5;
cout << "Value: " << y;
            

Initialization Tips

  • Initialize variables at declaration time
  • Avoids undefined behavior
  • ✓ int, float, double, char, bool, string

int count = 10;
double distance = 12.5;
char initial = 'C';
bool done = false;
string city = "LA";
            

Quiz: Tips

  • A) int x;
  • B) double distance = 12.5;
  • C) char;
  • D) bool;

// Correct example
double distance = 12.5;
cout << "Distance: " << distance;
            

Key Takeaways

  • Initialize variables, no garbage values
  • Simplifies code and debugging
  • Applicable to all basic types

int age = 25;
float price = 19.99;
string name = "Alice";
cout << "Age: " << age << ", Price: " << price;
            

Assignment

  • Assign a value to an existing variable
  • Can happen anytime after declaration
  • Works with all types: int, float, double, char, bool, string

int score;
score = 95;
float temp;
temp = 36.6f;
char grade;
grade = 'A';
bool passed;
passed = true;
string name;
name = "Bob";
            

Quiz: Assignment

  • A) int x = 5;
  • B) int x; x = 5;
  • C) float y;
  • D) char c;

// Assignment example
int x;
x = 5;
cout << "X: " << x;
            

Multiple Assignments

  • Assign values to variables separately
  • Keep code readable

int a, b;
a = 10;
b = 20;
float temp, height;
temp = 36.5f;
height = 5.9f;
            

Quiz: Multiple Assignment

  • A) int a, b; a=5; b=10;
  • B) float x, y; x=; y=20;
  • C) char c; c;
  • D) bool flag;

// Multiple assignment example
int a, b;
a = 5;
b = 10;
cout << a + b;
            

Key Takeaways

  • Assign values anytime after declaration
  • Works for all basic types
  • Improves readability and debugging

string name;
name = "Alice";
int age;
age = 25;
cout << name << " is " << age << " years old";
            

Reassignment

  • Change value of an variable
  • Previous value is overwritten
  • Applicable to all types

int score = 50;
score = 75;
float temp = 36.5f;
temp = 37.0f;
char grade = 'B';
grade = 'A';
bool passed = false;
passed = true;
string name = "Bob";
name = "Alice";
            

Quiz: Reassignment

  • A) int x = 5; x = 10;
  • B) float y;
  • C) char c;
  • D) bool flag;

// Reassignment example
int x = 5;
x = 10;
cout << x;
            

Tips for Reassignment

  • Use meaningful variable names
  • Keep track of current value
  • Reassignment can happen many times

int score = 50;
score = 70;
score = 90;
cout << "Final score: " << score;
            

Quiz: Tips

  • A) int x = 10; x = 20;
  • B) float y;
  • C) char c;
  • D) bool flag;

// Multiple reassignment
int x = 10;
x = 20;
x = 30;
cout << x;
            

Key Takeaways

  • Reassignment changes variable values
  • Overwrites previous value
  • Use meaningful names and keep track

int score = 50;
score = 75;
score = 100;
cout << "Final Score: " << score;
            
  1. Introduction to Variables ✓
  2. Variable Declaration ✓
  3. Variable Initialization ✓
  4. Assignment ✓
  5. Reassignment ✓
  6. Hands-On Practice
  7. Variable Memory Size
  8. Constants, Casting, etc.
  9. Basic Input Output (I/O)
  10. Homework 1 and Lab 1

Hands-On Practice 1

John is 21 years old. Define a variable to store his age and initialize it with the correct value.


// Define variable type and initialize
            

Hands-On Practice 2

The room temperature is 23.5 degrees Celsius. Create a variable to store the temperature.


// Define variable type and initialize
            

Hands-On Practice 3

The student received a grade 'A' in the exam. Define a variable to store the grade.


// Define variable type and initialize
            
  1. Introduction to Variables ✓
  2. Variable Declaration ✓
  3. Variable Initialization ✓
  4. Assignment ✓
  5. Reassignment ✓
  6. Hands-On Practice ✓
  7. Variable Memory Size
  8. Constants, Casting, etc.
  9. Basic Input Output (I/O)
  10. Homework 1 and Lab 1

Memory Size: int

  • Stores whole numbers
  • Typically 4 bytes (depends on system)
  • Range: -2,147,483,648 to 2,147,483,647

#include <iostream>
using namespace std;

int main() {
    cout 
        << "Size of int: " 
        << sizeof(int) 
        << " bytes\n";
}
            

Memory Size: float

  • Stores decimal numbers
  • Typically 4 bytes
  • Approximate precision: 6–7 digits

#include <iostream>
using namespace std;

int main() {
    cout 
        << "Size float: " 
        << sizeof(float) 
        << " bytes\n";
}
            

Memory Size: double

  • Stores decimal numbers with higher precision
  • Typically 8 bytes
  • Approximate precision: 15–16 digits

#include <iostream>
using namespace std;

int main() {
    cout 
        << "Size of double: " 
        << sizeof(double) 
        << " bytes\n";
}
            

Memory Size: char

  • Stores a single character
  • Typically 1 byte
  • Range: -128 to 127 (signed)

#include <iostream>
using namespace std;

int main() {
    cout 
        << "Size of char: " 
        << sizeof(char) 
        << " bytes\n";
}
            

Memory Size: bool

  • Stores true or false
  • Typically 1 byte
  • 0 = false, 1 = true

#include <iostream>
using namespace std;

int main() {
    cout 
        << "Size of bool: " 
        << sizeof(bool) 
        << " bytes\n";
}
            

Memory Size: string

  • Stores text of variable length
  • Size depends on implementation and length of content
  • Typically more than the length of characters due to overhead

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name = "Alice";
    cout 
        << "Size of string object: " 
        << sizeof(name) 
        << " bytes\n";
}
            
  1. Introduction to Variables ✓
  2. Variable Declaration ✓
  3. Variable Initialization ✓
  4. Assignment ✓
  5. Reassignment ✓
  6. Hands-On Practice ✓
  7. Variable Memory Size ✓
  8. Constants, Casting, etc.
  9. Basic Input Output (I/O)
  10. Homework 1 and Lab 1

Constants (const)

  • Variables that cannot be changed after initialization
  • Useful for fixed values like PI or max limits
  • Helps prevent accidental modification

const double PI = 3.14159;
const int MAX_STUDENTS = 50;
cout << "PI: " << PI << ", Max: " << MAX_STUDENTS;
            

Type Modifiers

  • Change size or sign of data types
  • Common modifiers: short, long, unsigned
  • Useful for memory optimization or larger ranges

unsigned int count = 100;
long distance = 100000L;
short smallNumber = 10;
cout << count << ", " << distance << ", " << smallNumber;
            

Type Casting / Conversion

  • Convert a variable from one type to another
  • Implicit vs explicit casting
  • Helps when performing calculations with different types

int x = 10;
double y = (double)x; // explicit cast
float z = x;           // implicit cast
cout << y << ", " << z;
            

Input & Output

  • Use cin to read values from user
  • Use cout to display values
  • Works with all basic data types

int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age;
            

Scope & Lifetime of Variables

  • Local variables exist only inside a function/block
  • Global variables exist throughout the program
  • Helps manage memory and avoid conflicts

int globalVar = 100; // global

void func() {
    int localVar = 50; // local
    cout << localVar;
}

int main() {
    cout << globalVar;
    func();
}
            

Default Values

  • Uninitialized variables may contain garbage
  • Always initialize variables to avoid undefined behavior
  • Applies to int, float, double, char, bool, string

int a;       // may have garbage value
float b;     // may have garbage
int c = 0;   // safe initialization
float d = 0; // safe initialization
            

Enumerations (enum)

  • Define a set of named integer constants
  • Improves code readability
  • Use for categories, options, or states

enum Color { RED, GREEN, BLUE };
Color c = RED;
cout << c; // prints 0 for RED
            

Pointers (Intro)

  • Store memory addresses of variables
  • Useful for dynamic memory and efficient data handling
  • Introductory concept for later lessons

int x = 10;
int* ptr = &x; // pointer stores address of x
cout << "Address: " << ptr;
cout << "Value: " << *ptr;
            
  1. Introduction to Variables ✓
  2. Variable Declaration ✓
  3. Variable Initialization ✓
  4. Assignment ✓
  5. Reassignment ✓
  6. Hands-On Practice ✓
  7. Variable Memory Size ✓
  8. Constants, Casting, etc.✓
  9. Basic Input Output (I/O)
  10. Homework 1 and Lab 1

Basic IO: Introduction

  • cin and cout are used for input and output
  • cin reads data from user
  • cout prints data to console
  • Part of iostream library

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "Your age is " << age;
}
            

Input Multiple Variables

  • cin can read several variables at once
  • Values are separated by spaces
  • Works for int, float, char, string

#include <iostream>
#include <string>
using namespace std;

int main() {
    int age;
    float height;
    string name;

    cout << "Enter name, age, height: ";
    cin >> name >> age >> height;

    cout << name << " is " << age << " years old, "
         << height << " m tall";
}
            

Formatted Output

  • Use endl for new lines
  • << operator concatenates outputs
  • Useful for clear console messages

#include <iostream>
using namespace std;

int main() {
    int x = 10, y = 20;
    cout << "X = " << x << endl;
    cout << "Y = " << y << endl;
    cout << "Sum = " << (x+y) << endl;
}
            

Input Validation

  • Check if the user enters the correct type
  • cin.fail() can detect input errors
  • Helps avoid garbage values or crashes

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter age: ";
    cin >> age;

    if(cin.fail()) {
        cout << "Invalid input!";
    } else {
        cout << "Age: " << age;
    }
}
            

Input & Output with Strings

  • Use getline() for multi-word strings
  • cin reads only up to first space
  • cout prints the string normally

#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    cout << "Enter full name: ";
    getline(cin, fullName);
    cout << "Hello, " << fullName;
}
            
  1. Introduction to Variables ✓
  2. Variable Declaration ✓
  3. Variable Initialization ✓
  4. Assignment ✓
  5. Reassignment ✓
  6. Hands-On Practice ✓
  7. Variable Memory Size ✓
  8. Constants, Casting, etc.✓
  9. Basic Input Output (I/O) ✓
  10. Homework 1 and Lab 1

Today, Thursday Sept 4th

  1. Introduction to Variable Naming
  2. Team Formation & Game Rules
  3. Homework 1 and Lab 1 Overview

Introduction to Variable Naming

  • Good variable names improve readability
  • Reduces errors and improves maintainability
  • Follow clear conventions for consistency

// Example of descriptive names
int age = 20;
float heightInMeters = 1.75;
bool isRegistered = true;
            

Basic Rules

  • Names must start with a letter or underscore (_)
  • Cannot start with a digit
  • No special characters except underscore

// Valid names
int _count;
float totalAmount;
// Invalid names
// int 2ndValue;
// char first-name;
            

Case Sensitivity

  • Variable names are case-sensitive
  • age and Age are different
  • Follow consistent capitalization style

int age = 20;
int Age = 30; // separate variable
            

Meaningful Names

  • Describe purpose of the variable
  • Avoid generic names like temp or val
  • Helps others understand your code

int s;         // unclear
int score;     // clear
float t;       // unclear
float temperature; // clear
            

Naming Styles

  • camelCase: totalAmount
  • snake_case: total_amount
  • PASCALCase: TotalAmount (commonly for classes)
  • Be consistent across the project

// camelCase
int studentCount;
// snake_case
int student_count;
// PASCALCase (class example)
class StudentInfo {};
            

Boolean Variables

  • Use names that clearly represent true/false
  • Common prefixes: is, has, can
  • Helps readability in conditions

bool isRegistered = true;
bool hasAccess = false;
bool canVote = true;

if(isRegistered) {
    cout << "User registered.";
}
            

Avoid Reserved Keywords

  • C++ keywords cannot be used as variable names
  • Examples: int, float, class, return
  • Use descriptive alternatives

// Invalid
// int class = 10;
// float return = 5.5;
// Valid
int classCount;
float returnValue;
            

Length of Variable Names

  • Too short: unclear (x, y)
  • Too long: cumbersome (totalSumOfMonthlyTransactions)
  • Balanced: descriptive yet concise (totalSum)

int x;               // bad
int totalSumOfMonth; // too long
int totalSum;        // good
            

Global vs Local Variables

  • Use clear prefixes for global variables (g_)
  • Local variables should be descriptive within their function
  • Reduces confusion and conflicts

int g_totalUsers = 0; // global
void registerUser() {
    int localScore = 0; // local
}
            

Default Values

  • Always initialize variables to avoid garbage values
  • Applies to all types: int, float, char, bool, string
  • Helps prevent undefined behavior

int score = 0;
float temperature = 0.0f;
bool isActive = false;
string name = "";
char grade = 'A';
            

Constants

  • Variables that cannot be changed after initialization
  • Use UPPERCASE naming for constants
  • Helps distinguish from normal variables

const double PI = 3.14159;
const int MAX_USERS = 50;
cout << "PI: " << PI << ", Max: " << MAX_USERS;
            

Type Modifiers

  • short, long, unsigned modify size or sign
  • Helps memory optimization or larger ranges
  • Include in variable names if necessary

unsigned int count = 100;
long distance = 100000L;
short smallNumber = 10;
cout << count << ", " << distance << ", " << smallNumber;
            

Type Casting

  • Explicit: (double)x
  • Implicit: automatic conversion
  • Use descriptive names if casting result differs in purpose

int x = 10;
double y = (double)x; // explicit cast
float z = x;           // implicit cast
cout << y << ", " << z;
            

Scope & Lifetime

  • Local: exists inside a block/function
  • Global: exists throughout the program
  • Name variables clearly to reflect scope

int g_counter = 0; // global
void func() {
    int localCounter = 5; // local
    cout << localCounter;
}
cout << g_counter;
            

Summary: Best Practices

  • Start with a letter or underscore
  • Use meaningful, descriptive names
  • Follow a consistent style: camelCase or snake_case
  • Boolean variables: use is/has/can prefixes
  • Constants in UPPERCASE
  • Always initialize variables

// Example
int studentCount = 50;
bool isRegistered = true;
const int MAX_USERS = 100;
float temperature = 36.5f;
            
Questions?

Welcome & Game Briefing

Today's topic: Variables in C++. Teams will compete in quizzes, coding relays, and challenges!

Team Formation

Form 2–3 teams (3–5 members each). Pick a team name and captain.

Game Rules

  • Correct answer: +10 points
  • Wrong answer: -5 points
  • Bonus challenge: +15 points

Scoreboard

Team Red: 0 | Team Blue: 0 | Team Green: 0

Concept: What is a Variable?

A variable stores data that can change during program execution.

Quiz: Identify Valid Declaration

  • A) int 5x;
  • B) int x5;
  • C) int x=;
  • D) int;x=5;

Challenge: Declare Correctly


// Declare an integer named 'age'
    

Bonus Round: Declare 3 Types


// Declare int, float, char in one line
    

Quiz: Which is Correct Initialization?

  • A) int x = 10;
  • B) int x == 10;
  • C) int x;

Quiz: Boolean Naming

  • A) bool registered;
  • B) bool isRegistered;
  • C) bool 1Registered;

Quiz: Valid Variable Names

  • A) int _count;
  • B) int 2count;
  • C) int count!;

Quiz: Reserved Words

  • A) int float;
  • B) int value;
  • C) char return;

Quiz: Case Sensitivity

Which statement is correct?

  • A) int age = 5; int Age = 6;
  • B) int age = 5; int age = 6;
  • C) int Age = 5; int Age = 6;

Quiz: Constants Naming

  • A) const int MAX = 100;
  • B) const int max = 100;
  • C) int MAX = 100;

Quiz: Default Value

What is the default value of an uninitialized bool in C++?

Quiz: Float vs Double

Which type has higher precision?

  • A) float
  • B) double

Quiz: Type Modifiers

Which is correct to store only positive values?

  • A) int a;
  • B) unsigned int a;
  • C) long int a;

Quiz: Swap Variables


// Swap a=5, b=10 using arithmetic
    

Quiz: Variable Scope


int x = 5;
{
  int x = 10;
}
cout << x;
    

Quiz: Variable Shadowing

What happens if a local variable has the same name as a global variable?

  • A) Error
  • B) Local variable overrides global inside scope
  • C) Global variable overrides local

Quiz: Implicit Conversion

What is the type of int x = 5; double y = x;?

  • A) int to double (implicit)
  • B) double to int (explicit)

Quiz: Initialization vs Assignment

  • A) int x = 5; // initialization
  • B) x = 10; // assignment
  • C) Both A & B

Quiz: Naming Boolean Variables

  • A) bool flag;
  • B) bool isReady;
  • C) bool 0Ready;

Quiz: Valid Identifiers

  • A) int myVar;
  • B) int 2myVar;
  • C) int my-Var;

Quiz: Constants Correct Syntax

  • A) const int MAX = 10;
  • B) const int MAX;
  • C) int const MAX;

Quiz: Memory Sizes

  • A) char – 1 byte
  • B) int – 4 bytes
  • C) double – 8 bytes
  • D) All of the above

Quiz: Input/Output

Which line reads an integer from the user?

  • A) cin >> x;
  • B) cout << x;
  • C) scanf("%d", x);

Quiz: Swap Variables Correctly


// Swap x=3 and y=5 using a temporary variable
    

Lightning Round

5 quick questions: each worth +5 points.

Q1: Valid Variable Name?

  • A) int 1value;
  • B) int value1;
  • C) int value-1;

Q2: Boolean Initialization

  • A) bool flag = true;
  • B) bool flag = 1;
  • C) bool flag = "true";

Q3: Correct Constant Declaration

  • A) const int MAX = 100;
  • B) const int MAX;
  • C) int const MAX;

Q4: Default Value of uninitialized int?

  • A) 0
  • B) Garbage / undefined
  • C) 1

Q5: Output of this code?


int x = 5;
{
    int x = 10;
}
cout << x;
    

Team Discussion

When to use constants vs variables?

Scoreboard Update

Team Red: __ | Team Blue: __ | Team Green: __

Recap & Key Takeaways

  • Variables store changeable data
  • Constants prevent modification
  • Memory size matters
  • Input/Output via cin/cout

Final Quiz

Mixed questions on all topics.

Identify and fix the syntax error in this code.


int main() {
    int x
    x = 10;
    cout << x;
    return 0;
}
        

This code may crash. Find the problem and fix it.


int main() {
    int a = 5, b = 0;
    int c = a / b;
    cout << c;
    return 0;
}
        

The program prints incorrectly. Fix the variable scope.


int main() {
    if (true) {
        int x = 10;
    }
    cout << x;
    return 0;
}
        

Homework & Lab

Homework 1 and Lab 1 details shared with teams.

Winner Announcement

Congratulations to the winning team!

Today, Tuesday Sept 9th

  1. What is a branch?
  2. Decision-making in programs
  3. Real-world example
  4. if / else statements in C++
  5. switch statements in C++
  6. Homework and Lab
Agenda Image Placeholder

What is a Branch?

  • Programs need to make choices
  • Branches control the program flow
  • Initial check: Determine if the printer has paper before printing
  • Example: Printer checks paper tray
bool paperTrayFull = true;
if (paperTrayFull) {
    cout << "Ready to print";
}

What is a Branch?

  • Branches allow programs to respond differently
  • Initial check: Is printer online before sending a job?
  • Prevents errors like printing without power
bool printerOnline = false;
if (printerOnline) {
    cout << "Sending print job...";
} else {
    cout << "Printer offline!";
}

What is a Branch?

  • Branches evaluate conditions
  • Initial check: Is toner available?
  • Prevents printing blank pages
bool tonerAvailable = true;
if (tonerAvailable) {
    cout << "Printing document...";
} else {
    cout << "Refill toner first";
}

What is a Branch?

  • Branches help decision-making in sequence
  • Initial check: Paper type suitable for print job?
  • Ensures correct quality output
string paperType = "A4";
if (paperType == "A4") {
    cout << "Proceed with print";
} else {
    cout << "Insert correct paper size";
}

What is a Branch?

  • Branches allow error handling
  • Initial check: Is printer jammed?
  • Prevents damage and wasted pages
bool printerJam = true;
if (printerJam) {
    cout << "Clear the jam first";
} else {
    cout << "Ready to print";
}

What is a Branch?

  • Branches support conditional notifications
  • Initial check: Low ink warning
  • Prevents unfinished print jobs
bool inkLow = true;
if (inkLow) {
    cout << "Warning: Refill ink";
} else {
    cout << "Ink level sufficient";
}

What is a Branch?

  • Branches allow conditional logging
  • Initial check: Has a job been queued?
  • Helps track printer usage
bool jobQueued = true;
if (jobQueued) {
    cout << "Processing queued job";
} else {
    cout << "No jobs pending";
}

What is a Branch?

  • Branches check preconditions before execution
  • Initial check: Printer cover closed?
  • Ensures safe operation
bool coverClosed = false;
if (coverClosed) {
    cout << "Printer ready";
} else {
    cout << "Close the cover";
}

What is a Branch?

  • Branches are evaluated at runtime
  • Initial check: Correct tray selected?
  • Prevents printing errors
int selectedTray = 1;
if (selectedTray == 1) {
    cout << "Tray 1 selected";
} else if (selectedTray == 2) {
    cout << "Tray 2 selected";
} else {
    cout << "Invalid tray";
}

What is a Branch?

  • Branches check the state before action
  • Initial check: Printer ready to receive commands?
  • Ensures safe and correct execution
bool printerReady = true;
if (printerReady) {
    cout << "Ready for print job";
} else {
    cout << "Printer not ready";
}

Today, Tuesday Sept 9th

  1. What is a branch? ✓
  2. Decision-making in programs
  3. Real-world example
  4. if / else statements in C++
  5. switch statements in C++
  6. Homework and Lab
Agenda Image Placeholder

Decision-Making in Programs

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

Decision-Making in Programs

  • Check if printer cover is closed
  • Initial check ensures safe operation
bool coverClosed = false;
if (coverClosed) {
    cout << "Printer ready";
} else {
    cout << "Close the cover";
}

Decision-Making in Programs

  • Check if selected tray matches print job
  • Initial check prevents printing errors
int selectedTray = 1;
if (selectedTray == 1) {
    cout << "Tray 1 selected";
} else if (selectedTray == 2) {
    cout << "Tray 2 selected";
} else {
    cout << "Invalid tray";
}

Decision-Making in Programs

  • Check if printer has paper loaded in multiple trays
  • Ensures correct tray is used
bool tray1Full = true;
bool tray2Full = false;
if (tray1Full) {
    cout << "Using tray 1";
} else if (tray2Full) {
    cout << "Using tray 2";
} else {
    cout << "No paper loaded";
}

Decision-Making in Programs

  • Check network connectivity for printing
  • Initial check prevents sending jobs to unavailable printer
bool networkConnected = true;
if (networkConnected) {
    cout << "Connected to printer";
} else {
    cout << "Cannot reach printer";
}

Decision-Making in Programs

  • Check if print queue has pending jobs
  • Initial check prevents empty job execution
bool queueEmpty = false;
if (!queueEmpty) {
    cout << "Processing jobs...";
} else {
    cout << "No jobs in queue";
}

Decision-Making in Programs

  • Check toner and paper together before batch job
  • Initial check prevents job failure
bool paperFull = true;
bool tonerOk = false;
if (paperFull && tonerOk) {
    cout << "Starting batch print";
} else {
    cout << "Check paper or toner";
}

Decision-Making in Programs

  • Decision-making ensures safe operations
  • Example: Printer ready for user commands
bool printerReady = true;
if (printerReady) {
    cout << "Ready for print job";
} else {
    cout << "Printer not ready";
}

Today, Tuesday Sept 9th

  1. What is a branch? ✓
  2. Decision-making in programs ✓
  3. Real-world example
  4. if / else statements in C++
  5. switch statements in C++
  6. Homework and Lab
Agenda Image Placeholder

Printer

  • Check paper tray before printing
  • Prevent errors if tray empty
bool paperTrayFull = true;
if (paperTrayFull) {
    cout << "Printing...";
} else {
    cout << "Add paper to tray";
}

Card Swipe Door

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

Laundry Machine

  • Check if door is closed
  • Start washing only if safe
bool doorClosed = true;
if (doorClosed) {
    cout << "Starting wash cycle...";
} else {
    cout << "Close door first";
}

Smart Thermostat

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

Traffic Light

  • Check light color
  • Decide whether to go, stop, or slow down
char light = 'Y';
if (light == 'G') {
    cout << "Go";
} else if (light == 'Y') {
    cout << "Slow down";
} else if (light == 'R') {
    cout << "Stop";
} else {
    cout << "Invalid signal";
}

Smart Fridge

  • Check if milk is expired
  • Alert user to replace it
bool milkExpired = true;
if (milkExpired) {
    cout << "Replace milk";
} else {
    cout << "Milk is good";
}

ATM Machine

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

Elevator

  • Check requested floor
  • Move elevator accordingly
int requestedFloor = 5;
int currentFloor = 3;
if (requestedFloor > currentFloor) {
    cout << "Going up";
} else if (requestedFloor < currentFloor) {
    cout << "Going down";
} else {
    cout << "Already there";
}

Coffee Machine

  • Check water and bean levels
  • Start brewing only if sufficient
bool waterFull = true;
bool beansFull = false;
if (waterFull && beansFull) {
    cout << "Brewing coffee...";
} else {
    cout << "Refill water or beans";
}

Door Lock

  • Check if key or code is correct
  • Allow or deny entry
bool keyValid = true;
if (keyValid) {
    cout << "Door unlocked";
} else {
    cout << "Access denied";
}

Today, Tuesday Sept 9th

  1. What is a branch? ✓
  2. Decision-making in programs ✓
  3. Real-world example ✓
  4. if / else statements in C++
  5. switch statements in C++
  6. Homework and Lab
Agenda Image Placeholder

If / Else Statements

  • Basic conditional check
  • Syntax: if(condition) { ... } else { ... }
  • Use for two possible paths
int temp = 75;
if (temp > 70) {
    cout << "Turn on AC";
} else {
    cout << "AC off";
}

Else If

  • Handle multiple conditions in order
  • Evaluates first true condition
  • Useful for prioritized checks
int score = 82;
if (score >= 90) {
    cout << "A";
} else if (score >= 75) {
    cout << "B";
} else if (score >= 60) {
    cout << "C";
} else {
    cout << "Fail";
}

Best Practices

  • Keep conditions simple and readable
  • Use braces even for single statements
  • Avoid deeply nested ifs
if (isReady) {
    cout << "Ready";
} else {
    cout << "Not ready";
}

Common Mistakes

  • Using assignment instead of comparison (= vs ==)
  • Not handling else case
  • Multiple unrelated conditions in one if
bool active = true;
if (active = false) {  // ❌ mistake
    cout << "Inactive";
}

Interactive Question

  • Do you recommend if / else for multiple discrete values?
// Example: Decide printer mode
int mode = 2;
if (mode == 1) {
    cout << "Print B&W";
} else if (mode == 2) {
    cout << "Print Color";
} else {
    cout << "Unknown mode";
}

Nested If

  • Check multiple related conditions
  • Can become complex, reduce nesting if possible
bool hasPaper = true;
bool tonerOk = false;

if (hasPaper) {
    if (tonerOk) {
        cout << "Ready to print";
    } else {
        cout << "Replace toner";
    }
} else {
    cout << "Add paper";
}

Logical Operators

  • Combine multiple conditions with && or ||
  • Useful for if/else decision-making
bool paper = true;
bool toner = true;

if (paper && toner) {
    cout << "Printing...";
} else {
    cout << "Cannot print";
}

Short-circuit Evaluation

  • Conditions evaluated left-to-right
  • Stops as soon as outcome is known
  • Efficient for expensive checks
if (isConnected && hasJob) {
    cout << "Processing job";
}

Interactive Question

  • When should you prefer if/else over switch?
// Example: Printer toner check
int tonerLevel = 5;
if (tonerLevel < 3) {
    cout << "Refill toner";
} else if (tonerLevel <= 7) {
    cout << "Toner ok";
} else {
    cout << "Check sensor";
}

Summary – If / Else

  • Use for two or range-based conditions
  • Keep conditions readable
  • Use braces for clarity
bool ready = true;
if (ready) {
    cout << "Go";
} else {
    cout << "Wait";
}

Today, Tuesday Sept 9th

  1. What is a branch? ✓
  2. Decision-making in programs ✓
  3. Real-world example ✓
  4. if / else statements in C++ ✓
  5. switch statements in C++
  6. Homework and Lab
Agenda Image Placeholder

Switch Statement

  • Alternative to multiple else-if
  • Works with integers, chars, and enums
  • Check discrete values efficiently
int mode = 2;
switch(mode) {
    case 1: cout << "Print B&W"; break;
    case 2: cout << "Print Color"; break;
    default: cout << "Unknown mode";
}

Best Practices

  • Always use break after each case
  • Default case is optional but recommended
  • Keep cases simple and short
char option = 'B';
switch(option) {
    case 'A': cout << "Option A"; break;
    case 'B': cout << "Option B"; break;
    default: cout << "Invalid option";
}

Multiple Cases Same Action

  • Group multiple cases without code repetition
char grade = 'B';
switch(grade) {
    case 'A':
    case 'B': cout << "Pass"; break;
    case 'C': cout << "Consider"; break;
    default: cout << "Fail";
}

Switch with Enum

  • Better readability using enums
enum Mode { BW=1, COLOR=2 };
Mode m = COLOR;
switch(m) {
    case BW: cout << "B&W"; break;
    case COLOR: cout << "Color"; break;
}

Interactive Question

  • Do you recommend switch or if/else for checking a printer mode with 4 discrete options?
int printerMode = 3;
switch(printerMode) {
    case 1: cout << "B&W"; break;
    case 2: cout << "Color"; break;
    case 3: cout << "Draft"; break;
    case 4: cout << "High Quality"; break;
    default: cout << "Invalid mode";
}

Fallthrough Cases

  • Sometimes intentionally omit break
  • Can execute multiple cases sequentially
char c = 'A';
switch(c) {
    case 'A':
    case 'B': cout << "Good"; break;
    case 'C': cout << "Average"; break;
}

Default Case

  • Catches unexpected values
  • Prevents undefined behavior
int option = 5;
switch(option) {
    case 1: cout << "Option 1"; break;
    case 2: cout << "Option 2"; break;
    default: cout << "Unknown option";
}

Interactive Question

  • What happens if you forget break in a switch?
int x = 2;
switch(x) {
    case 1: cout << "One";
    case 2: cout << "Two"; // Falls through to next case
    case 3: cout << "Three";
}

Best Practices – Switch

  • Always include default
  • Keep cases simple
  • Use enums for readability
enum PrinterMode { BW=1, COLOR=2, DRAFT=3 };
PrinterMode mode = DRAFT;
switch(mode) {
    case BW: cout << "B&W"; break;
    case COLOR: cout << "Color"; break;
    case DRAFT: cout << "Draft"; break;
    default: cout << "Unknown";
}

Summary – Switch Statements

  • Use for discrete values
  • Readable and maintainable
  • Use default and breaks
char opt = 'C';
switch(opt) {
    case 'A': cout << "Option A"; break;
    case 'B': cout << "Option B"; break;
    case 'C': cout << "Option C"; break;
    default: cout << "Unknown";
}

Cyclomatic Complexity – Concept

  • Measures number of independent paths in a program
  • Helps assess code complexity
  • High complexity → harder to test and maintain
// Example concept
// A simple if/else has 2 paths
bool ready = true;
if (ready) {
    cout << "Go";
} else {
    cout << "Wait";
}

Cyclomatic Complexity – Formula

  • M = E – N + 2P
  • E = edges in flow graph
  • N = nodes in flow graph
  • P = connected components (usually 1 for single function)
// Simple function
int max(int a, int b) {
    if (a > b) return a;
    else return b;
}

Practical Example – Printer Check

  • Check paper, toner, and connection
  • 3 conditions → cyclomatic complexity = 4
bool paper = true;
bool toner = true;
bool connected = true;

if (paper && toner && connected) {
    cout << "Ready to print";
} else {
    cout << "Cannot print";
}

Interactive Question

  • Which has higher cyclomatic complexity?
  • A simple if/else or nested ifs checking 3 conditions separately?
// Nested example
if (paper) {
    if (toner) {
        if (connected) {
            cout << "Ready";
        }
    }
}

Best Practices

  • Keep cyclomatic complexity low (≤10 per function)
  • Refactor complex functions into smaller ones
  • Use switch statements or boolean logic to simplify
// Refactor example
bool readyToPrint(bool paper, bool toner) {
    return paper && toner;
}

Today, Tuesday Sept 9th

  1. What is a branch? ✓
  2. Decision-making in programs ✓
  3. Real-world example ✓
  4. if / else statements in C++ ✓
  5. switch statements in C++ ✓
  6. Homework and Lab
Agenda Image Placeholder
  • Introduce Horse Race Game
  • Track has 3 positions
  • Player controls horse moves
  • Game ends at finish line

// Overview: Start -> Middle -> Finish
// Player chooses moves
      
  • Horse starts at Start
  • Player chooses actions: Move or Quit
  • Each move is a decision branch

// Rules:
// Positions: START = 0, MIDDLE = 1, FINISH = 2
// Player input determines horse move
      
  • Define constants for positions
  • Avoid magic numbers

const int START = 0;
const int MIDDLE = 1;
const int FINISH = 2;
      
  • Use variables to store state
  • horsePos tracks position
  • choice stores player input

int horsePos = START;
int choice;
      
  • Print welcome message
  • Tell player rules
  • Show initial horse position

cout << "Horse Race Game!" << endl;
cout << "Horse starts at the beginning." << endl;
cout << "Horse: H _ _" << endl;
      
  • Ask player for first action
  • 1 = Move Forward, 2 = Quit

cout << "Choose: 1=Move, 2=Quit" << endl;
cin >> choice;
      
  • Check choice with if / else
  • Move horse if 1, quit if 2

if (choice == 1) {
    horsePos = MIDDLE;
    cout << "Horse moved to the middle!" << endl;
    cout << "Horse: _ H _" << endl;
} else {
    cout << "You quit the race." << endl;
    return 0;
}
      
  • Q: What does horsePos store?
  • A: Current position of the horse

// horsePos = START / MIDDLE / FINISH
      
  • Ask player for second action
  • 1 = Move Forward, 2 = Quit

cout << "Choose: 1=Move, 2=Quit" << endl;
cin >> choice;
      
  • Use switch-case for decision
  • Case 1 → Finish, Case 2 → Quit

switch(choice) {
    case 1:
        horsePos = FINISH;
        cout << "Horse: _ _ H" << endl;
        cout << "You reached finish line!" << endl;
        break;
    case 2:
        cout << "You quit the race." << endl;
        break;
    default:
        cout << "Invalid input." << endl;
}
      
  • Check if horse reached finish
  • Display winning message

if (horsePos == FINISH) {
    cout << "Congratulations! You won!" << endl;
}
      
  • Player chooses to quit
  • Game ends immediately
  • Show quit message

else {
    cout << "You quit the race. Game over." << endl;
}
      
  • Q: Why use switch-case?
  • A: Easier to handle multiple options

// switch(choice) { case 1: ... case 2: ... }
      
  • Visual representation of horse moves
  • Start → Middle → Finish

// Start: H _ _
// Middle: _ H _
// Finish: _ _ H
      
  • Player chose Move Forward
  • Horse updated to Middle

horsePos = MIDDLE;
cout << "Horse: _ H _" << endl;
      
  • Player chose Move Forward
  • Horse reached Finish
  • Display winning message

horsePos = FINISH;
cout << "Horse: _ _ H" << endl;
cout << "🏆 You won the race!" << endl;
      
  • Player can quit at first or second choice
  • Game ends immediately

if(choice == 2) {
    cout << "You quit the race. Game over." << endl;
}
      
  • Flow diagram of decisions
  • First: Move or Quit
  • Second: Move or Quit

// Pseudocode
// choice1 -> if/else -> horsePos = MIDDLE
// choice2 -> switch -> horsePos = FINISH / Quit
      
  • Use assignments to update horsePos
  • e.g., horsePos = MIDDLE

horsePos = MIDDLE;  // updates horse position
      
  • Constants used to label positions
  • START = 0, MIDDLE = 1, FINISH = 2

const int START = 0;
const int MIDDLE = 1;
const int FINISH = 2;
      

Today, Tuesday Sept 16th

  1. Introduction to Loops
  2. Why Loops are Useful
  3. while Loop in C++
  4. for Loop in C++
  5. Real-world Loop Examples
  6. Homework and Lab
Loops Agenda Image
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6

Introduction to Loops

  • Loops repeat a block of code
  • Used to avoid writing repetitive code
  • Types in C++: for, while, do-while
  • Can also nest loops for complex tasks
Types of Loops

For Loop

  • Use when number of iterations is known
  • Syntax: for(init; condition; update)
  • Common for counting and arrays
for (int i = 1; i <= 5; i++) {
    cout << "Count: " << i << endl;
}

While Loop

  • Use when iterations depend on condition
  • Condition checked before each loop
  • Runs 0 or more times
int x = 1;
while (x <= 5) {
    cout << "x = " << x << endl;
    x++;
}

Do-While Loop

  • Always executes at least once
  • Condition checked after each loop
  • Good for menus and input validation
int choice;
do {
    cout << "1=Play, 2=Quit" << endl;
    cin >> choice;
} while (choice != 2);

Nested Loops

  • Loop inside another loop
  • Useful for grids, tables, patterns

for (int r = 1; r <= 3; r++) {
    for (int c = 1; c <= 3; c++) {
        cout << "(" << r << "," << c << ")";
    }
    cout << endl;
}

Break and Continue

  • break → exits loop early
  • continue → skips to next iteration
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue; // skip 3
    if (i == 5) break;    // stop at 5
    cout << i << " ";
}

Common Mistakes

  • Forgetting loop update → infinite loop
  • Off-by-one errors (≤ vs <)
  • Using wrong condition
// Infinite loop: forgot i++
for (int i = 0; i < 5; ) {
    cout << i << " ";
}

// Off-by-one error
for (int i = 0; i <= 5; i++) {
    cout << i << " "; // Prints 0–5 instead of 0–4
}

Which loop guarantees at least one execution?

  • for loop
  • while loop
  • do-while loop
  • nested loop

What will be the value of x?

  • 5
  • 10
  • 15
  • 20
int x = 0;
for (int i = 1; i <= 5; i++) {
    x = x + i;
}

What will be the value of y?

  • 4
  • 8
  • 16
  • 32
int y = 1;
int i = 1;
while (i <= 4) {
    y = y * 2;
    i = i + 1;
}

What will be the value of count?

  • 5
  • 6
  • 10
  • 20
int count = 0;
for (int i = 10; i > 0; i -= 2) {
    count = count + 1;
}

What will be the value of z?

  • 40
  • 50
  • 60
  • 80
int z = 100;
do {
    z = z - 20;
} while (z > 50);

What will be the value of sum?

  • 3
  • 4
  • 5
  • 6
int sum = 0;
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        sum = sum + 1;
    }
}

Chessboard with Loops

  • We can draw an 8×8 chessboard using nested loops
  • No array is needed: just alternate characters
  • Use row + column sum to decide black or white square
// Print an 8x8 chessboard
for (int row = 0; row < 8; row++) {
    for (int col = 0; col < 8; col++) {
        if ((row + col) % 2 == 0)
            cout << "W "; // White square
        else
            cout << "B "; // Black square
    }
    cout << endl;
}
W B W B W B W B
B W B W B W B W
W B W B W B W B
B W B W B W B W
W B W B W B W B
B W B W B W B W
W B W B W B W B
B W B W B W B W
            

Today, Tuesday Sept 23rd

  1. Introduction to Arrays
  2. Array Declaration and Initialization
  3. Accessing, Updating Array Elements
  4. Introduction to Vectors in C++
  5. Comparing Arrays vs Vectors
  6. Practical Examples and Use Cases
  7. Homework and Lab
Arrays and Vectors Agenda Image

Why Do We Need Arrays?

  • Store multiple values, one name
  • Avoid creating many variables
  • Better organize, process data
  • Foundation for adv. data structures
Why Arrays are Needed

Before Arrays

  • Each flower stored in its own variable
  • Becomes messy with many flowers
  • Hard to loop through and manage

#include <iostream>
#include <string>
using namespace std;

int main() {
    string flower1 = "Rose";
    string flower2 = "Tulip";
    string flower3 = "Lily";

    cout << flower1 << endl;
    cout << flower2 << endl;
    cout << flower3 << endl;
}

After Arrays

  • Store multiple flowers under one name
  • Access any element using an index
  • Easy to loop through flowers

#include <iostream>
#include <string>
using namespace std;

int main() {
    string flowers[3] = {"Rose", "Tulip", "Lily"};
    cout << flowers[0]; // Rose
}

Accessing Array Elements

  • Use index to read or update values
  • flowers[0] gives "Rose"
  • flowers[1] = "Orchid" update 2nd elem

flowers[1] = "Orchid";
cout << flowers[1]; // Orchid

What will this code output?


string flowers[3] = {"Rose", "Tulip", "Lily"};
cout << flowers[2];
  • Rose
  • Tulip
  • Lily
  • Orchid

Iterating Over Flower Arrays

  • Use a loop to access all flowers
  • for loop runs from 0 to array size-1
  • Useful for displaying inventory

for(int i = 0; i < 3; i++) {
    cout << flowers[i] << endl;
}

Flower Prices in Arrays

  • Use numeric arrays for prices
  • Keep index aligned with flower names
  • flowers[0] = Rose → prices[0] = 2.99

string flowers[3] = {"Rose", "Tulip", "Lily"};
double prices[3] = {2.99, 1.99, 3.49};

cout << flowers[0] 
     << " costs $" 
     << prices[0];

Multidimensional Flower Arrays

  • Use 2D arrays to store quantities by day
  • rows = flowers, columns = days
  • Example: flower sales per week

int sales[2][3] = {
   {10, 15, 12}, // Roses
   { 8, 11,  9}  // Tulips
};

cout << sales[0][1]; // 15

Size of Flower Arrays

  • Size is fixed at compile time
  • Use sizeof to calculate element count
  • Divide total size by element size

int sizes[4] = {5, 6, 7, 8};
int count = sizeof(sizes) / sizeof(sizes[0]);
cout << "Total flowers: " << count;

Updating Flower Inventory

  • Arrays allow element reassignment
  • Replace old values with new ones
  • Example: Roses sold out → inventory 0

int inventory[3] = {20, 15, 10};
inventory[0] = 0; 
cout << inventory[0]; // 0

What is the output of this code?


string flowers[3] = {"Rose", "Tulip", "Lily"};
flowers[2] = "Daisy";
cout << flowers[2];
  • Rose
  • Tulip
  • Lily
  • Daisy

Arrays and Parallel Data

  • Keep multiple arrays in sync
  • flowers[i] ↔ prices[i] ↔ inventory[i]
  • Helps model flower shop data

string flowers[2] = {"Rose", "Tulip"};
double prices[2] = {2.99, 1.99};
int stock[2] = {12, 18};

cout << flowers[1] << " costs $"
     << prices[1] << " with "
     << stock[1] << " in stock.";

Passing Arrays to Functions

  • Pass array name as argument
  • Size must be handled separately
  • Useful for reusable flower shop utilities

void printFlowers(string arr[], int size) {
    for(int i=0; i<size; i++) {
        cout << arr[i] << endl;
    }
}

string flowers[3] = {"Rose","Tulip","Lily"};
printFlowers(flowers, 3);

Which statement about arrays in C++ is TRUE?

  • Arrays automatically resize when new items are added
  • Arrays store mixed data types
  • Arrays have a fixed size once declared
  • Arrays start indexing from 1

Simple Flower Tic-Tac-Toe

  • Array stores 3 cells
  • Players place X or O
  • Demonstrates updating array elements

int main() {
    char board[3] = {'_', '_', '_'};

    board[0] = 'X'; // Player 1
    board[1] = 'O'; // Player 2
    board[2] = 'X'; // Player 1

    for(int i=0; i<3; i++) {
        cout << board[i] << " ";
    }
    // Output: X O X
}

Introduction to Vectors

  • Dynamic arrays in C++
  • Size can grow or shrink
  • Useful for flower shop inventory

#include <vector>
#include <string>
using namespace std;

vector<string> flowers;

Adding Flowers to a Vector

  • Use push_back() to insert elements
  • No need to declare fixed size
  • More flexible than arrays

vector<string> flowers;
flowers.push_back("Rose");
flowers.push_back("Tulip");
flowers.push_back("Lily");

Which method adds a new flower to the end of a vector?

  • flowers.add()
  • flowers.insert()
  • flowers.push_back()
  • flowers.append()

Accessing Vector Elements

  • Use index like arrays
  • Index starts from 0
  • flowers[0] = first flower

cout << flowers[0]; // Rose
flowers[1] = "Orchid"; 

Looping Over Vectors

  • Use for loop to print all flowers
  • Use flowers.size() to get count
  • Dynamic: adjusts when vector grows

for(int i=0; i<flowers.size(); i++) {
    cout << flowers[i] << endl;
}

Which function returns the number of elements in a vector?

  • flowers.length()
  • flowers.size()
  • flowers.count()
  • flowers.elements()

Removing Flowers from a Vector

  • Use pop_back() to remove last element
  • Vector size decreases automatically
  • No need to manage manually

flowers.pop_back(); // removes "Lily"

Flower Prices with Vectors

  • Use parallel vectors
  • flowers[i] ↔ prices[i]
  • Dynamic sizes stay consistent

vector<string> flowers = {"Rose", "Tulip"};
vector<double> prices = {2.99, 1.99};

cout << flowers[0] 
     << " costs $" 
     << prices[0];

What happens if you call pop_back() on a vector?

  • Removes first element
  • Removes last element
  • Deletes the whole vector
  • Adds a default value

Vector of Quantities

  • Track stock for each flower
  • Update easily as sales happen
  • No need to re-declare array size

vector<int> stock = {12, 8, 15};
stock[1] = 10; // update Tulip stock

Iterating with Range-based For

  • C++11 feature
  • Simpler syntax for looping
  • Great for flower display

for(string f : flowers) {
    cout << f << endl;
}

Which loop style automatically iterates through all vector elements?

  • while loop
  • range-based for loop
  • do-while loop
  • traditional for loop

When to Use Arrays vs Vectors?

  • ...with fixed number of flowers?
  • ...when flowers are added/removed?
  • ...if flowers never change?

// Example: Array (fixed size)
string flowers[3] = {"Rose", "Tulip", "Lily"};

// Example: Vector (dynamic size)
vector<string> flowers = {"Rose", "Tulip"};
flowers.push_back("Lily");

Exercise: CountValues in Array

  • Write a function that takes an array of integers (or flower quantities)
  • Return the total sum of all elements
  • Example: [5, 3, 2] → total = 10
  • Test with different arrays of flower counts
Array Sum Illustration

Exercise: Create 8×8 Chess Board

  • Create a 2D array (8 rows × 8 columns)
  • Each cell can hold a chess piece
  • Symbols: 'K' for King, 'Q' for Queen
  • Initialize board with standard setup
  • Print the board in a readable format
8x8 Chess Board Illustration

Arrays vs Vectors Comparison

Feature Array Vector
Size Fixed at compile time Dynamic, can grow or shrink
Declaration int quantities[5]; vector<int> quantities;
Adding elements Cannot add beyond declared size Use push_back() to add elements
Removing elements Not possible Use pop_back() to remove last element
Memory Contiguous memory, static Contiguous memory, resizes dynamically
Access Use index: quantities[0] Use index: quantities[0]
Use case example Flower types fixed: 3 types Inventory can grow: add new flower types

Applications Using Variables, Conditions, Loops, and Arrays

  • Simple calculators and math operations
  • Inventory management systems
  • Basic games (e.g., Tic-Tac-Toe, number guessing)
  • Data processing and reporting (sum, average, min/max)
  • Simulations (traffic lights, queues, counters)
  • Text or number-based pattern printing

Today, Tuesday Sept 25

  1. Variables and Data Types
  2. Conditions
  3. Loops
  4. Arrays
  5. Vectors (optional)
  6. Combine all concepts in a complete program: Tic-Tac-Toe
  7. Homework and Lab: extend the game
Software Implementation Agenda

Step 1: Variables

  • Store board, current player, and game state
  • Example:
  • char board[3][3]; 
    char currentPlayer = 'X'; 
    bool gameOver = false;

Step 2: Conditions

  • Check if a move is valid
  • Check for a win or draw
  • Switch players
  • if (board[row][col] == ' ') {
        board[row][col] = currentPlayer;
    } else {
        cout << "Invalid move!";
    }
    if (checkWin(board, currentPlayer)) gameOver = true;

Step 3: Loops

  • Main game loop
  • Keep the game running until gameOver is true
  • while (!gameOver) {
        printBoard(board);
        getPlayerMove();
        updateBoard();
        checkWinOrDraw();
        switchPlayer();
    }

Step 4: Arrays

  • Use a 2D array to store the 3x3 board
  • Access and update elements using indices
  • board[0][0] = 'X';
    char cell = board[1][2];

Step 5: Vectors (Optional)

  • Track move history dynamically
  • Example:
  • #include <vector>
    vector<pair<int,int>> moves;
    moves.push_back(make_pair(row, col));

Step 6: Helper Function - Print Board

void printBoard(char board[3][3]) {
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {
            cout << board[i][j] << ' ';
        }
        cout << endl;
    }
}

Step 7: Helper Function - Check Win

bool checkWin(char board[3][3], char player) {
    // check rows, columns, diagonals
    for (int i=0; i<3; i++) {
        if (board[i][0]==player && board[i][1]==player && board[i][2]==player) return true;
        if (board[0][i]==player && board[1][i]==player && board[2][i]==player) return true;
    }
    if (board[0][0]==player && board[1][1]==player && board[2][2]==player) return true;
    if (board[0][2]==player && board[1][1]==player && board[2][0]==player) return true;
    return false;
}

Step 8: Full Game Loop

while (!gameOver) {
    printBoard(board);
    int row, col;
    cout << "Enter row and column: ";
    cin >> row >> col;
    if (board[row][col]==' ') {
        board[row][col] = currentPlayer;
        if (checkWin(board, currentPlayer)) {
            cout << currentPlayer << " wins!\n";
            gameOver = true;
        } else {
            switchPlayer();
        }
    } else {
        cout << "Invalid move!\n";
    }
}

Homework / Lab

  • Add move history using vectors
  • Implement undo functionality
  • Add a scoring system or play-again option

Today, Tuesday Sept 30th

  1. What is a Function?
  2. Function Declaration & Definition
  3. Function Call & Parameters
  4. Return Values and Void Functions
  5. Function Overloading & Default Params
  6. Inline and Recursive Functions
  7. Pass by Value & Reference
  8. Const Parameters & Func Templates
  9. Static Functions & Func Pointers
  10. Recap and Practice Questions
Functions Agenda Image

What is a Function?

  • Functions are reusable blocks of code
  • They perform specific tasks
  • Helps in modular programming
  • Example: Calculate sum of two numbers
// Function declaration
int sum(int a, int b);

Function Signature in C++

  • Defines function name and parameter types
  • Determines how function is called
  • Includes return type, name, and parameters
  • Does NOT include the function body
  • Used by compiler to differentiate functions
// Example function signatures
int add(int a, int b);
void displayScore(int score);
double calculateAverage(double total, int count);

Function Declaration & Definition

  • Declaration tells the compiler about function
  • Definition provides the actual code
  • Declaration: int sum(int, int);
  • Definition: int sum(int a,int b){return a+b;}
int sum(int a, int b) {
    return a + b;
}

Function Call

  • Functions are called to execute code
  • Arguments passed to function parameters
  • Example: Call sum(5, 3)
int result = sum(5, 3);
cout << result; // Outputs 8

Function Parameters

  • Parameters allow data input to function
  • Can have multiple parameters
  • Supports pass by value and pass by reference
void greet(string name) {
    cout << "Hello, " << name;
}

Return Values

  • Functions can return data to the caller
  • Use the return keyword
  • Return type must match declaration
int square(int x) {
    return x * x;
}

Void Functions

  • Void functions do not return a value
  • Used for performing actions only
  • Example: Printing a message
void printHello() {
    cout << "Hello World";
}

Function Overloading

  • Same function name, different parameters
  • Compiler differentiates by signature
  • Improves code readability
int sum(int a,int b);
double sum(double x,double y);

Default Parameters

  • Functions can have default values
  • Caller may omit those arguments
  • Defaults defined in declaration
int add(int a, int b=5) {
    return a+b;
}

Inline Functions

  • Inline suggests compiler replace call with code
  • Reduces function call overhead
  • Good for small functions
inline int cube(int x) {
    return x*x*x;
}

Recursion

  • Function calls itself
  • Must have a base case to stop recursion
  • Example: Factorial calculation
int fact(int n) {
    if(n<=1) return 1;
    return n*fact(n-1);
}

Pass by Value

  • Function gets a copy of the argument
  • Changes inside function do not affect caller
void update(int x) {
    x = x+5;
}

Pass by Reference

  • Function gets reference to original variable
  • Changes affect the caller variable
void update(int &x) {
    x = x+5;
}

Const Parameters

  • Prevents function from modifying argument
  • Useful for passing large objects safely
void display(const string &s) {
    cout << s;
}

Function Templates

  • Templates allow generic functions
  • Works with multiple data types
  • Reduces code duplication
template
T add(T a,T b){return a+b;}

Static Functions

  • Function scope limited to file
  • Cannot be called from other files
static void helper() {
    cout << "Helper function";
}

Function Pointers

  • Pointer that stores function address
  • Allows dynamic call of functions
int (*fp)(int,int) = sum;
cout << fp(2,3);

Recap: Function Types

  • Void and non-void functions
  • Inline, recursive, overloaded
  • Template and static functions
// Examples of all function types
void f1();
int f2(int x);
inline int f3(int y);

Question 1

  • Which function type returns no value?
  • A) void B) inline C) static D) template
// Answer: void

Question 2

  • Pass by reference allows function to modify caller?
  • A) Yes B) No
// Answer: Yes

Question 3

  • Template functions allow which of the following?
  • A) Only int B) Multiple types C) Only void
// Answer: B) Multiple types

Practice: Write Game Functions

  • Write function to calculate player score
  • Write function to display health status
  • Write function to check if player won
  • Use parameters for player stats
  • Return appropriate values from function
#include <iostream>
using namespace std;

// Example function skeletons
int calculateScore(int kills, int coins);
void displayHealth(int health);
bool hasWon(int score);

int main() {
    // Call your functions here
}

Today, Thursday Oct 2nd

  1. Practice: Build a 10-Function Game (parallel work)
Functions Teamwork Image

10-Function Game: Parallel Work

  • Student 1 → printWelcome()
  • Student 2 → generateSecret(int min, int max)
  • Student 3 → getPlayerGuess()
  • Student 4 → checkGuess(int secret, int guess)
  • Student 5 → printHint(int secret, int guess)
  • Student 6 → printResult(bool isCorrect)
  • Student 7 → askPlayAgain()
  • Student 8 → printGoodbye()
  • Student 9 → printScore(int score)
  • Student 10 → updateScore(int score, bool correct)
  • Everyone → main()
  • Required Libraries for the Game
  • <iostream> → input/output
  • <cstdlib> → random numbers
  • <ctime> → seed random
  • using namespace std; → avoid std::

#include <iostream>
#include <cstdlib>   // for rand() and srand()
#include <ctime>     // for time()
using namespace std;
            
  • Function 1: printWelcome() → Print a welcome message
void printWelcome() {
    cout << "Welcome!" << endl;
    cout << "Number Guessing Adventure!" << endl;
}
            
  • Function 2: generateSecret() → Generate a random number between min and max
int generateSecret(int min, int max) {
    return rand() % (max - min + 1) + min;
}
            
  • Function 3: getPlayerGuess() → Ask the player for a guess
int getPlayerGuess() {
    int guess;
    cout << "Enter your guess: ";
    cin >> guess;
    return guess;
}
            
  • Function 4: checkGuess() → Compare guess with secret
bool checkGuess(int secret, int guess) {
    return guess == secret;
}
            
  • Function 5: printHint() → Print if guess is too high or too low
void printHint(int secret, int guess) {
    if (guess < secret) cout << "Too low!";
    else if (guess > secret) cout << "Too high!";
}
            
  • Function 6: printResult() → Print if guess is correct
void printResult(bool isCorrect) {
    if (isCorrect) cout << "Correct! You guessed it!";
}
            
  • Function 7: askPlayAgain() → Ask if player wants to play again
bool askPlayAgain() {
    char choice;
    cout << "Play again? (y/n): ";
    cin >> choice;
    return choice == 'y' || choice == 'Y';
}
            
  • Function 8: printGoodbye() → Print a goodbye message
void printGoodbye() {
    cout << "Thanks for playing! Goodbye!" << endl;
}
            
  • Function 9: printScore() → Print player's current score
void printScore(int score) {
    cout << "Your current score: " << score << endl;
}
            
  • Function 10: updateScore() → Update score if guess is correct
int updateScore(int score, bool correct) {
    if (correct) return score + 1;
    return score;
}
            
  • Function 11: main() → Connect all functions to run the game

int main() {
    srand(time(0));
    int score = 0;
    printWelcome();
    bool playing = true;

    while (playing) {
        int secret = generateSecret(1, 100);
        bool correct = false;

        while (!correct) {
            int guess = getPlayerGuess();
            correct = checkGuess(secret, guess);
            printHint(secret, guess);
            score = updateScore(score, correct);
        }

        printResult(correct);
        printScore(score);
        playing = askPlayAgain();
    }

    printGoodbye();
    return 0;
}
            

Today, Tuesday Oct 7th

  1. Object-Oriented Programming (OOP)
  2. Classes and Objects
  3. Midterm Review & Sample Questions
OOP Agenda Image

The Formula of an Object

Variables + Functions = Object

Data (attributes) + Behavior (methods) = Object

Example: Car = (model, year) + (start(), stop())

Car Object Formula

What is OOP?

  • Program based on real-world entities
  • Objects combine data and actions
  • Improves organization and reuse
  • Example: Think of a Car as an object
Car Icon

Why Use OOP?

  • Models real-world systems easily
  • Makes code modular and readable
  • Encourages reuse through objects
  • Reduces redundancy
OOP Flow

OOP in the Real World

  • Car has properties (model, color)
  • It has actions (start, stop)
  • Each car unique but same design
Car Example

What is a Class?

  • A blueprint for creating objects
  • Defines attributes and behaviors
  • Does not store data itself
  • Example: “Car” is a class

class Car {
public:
    string model;
    int year;
    void start() {
        cout << "Car started";
    }
};
            

What is an Object?

  • An instance of a class
  • Has its own values for attributes
  • Can use class methods
  • Example: myCar is an object of Car

Car myCar;
myCar.model = "Tesla";
myCar.year = 2024;
myCar.start();
            

Creating Multiple Objects

  • Each object has its own data
  • Objects can share class structure
  • Memory allocated separately

Car car1, car2;
car1.model = "Honda";
car2.model = "BMW";
            

Data and Behavior

  • Data (attributes): model, color, year
  • Behavior (methods): start(), stop()
  • Together form an object’s identity
Car Data Behavior

Recap: Class and Object

  • Class: Blueprint for a car
  • Object: A specific car created from blueprint
  • OOP helps model real-world systems easily
Recap Icon

Practice Question

  • Create a Car class with attributes: brand, year
  • Add a method displayInfo() to print details
  • Create two Car objects and call the method

Car car1, car2;
car1.brand = "Toyota";
car2.brand = "Ford";
car1.displayInfo();
car2.displayInfo();
            

Today, Tuesday Oct 21th

  1. Midterm Review
  2. Object-Oriented Programming (OOP)
  3. Classes and Objects
OOP Agenda Image

Today, Thursday Oct 23th

  1. Brief Quiz and Midterm Survey
  2. Object-Oriented Programming (cont.)
  3. Lab, Homework, and Project
OOP Agenda Image

Midterm Survey

  • More labs/quiz (in class)
  • Review Functions and Arrays
  • Attendance
  • Less random asking

Brief Quiz

  • Not graded
  • Previous topics
  • Concept and Coding
  • On paper

Today, Thursday Oct 23th

  1. Brief Quiz and Midterm Survey ✓
  2. Object-Oriented Programming (cont.)
  3. Lab, Homework, and Project
OOP Agenda Image

Object-Oriented Programming

  • Model real-world entities
  • Encapsulate data and behavior
  • Promotes reusability

Why model entities in OOP?


<!-- Example: Vehicles and Cars -->

Inheritance Example: Car

  • Car "is-a" Vehicle
  • Reuse brand and honk() methods

Concept: Inheritance


+-----------+         +-----------+
| Vehicle   | <----   | Car       |
+-----------+         +-----------+
| brand     |         | doors     |
| honk()    |         | honk()    |
+-----------+         +-----------+

Composition Example: Car

  • Car "has-a" Engine

Concept: Composition


+-----------+         +-----------+
| Car       | <----   | Engine    |
+-----------+         +-----------+
| brand     |         | hp        |
| doors     |         +-----------+
| engine    |  // Car "has-a" Engine
+-----------+

Inheritance Example: Agriculture

  • Tractor "is-a" FarmEquipment

Concept: Inheritance


+----------------+       +----------------+
| FarmEquipment  | <--   | Tractor        |
+----------------+       +----------------+
| manufacturer   |       | horsepower     |
| start()        |       | start()        |
+----------------+       +----------------+

Composition Example: Agriculture

  • Tractor "has-a" Plow

Concept: Composition


+-------------+         +------------+
| Tractor     | <-----  | Plow       |
+-------------+         +------------+
| manufacturer|         | type       |
| engine      |         +------------+
| plow        | // Tractor "has-a" Plow
+-------------+

Inheritance Example: Healthcare

  • MRI "is-a" MedicalDevice

Concept: Inheritance


+----------------+       +----------------+
| MedicalDevice  | <--   | MRI            |
+----------------+       +----------------+
| model          |       | resolution     |
| operate()      |       | operate()      |
+----------------+       +----------------+

Composition Example: Healthcare

  • MRI "has-a" CoolingSystem

Concept: Composition


+----------------+       +----------------+
| MRI            | <--   | CoolingSystem  |
+----------------+       +----------------+
| model          |       | capacity       |
| power          |       +----------------+
| coolingSystem  | // MRI "has-a" CoolingSystem
+----------------+

Defining a Class

  • Keyword <code>class</code>
  • Members: data + functions

class Vehicle {
public:
    string brand;
    void honk() {
        cout << "Beep!" << endl;
    }
};

Creating Objects

  • Objects are instances of classes

How do we instantiate Vehicle?


Vehicle v1;
v1.brand = "Toyota";
v1.honk();

Encapsulation

  • Hide details using access specifiers
  • public, private, protected

class Vehicle {
private:
    int speed;
public:
    void setSpeed(int s){ speed = s; }
    int getSpeed(){ return speed; }
};

Constructors

  • Initialize objects automatically

Why use constructors?


class Vehicle {
public:
    string brand;
    Vehicle(string b){ brand = b; }
};

Using Constructors

  • Called when object is created

Vehicle v1("Honda");
cout << v1.brand;

Destructors

  • Clean up resources

When is a destructor called?


~Vehicle() {
    cout << brand << " destroyed." << endl;
}

Inheritance

  • Derive new class from existing one
  • Reuse attributes & methods

class Car : public Vehicle {
public:
    int doors;
};

Derived Class Access

  • Inherited members become available

How do Car objects access Vehicle members?


Car c1;
c1.brand = "Ford";
c1.honk();
c1.doors = 4;

Protected Members

  • Accessible in derived classes

class Vehicle {
protected:
    int year;
};

Base Constructor Calls

  • Use initializer list

How does Car call Vehicle constructor?


class Car : public Vehicle {
public:
    Car(string b, int y) : Vehicle(b) {
        year = y;
    }
};

Multi-Level Inheritance

  • Derived class can be extended further

class ElectricCar : public Car {
public:
  int batteryCapacity;
  ElectricCar(string b,int y,int d,int bc) : Car(b,y,d){
    batteryCapacity = bc;
  }
};

Accessing Members

  • ElectricCar has all Car and Vehicle members

How do we set all attributes for ElectricCar?


ElectricCar e1("Tesla",2025,4,75);
cout << e1.brand << ", ";
cout << e1.doors << ", ";
cout << e1.batteryCapacity << endl;

Overriding Functions

  • Derived class modifies base behavior

class Car : public Vehicle {
public:
    void honk() {
        cout << "Car horn!" << endl;
    }
};

Abstract Classes

  • Contains pure virtual functions

Why use abstract classes?


class Vehicle {
public:
    virtual void honk() = 0;
};

Implementing Abstract Methods

  • Derived class must override pure virtual functions

class Car : public Vehicle {
public:
    void honk() override {
        cout << "Car horn!" << endl;
    }
};

Composition vs Inheritance

  • “Has-a” vs “Is-a” relationship

Question: How does Car “have” an Engine?


class Engine {
public: int hp;
};
class Car {
    Engine e; // Composition
};

Static Members

  • Shared among all objects

class Car {
public:
    static int count;
};
int Car::count = 0;

Using Static Members

  • Access without creating objects

How to increment static counter?


Car::count++;
cout << Car::count;

Namespaces

  • Organize code more...

namespace vehicles {
    class Car {};
}
vehicles::Car c1;

Multiple Inheritance

  • A class can inherit from multiple bases

How does SmartCar inherit GPS and MusicSystem?


class GPS {};
class MusicSystem {};
class SmartCar : public GPS, public MusicSystem {};
SmartCar s;

Summary

  • Classes encapsulate data
  • Inheritance builds hierarchies
  • Polymorphism enables flexibility

<!-- Vehicle → Car → ElectricCar -->

Today, Tuesday Oct 28th

  1. Introduction to Data Streams
  2. Saving Data Streams to File in C++
  3. Examples and Exercises

// Topic: Saving Data Streams to File
// Language: C++

What is a Data Stream?

  • A continuous flow of data elements.
  • Streams can be input (read) or output (write).
  • Used in sensors, logging, and files.

// Streams in C++ represent data flow:
// input  -> istream
// output -> ostream

C++ Stream Classes

  • istream: for reading data
  • ostream: for writing data
  • fstream: for both

#include <iostream>
#include <fstream>
using namespace std;

File Stream Objects

  • ifstream - input from file
  • ofstream - output to file
  • fstream - both directions

ifstream inFile;
ofstream outFile;
fstream file;

Opening a File for Writing

  • Use ofstream with filename
  • Automatically creates file if missing
  • Overwrites existing file by default

ofstream outFile("data.txt");
outFile << "Hello, stream!" << endl;
outFile.close();

Opening Modes

  • ios::out - Write mode
  • ios::in - Read mode
  • ios::app - Append mode
  • ios::binary - Binary mode

ofstream file("log.txt", ios::app);
file << "New entry\n";
file.close();

Reading from a File

  • Use ifstream to read files
  • Use getline() to read line-by-line

ifstream inFile("data.txt");
string line;
while (getline(inFile, line)) {
    cout << line << endl;
}
inFile.close();

Error Checking

  • Always verify that file opened successfully
  • Use is_open() or fail()

ofstream out("output.txt");
if (!out.is_open()) {
    cerr << "Error opening file\n";
}

Stream States

  • good() – No errors
  • eof() – End of file reached
  • fail() – Logical error
  • bad() – Read/write error

if (in.fail()) {
    cout << "Read failed!" << endl;
}

Flushing the Stream

  • flush() forces buffer write
  • Useful for real-time logs

outFile << "Saving..." << flush;

Binary Output Streams

  • Use ios::binary mode
  • Write raw bytes using write()

ofstream out("sensor.bin", ios::binary);
float value = 24.5;
out.write((char*)&value, sizeof(value));
out.close();

Binary Input Streams

  • Read binary data using read()
  • Cast to the correct data type

ifstream in("sensor.bin", ios::binary);
float value;
in.read((char*)&value, sizeof(value));
in.close();

Appending Data

  • Open with ios::app
  • Writes at end of file

ofstream file("log.txt", ios::app);
file << "New session started\n";
file.close();

Redirecting cout to File

  • Capture console output to file
  • Use rdbuf() to redirect

ofstream log("out.txt");
streambuf *old = cout.rdbuf(log.rdbuf());
cout << "Logging data...";
cout.rdbuf(old);

Continuous Data Stream Example

  • Simulate sensor readings
  • Write multiple values in a loop

ofstream data("stream.txt");
for (int i = 0; i < 5; ++i)
    data << "Reading " << i << endl;
data.close();

Reading Until EOF

  • Loop until eof() is true
  • Useful for unknown file lengths

while (!in.eof()) {
    getline(in, line);
    cout << line << endl;
}

Error Recovery

  • Use clear() to reset stream state
  • Then retry operation if needed

if (in.fail()) {
    in.clear();
    in.seekg(0);
}

Practical Use Case

  • Store sensor readings over time
  • Save to CSV or binary file
  • Later load for analysis

ofstream log("sensor.csv");
log << "time,temp\n";
for (int i=0;i<10;i++)
  log << i << "," << 20+i << endl;
log.close();

Summary

  • Streams simplify file I/O
  • Use text or binary modes as needed
  • Always close and check for errors

// Save, Read, Verify
// C++ file streams = reliable data persistence

Today, Tuesday Oct 30th

  1. Introduction to Data Streams
  2. Saving Data Streams to File in C++
  3. Examples and Exercises
Writing to a File Diagram

Slide: C++ Stream Class Hierarchy

  • Shows inheritance from ios base class
  • Separation of input (istream) and output (ostream)
  • Specialized classes for files and combined streams
Class Type Description
ios Base Base class for all stream operations
ostream Output Provides output operations (<<)< /td>
istream Input Provides input operations (>>)
ofstream Output File Write to files
ifstream Input File Read from files
iostream Input/Output Supports both reading and writing
fstream File I/O Read and write files

Introduction to Streams

  • What is a stream?
  • Input vs Output streams
  • Standard streams: cin, cout, cerr

// Input and output streams
#include 
using namespace std;

int main() {
    int x;
    cout << "Enter a number: ";
    cin >> x;
    cout << "You entered: " << x << endl;
    return 0;
}

File Streams

  • ofstream: write to file
  • ifstream: read from file
  • fstream: read/write

#include 
using namespace std;

ofstream outFile("data.txt");
outFile << "Hello, file!" << endl;
outFile.close();

Opening Files

  • Open in text mode
  • Open in binary mode
  • Check if open succeeded

#include 
#include 
using namespace std;

ifstream inFile("data.txt");
if(!inFile) {
    cerr << "Error opening file!" << endl;
}

Writing to a File

  • Use << operator
  • Write strings or numbers
  • Close after writing

ofstream outFile("output.txt");
outFile << "C++ streams are easy!" << endl;
outFile << 42 << endl;
outFile.close();

Reading from a File

  • Use >> operator or getline
  • Read strings or numbers
  • Check for EOF

ifstream inFile("output.txt");
string line;
while(getline(inFile, line)) {
    cout << line << endl;
}
inFile.close();

Stream States

  • good(), eof(), fail(), bad()
  • Check before read/write
  • Recover from errors

ifstream inFile("data.txt");
if(inFile.good()) {
    cout << "Ready to read." << endl;
}
if(inFile.eof()) {
    cout << "End of file reached." << endl;
}

Binary Files

  • Use ios::binary
  • Store data efficiently
  • Read/write raw bytes

ofstream outFile("data.bin", ios::binary);
int x = 12345;
outFile.write(reinterpret_cast(&x), sizeof(x));
outFile.close();

Reading Binary Files

  • Read using read()
  • Use reinterpret_cast
  • Know data type size

ifstream inFile("data.bin", ios::binary);
int x;
inFile.read(reinterpret_cast(&x), sizeof(x));
cout << x << endl;
inFile.close();

File Modes

  • ios::in, ios::out
  • ios::app, ios::trunc
  • Combine modes with | operator

ofstream outFile("data.txt", ios::app); // append
outFile << "More text" << endl;
outFile.close();

Formatted Output

  • Use manipulators
  • setw(), setprecision()
  • Fixed and scientific formats

#include 
cout << setw(10) << 123 << endl;
cout << fixed << setprecision(2) << 3.14159 << endl;

Unformatted Output

  • Use put(), write()
  • Character or byte-wise output

ofstream outFile("char.txt");
outFile.put('A');
outFile.write("Hello", 5);
outFile.close();

Unformatted Input

  • Use get(), getline(), read()
  • Character or binary input

ifstream inFile("char.txt");
char c;
inFile.get(c);
cout << c << endl;
inFile.close();

String Streams

  • istringstream, ostringstream
  • Parse strings like files
  • Useful for conversion

#include 
string data = "10 20 30";
istringstream ss(data);
int x;
while(ss >> x) {
    cout << x << endl;
}

Flushing Streams

  • Use flush() or endl
  • Ensure output is written

cout << "Hello, world!" << endl; // flushes
cout << "Hello again!";
cout.flush();

Stream Manipulators

  • hex, dec, oct
  • boolalpha, nouppercase

cout << hex << 255 << endl; // ff
cout << boolalpha << true << endl; // true

Stream Buffers

  • Underlying storage for streams
  • Use rdbuf() for custom buffer

ofstream out("buf.txt");
streambuf* buf = out.rdbuf();
cout << "Using same buffer as file" << endl;

Error Handling

  • Check fail(), bad()
  • Clear errors with clear()

ifstream in("data.txt");
if(in.fail()) {
    cerr << "Read failed!" << endl;
    in.clear(); // reset state
}

Closing Streams

  • Always close files
  • Destructor also closes

ofstream out("file.txt");
out << "Some text" << endl;
out.close(); // important!

Exercises

  • Write numbers 1-10 to a file
  • Read them back and sum
  • Use binary mode

// Exercise code here

Quiz

  • What class is used for writing files?
  • How to open binary file?
  • What is flush() used for?

// Answer review in class

Class Discussion: Review Questions

  1. What is the difference between ofstream and fstream?
  2. When should you use ios::app mode?
  3. How can you detect if a file failed to open?
  4. What is the purpose of flush()?
  5. Why do we use reinterpret_cast<char*> for binary data?

// Think and Discuss:
// - File modes
// - Error handling
// - Binary vs text data

In-Class Coding Question

  • Write a C++ program that:
    • Opens a file called numbers.txt
    • Writes the numbers 1–10, each on a new line
    • Closes the file
    • Then reads and prints all numbers to the console

// TODO:
// 1. Create ofstream to write numbers
// 2. Close the file
// 3. Reopen with ifstream to read
// 4. Print contents to console

Today, Tuesday Nov 4th

  1. Introduction to Exception Handling
  2. Try, Catch, and Throw in C++
  3. Agriculture-based Examples
Exception Handling Concept

What is Exception Handling?

  • Helps manage unexpected runtime errors.
  • Prevents the program from crashing suddenly.
  • Uses try, throw, and catch.
Farm Safety

Why Do Farmers Need Error Handling?

  • Ensures sensor data doesn’t crash systems.
  • Protects important farm records.
  • Keeps irrigation or automation running safely.

// Without Exception Handling
int main() {
    int soilMoisture = 100;
    int sensors = 0;
    cout << soilMoisture / sensors; // crash!
}
            

Basic Syntax

  • try: risky code.
  • throw: send out an error.
  • catch: handle the error safely.

try {
    // risky code
} catch (exceptionType e) {
    // handle problem
}
            

Example: Divide Crop Yield

  • Catch division by zero when calculating yield per acre.

try {
    int totalYield = 500;
    int acres = 0;
    if (acres == 0)
        throw runtime_error("No acres found!");
    cout << totalYield / acres;
}
catch (const runtime_error& e) {
    cerr << e.what();
}
            

💡 Question:

  • What happens if no catch block matches the error type?
  • Does the program continue or stop?
 

Multiple Error Types

  • Different exceptions can mean different problems.

try {
    throw "Sensor error!";
}
catch (int e) { cout << "Integer error"; }
catch (const char* e) { cout << e; }
            

Catch-All Handler

  • Use catch(...) for unknown problems.

try {
    throw "Data lost!";
}
catch (...) {
    cout << "Unknown farm error.";
}
            

Standard Exception

  • Use built-in std::exception for simplicity.
  • Access details with what().

catch (const exception& e) {
    cerr << e.what();
}
            

Custom Farm Error

  • You can make your own exception type.

class FarmError : public exception {
public:
    const char* what() const noexcept override {
        return "Farm system error!";
    }
};
            

Using Custom Farm Error


try {
    throw FarmError();
}
catch (const FarmError& e) {
    cerr << e.what();
}
            

Example: Sensor Reading

  • Throw error if temperature sensor gives invalid value.

float readTemp = -100;

try {
    if (readTemp < -50)
        throw runtime_error("Sensor reading invalid!");
    cout << readTemp;
}
catch (const exception& e) {
    cerr << e.what();
}
            

💡 Question:

  • Why should we check data before using it in calculations?
 

Re-Throwing Exceptions

  • Pass the problem up if it can’t be solved here.

try {
    try { throw runtime_error("Pump error!"); }
    catch (...) { throw; }
}
catch (const exception& e) {
    cerr << e.what();
}
            

Stack Unwinding

  • When an error occurs, local variables are destroyed automatically.

struct Crop {
    ~Crop() { cout << "Crop data cleaned up\n"; }
};

int main() {
    try {
        Crop c;
        throw 1;
    } catch (...) {}
}
            

File Handling Example

  • Throw error if weather data file is missing.

ifstream file("weather.txt");
if (!file)
    throw runtime_error("File not found!");
            

Practical Example: Soil Moisture

  • Handle invalid soil moisture values safely.

float soil = -10;
try {
    if (soil < 0)
        throw runtime_error("Invalid soil reading!");
    cout << soil;
}
catch (const exception& e) {
    cerr << e.what();
}
            

💡 Question:

  • What could happen if invalid sensor data isn’t caught?
 

Handling Exceptions from Functions

  • Errors can be thrown from helper functions.

void checkPump() { throw runtime_error("Pump offline!"); }

int main() {
    try { checkPump(); }
    catch (const exception& e) { cerr << e.what(); }
}
            

Exception Best Practices

  • Use exceptions only for real problems.
  • Clean up properly before exiting.
  • Keep code readable for beginners.
 

Summary

  • Try–catch blocks make programs safer.
  • Use meaningful error messages.
  • Validate farm data before processing.
 

Today’s Challenge: “Code Quest” 🎮

  1. Write 10 small C++ functions
  2. Each has conditions or loops
  3. Earn 10 points total
Game Theme

Code Quest 💡: Student Edition

1️⃣ Check Even or Odd


// Write a function checkEvenOdd(int n)
// Example:
// checkEvenOdd(4) → "Even"
// checkEvenOdd(7) → "Odd"

2️⃣ Sum of First N Numbers


// Write a loop to calculate sumN(int n)
// Example:
// sumN(3) → 1 + 2 + 3 = 6
// sumN(5) → 15

3️⃣ Find Maximum of Two


// Complete findMax(int a, int b)
// Example:
// findMax(10, 7) → 10
// findMax(-3, 5) → 5

4️⃣ Factorial Calculator


// Loop and multiply numbers from 1 to n
// Example:
// factorial(4) → 24
// factorial(0) → 1

5️⃣ Guessing Game


// Compare secret and guess using if-else
// Example:
// guessGame(5, 5) → "Correct!"
// guessGame(5, 2) → "Try again"

6️⃣ Countdown


// Print countdown from n to 0
// Example:
// countdown(3) → 3 2 1 0

7️⃣ Temperature Advice


// Use chained if statements for t
// Example:
// weatherMsg(5) → "Cold"
// weatherMsg(20) → "Warm"
// weatherMsg(30) → "Hot"

8️⃣ Multiplication Table


// Print 10 lines of n × i
// Example:
// table(3) → 
// 3 × 1 = 3
// 3 × 2 = 6
// ...
// 3 × 10 = 30

9️⃣ Sum of Digits


// Use modulo and division in a while loop
// Example:
// digitSum(123) → 6
// digitSum(505) → 10

🔟 Mini-Battle Score


// Add +10 for wins, -5 for losses in loop
// Example:
// Input: w, w, l, w, l
// Final score → 20

11️ Substring Finder


// Write a function findSubstring(string text, string word)
// Return true if 'word' appears inside 'text'
// (you may use a loop or text.find())

// Example:
// findSubstring("programming", "gram") → true
// findSubstring("hello world", "bye") → false

Code Quest 🎯: Sample Solutions

1️⃣ Check Even or Odd

  • Use if to check remainder

string checkEvenOdd(int n) {
    if (n % 2 == 0)
        return "Even";
    else
        return "Odd";
}

2️⃣ Sum of First N Numbers


int sumN(int n) {
    int sum = 0;
    for (int i = 1; i <= n; i++)
        sum += i;
    return sum;
}

3️⃣ Find Maximum of Two


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

4️⃣ Factorial Calculator


int factorial(int n) {
    int f = 1;
    for (int i = 1; i <= n; i++)
        f *= i;
    return f;
}

5️⃣ Guessing Game


string guessGame(int secret, int guess) {
    if (guess == secret)
        return "Correct!";
    else
        return "Try again";
}

6️⃣ Countdown


void countdown(int n) {
    while (n >= 0) {
        cout << n << " ";
        n--;
    }
}

7️⃣ Temperature Advice


string weatherMsg(int t) {
    if (t < 10) return "Cold";
    else if (t < 25) return "Warm";
    else return "Hot";
}

8️⃣ Multiplication Table


void table(int n) {
    for (int i = 1; i <= 10; i++)
        cout << n << " × " << i
             << " = " << n*i << endl;
}

9️⃣ Sum of Digits


int digitSum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

🔟 Mini-Battle Score


void miniBattle() {
    int score = 0;
    for (int i = 1; i <= 5; i++) {
        char result;
        cout << "Round " << i << " (w/l): ";
        cin >> result;
        if (result == 'w') score += 10;
        else score -= 5;
    }
    cout << "Final score: " << score;
}

11️⃣ Substring Finder


// Write a function findSubstring(string text, string word)
// Return true if 'word' appears inside 'text'
// (you may use a loop or text.find())

// Example:
// findSubstring("programming", "gram") → true
// findSubstring("hello world", "bye") → false

12️⃣ The substr() Function

  • Extracts part of a string
  • Syntax: string.substr(start, length)
  • If length is omitted → goes to end

#include <iostream>
#include <string>
using namespace std;

int main() {
    string word = "programming";
    cout << word.substr(0, 3) << endl;  // "pro"
    cout << word.substr(3, 4) << endl;  // "gram"
    cout << word.substr(7) << endl;    // "ming"
}

Practice: Extract a Word

  • Given a full sentence string
  • Use find() and substr()
  • Extract a specific word (like “world”)

// Example:
string text = "hello world";
int pos = text.find("world");
string result = text.substr(pos);  // "world"

✅ Solution: Substring Finder


#include <iostream>
#include <string>
using namespace std;

bool findSubstring(string text, string word) {
    if (text.find(word) != string::npos)
        return true;
    else
        return false;
}

// Example tests:
int main() {
    cout << boolalpha;
    cout << findSubstring("programming", "gram") << endl; // true
    cout << findSubstring("hello world", "bye") << endl;   // false
}

Today, Tuesday Nov 11th

  1. Recursion
  2. Project Review
  3. Module Review
  4. Homework, Lab
Exception Handling Concept

Recursion: The Concept

  • A function calling itself to solve smaller subproblems.
  • Each call handles a simpler case until a base case is reached.
  • Used in divide-and-conquer algorithms.
  • Stack frames grow with each call.

void greet(int n) {
    if (n == 0) return;
    cout << "Hello\n";
    greet(n - 1);
}
            

Base Case vs Recursive Case

  • Base case: stops recursion.
  • Recursive case: reduces problem size.
  • Without base case → infinite calls.

void countdown(int n) {
    if (n == 0) {
        cout << "Done!";
        return;
    }
    cout << n << " ";
    countdown(n - 1);
}
            

Recursion vs Loop

  • Both repeat actions.
  • Recursion uses function calls.
  • Loops use iteration (for, while).

// Recursion
void printR(int n) {
    if (n == 0) return;
    cout << n << " ";
    printR(n - 1);
}

// Loop
for(int i=n;i>0;i--) cout << i << " ";
            

Example: Factorial (n!)

  • Classic recursion example.
  • Each call computes n × (n−1)!
  • Base case: 0! = 1

int fact(int n) {
    if (n == 0) return 1;
    return n * fact(n - 1);
}
            

Example: Fibonacci Numbers

  • Each term = sum of two previous terms.
  • Recursive structure fits naturally.
  • High cost due to repeated calls.

int fib(int n) {
    if (n <= 1) return n;
    return fib(n-1) + fib(n-2);
}
            

Tail Recursion

  • Recursive call is the last operation.

void tailPrint(int n) {
    if (n == 0) return;
    cout << n << " ";
    tailPrint(n - 1);
}
            

Advantages of Recursion

  • Cleaner code for hierarchical tasks.
  • Useful for tree and graph traversal.
  • Natural fit for divide-and-conquer.

// Example: Tree traversal
void inorder(Node* root) {
    if (!root) return;
    inorder(root->left);
    cout << root->val << " ";
    inorder(root->right);
}
            

When to Use Recursion

  • When problem breaks to smaller identical parts.
  • When hierarchy or branching is involved.
  • Use loops when simple repetition suffices.

// Loop better for:
for (int i=0; i<1000; i++) doWork();

// Recursion better for:
searchTree(root);
            

In-Class Exercise: Recursive Search

  • Use an array of 50 integers (manually given).
  • Write a recursive function to find a target number.
  • Return the index if found, or -1 if not found.
  • Show only the function signature for now.

Question:
Write a recursive function
find(int arr[], int n, int target, int i)
that searches for target in a 50-element array.

Recursive Find Function (Array Data)

  • Array of 50 integers preloaded.
  • Only function signature shown.
  • Students complete logic themselves.

// Example dataset
int arr[50] = {
  2, 4, 7, 9, 12, 15, 18, 21, 24, 27,
  30, 33, 36, 39, 42, 45, 48, 51, 54, 57,
  60, 63, 66, 69, 72, 75, 78, 81, 84, 87,
  90, 93, 96, 99, 102, 105, 108, 111, 114, 117,
  120, 123, 126, 129, 132, 135, 138, 141, 144, 147
};

// Function signature
int find(int arr[], int n, int target, int i);
            

Recursive Binary Search

  • Divides array into halves each call.
  • Base case: range becomes invalid.
  • Midpoint checked each recursion.
  • O(log n) time complexity.

#include <iostream>
using namespace std;

int find(int arr[], int left, int right, int target) {
    if (left > right) return -1;       // base case
    int mid = (left + right) / 2;

    if (arr[mid] == target) return mid;
    if (target < arr[mid])
        return find(arr, left, mid - 1, target);
    else
        return find(arr, mid + 1, right, target);
}

int main() {
    int arr[50] = {
        2, 4, 7, 9, 12, 15, 18, 21, 24, 27,
        30, 33, 36, 39, 42, 45, 48, 51, 54, 57,
        60, 63, 66, 69, 72, 75, 78, 81, 84, 87,
        90, 93, 96, 99, 102, 105, 108, 111, 114, 117,
        120, 123, 126, 129, 132, 135, 138, 141, 144, 147
    };

    int target = 81;
    cout << "Found at index: " << find(arr, 0, 49, target);
}
            
Questions?

Rock–Paper–Scissors: Project Map

  • Goal: best of three vs computer.
  • Key pieces: input, random move, compare, scores.
  • Control flow: nested loops (rounds, replay).
  • Functions keep code clear and reusable.
// Headers and std setup
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;

// Forward look: functions handle small tasks
// - compMove(): random computer choice
// - checkPlayerMove(): validate input
// - compare(): who wins this turn?
// - standings & win checks: score and match end

Generating the Computer’s Move

  • Seed once with srand(time(0)).
  • rand()%3 → 0,1,2.
  • Map to Rock, Paper, Scissors.
  • Return a string choice.

// Returns "Rock", "Paper", or "Scissors"
string compMove() {
    string compMoveA;
    int randomNumber = rand() % 3; // 0..2
    switch (randomNumber) {
        case 0: compMoveA = "Rock";      break;
        case 1: compMoveA = "Paper";     break;
        case 2: compMoveA = "Scissors";  break;
    }
    return compMoveA;
}

Checking Player Input

  • Accept only exact words.
  • Return true if valid.
  • Else false and re-prompt.

// Ensures player typed a valid word
bool checkPlayerMove(string a) {
    bool okMove;
    if (a == "Rock" || a == "Paper" || a == "Scissors") {
        okMove = true;
    } else {
        okMove = false;
    }
    return okMove;
}

Who Wins a Round?

  • Inputs: computer, player.
  • All winning triples listed.
  • Return "computer", "player", or "tie".

// Returns which side wins this round
string compare(string comp, string player) {
    if ((comp=="Scissors" && player=="Paper") ||
        (comp=="Paper"    && player=="Rock")  ||
        (comp=="Rock"     && player=="Scissors")) {
        return "computer";
    } else if (comp == player) {
        return "tie";
    } else {
        return "player";
    }
}

Summaries and Scoreboard

  • Show choices each round.
  • Print current scores.
  • Small helpers keep main() clean.

// Prints chosen moves
void roundSummary(string player, string comp) {
    cout << "You chose " << player
         << ", the computer chose " << comp << '\n';
}

// Note: params are (player, computer) order
void currentStandings(int playerScore, int compScore) {
    cout << "Player- " << playerScore
         << " Computer- " << compScore << '\n';
}

Best-of-Three and Final Standings

  • Best of three → first to 2.
  • Return winner string.
  • Print final totals after a match.

// a = computer round wins, b = player round wins
string checkWin(int a, int b) {
    if (a == 2) return "Computer";
    if (b == 2) return "Player";
    return "nope"; // not yet decided
}

void finalStandings(int compTotal, int playerTotal) {
    cout << "Final scores:\n"
         << "Player- " << playerTotal
         << " Computer- " << compTotal;
}

main(): Setup

  • Seed RNG once at start.
  • Round scores vs total matches.
  • Flags for loops (play, keepGoing).

int main() {
    srand(time(0)); // seed random once

    int playerScoreR = 0, compScoreR = 0; // round scores
    int playerTotal  = 0, compTotal  = 0; // match totals

    string playerMove, compMoveCurrent, winner;
    char again;
    bool keepGoing = true; // replay loop
    bool play = true;      // per-match loop

    // We'll use nested while-loops next...

main(): Play One Match (Input)

  • Prompt for move each round.
  • Validate with checkPlayerMove.
  • Skip scoring if invalid.

while (keepGoing) {
    while (play) { // one best-of-three
        cout << "Make your move! (Rock, Paper, or Scissors)\n";
        cin  >> playerMove;

        if (checkPlayerMove(playerMove)) {
            compMoveCurrent = compMove(); // random computer move
            // ... resolve round (next slide)
        } else {
            cout << "That's not a move!\n";
        }

main(): Round Result & Scoring

  • Use compare() to decide.
  • Update round scores.
  • Print summaries each time.

        string outcome = compare(compMoveCurrent, playerMove);
        if (outcome == "player") {
            playerScoreR++;
            winner = "Player";
            roundSummary(playerMove, compMoveCurrent);
            currentStandings(playerScoreR, compScoreR);
        } else if (outcome == "computer") {
            compScoreR++;
            winner = "Computer";
            roundSummary(playerMove, compMoveCurrent);
            currentStandings(playerScoreR, compScoreR);
        } else {
            cout << "Players made the same move! No points!\n";
            currentStandings(playerScoreR, compScoreR);
        }

main(): Match End Check

  • When someone reaches 2, match ends.
  • Increment total matches won.
  • Exit inner loop (set play=false).

        // Did anyone win the best-of-three?
        string matchWinner = checkWin(compScoreR, playerScoreR);
        if (matchWinner == "Player" || matchWinner == "Computer") {
            cout << matchWinner << " wins!\n";
            if (matchWinner == "Player") {
                playerTotal++;
                cout << "Player Wins!";
            } else {
                compTotal++;
                cout << "Computer Wins!";
            }
            play = false; // end this match
        }
    } // end inner while (play)

main(): Reset & Play Again?

  • Reset round scores to 0.
  • Show running totals.
  • Ask to play another match.

    // Reset per-round scores for the next match
    playerScoreR = 0;
    compScoreR   = 0;

    // Show running totals across matches
    finalStandings(compTotal, playerTotal);

    // Replay prompt
    cout << "Round over! Would you like to play again? (Y/N)";
    char again;
    cin >> again;

    if (again == 'Y' || again == 'y') {
        play = true;       // start a new match
    } else {
        keepGoing = false; // exit outer loop
    }
}
return 0;
}

Suggestions and Small Improvements

  • Normalize input (capitalize first letter).
  • Guard invalid cin states.
  • Extract “play one round” into a function.
  • Replace magic 2 with a named constant.

// Example: named constant for match length
const int ROUNDS_TO_WIN = 2;

// Example: safe input (future exercise)
// if (!(cin >> playerMove)) { /* clear and re-prompt */ }

Today, Thursday Nov 13th

  1. Review Functions
  2. Review Namespaces
  3. Module Review
  4. Homework, Lab
Exception Handling Concept

Function Signature

  • The function’s name and parameter list form its signature.
  • Return type is not part of the signature.
  • The compiler matches calls using the signature.

int add(int a, int b);
// name: add, params: (int, int)

Parameters vs Arguments

  • Parameters are placeholders in the function definition.
  • Arguments are the actual values passed at the call site.

void greet(string name);   // parameter
greet("Alice");            // argument

Return Types

  • Every function specifies a return type.
  • void means no value is returned.
  • Return type guides how the function is used.

double square(double x) {
    return x * x;
}

Passing by Value

  • A copy of the argument is passed to the function.
  • Original data remains unchanged.

void test(int x) {
    x = 50; // affects only local copy
}

Passing by Reference

  • The function receives an alias of the argument.
  • Changes affect the original variable.

void update(int& x) {
    x = 50; // changes caller's variable
}

Constant Parameters

  • const prevents modification of the parameter.
  • Useful for large objects passed by reference.

int length(const string& s) {
    return s.size();
}

Default Parameters

  • Provide fallback values when arguments are omitted.
  • Placed at the end of the parameter list.

void log(string msg, int level = 1);

Function Overloading

  • Same name, different parameter lists.
  • Compiler chooses based on matching signature.

int sum(int a, int b);
double sum(double a, double b);

Variable Scope

  • Local variables exist only inside the function.
  • Global variables exist throughout the program.
  • Local names hide global names.

int x = 10;
void test() {
    int x = 5; // hides global x
}

Returning Multiple Values

  • A function returns one value directly.
  • Pairs, structs, or references allow more.

pair getPair() {
    return {3, 7};
}

Helper Functions

  • Small functions keep code readable.
  • Reduces repetition.
  • Makes testing easier.

bool isEven(int x) {
    return x % 2 == 0;
}

Function Documentation

  • Brief comments explain purpose.
  • Clarifies input and output expectations.
  • Helps future readers of the code.

// Returns true if n is prime
bool isPrime(int n) { ... }

Order of Parameters

  • The sequence of parameter types forms the signature.
  • Changing the order changes the signature.

void mix(int a, double b);
void mix(double b, int a); // different

Missing Return

  • Non-void functions must return a value.
  • Reaching the end without return is undefined.

int test() {
    // no return → unsafe
}

Why We Use Functions

  • Breaks programs into smaller tasks.
  • Makes code easier to read and maintain.
  • Encourages reuse of common logic.

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

What is a Namespace?

  • A way to group related names together.
  • Prevents naming conflicts in large programs.
  • Keeps functions, classes, and variables organized.
  • Accessed using scope resolution (::).

namespace mathTools {
    int add(int a, int b) {
        return a + b;
    }
}

int x = mathTools::add(3, 4);

The std Namespace

  • Holds the standard C++ library names.
  • Includes cout, cin, string, vector, and more.
  • Created to avoid collisions with user code.
  • Introduced with C++ standardization.

std::cout << "Hello";
std::string name = "Solo";
std::vector v = {1,2,3};

Brief History of std

  • Early C++ had no namespaces at all.
  • Library names sat in the global scope.
  • C++98 introduced namespaces to solve conflicts.
  • std created to hold all standard library names.
  • Helped unify code across compilers.

// Before namespaces
// cout lived in global scope

// After C++98
std::cout << "Now organized";

Using std with ::

  • Most common way to access names inside std.
  • Clear and avoids accidental conflicts.
  • Shows exactly where each name comes from.

std::cout << "Enter age: ";
int age;
std::cin >> age;

using namespace std

  • Brings all std names into the local scope.
  • Makes code shorter for small programs.
  • Not ideal for large projects.
  • Can cause naming collisions.

using namespace std;

cout << "Shorter to write";
string s = "Hello";

Selective Using

  • You can import only certain names.
  • Safer than using the whole namespace.
  • Keeps the code clear and clean.

using std::cout;
using std::string;

cout << "Clean style";
string name = "Solo";

Why std Matters

  • Organizes the entire standard library.
  • Makes code safer in large projects.
  • Supports development across decades.
  • Respects the tradition of clean structure.

std::vector data = {1,2,3};
std::sort(data.begin(), data.end());

1. Write a function that returns the absolute value of an integer.

  • Takes one integer.
  • Returns positive version.

int absolute(int n);

2. Write a function that counts how many vowels are in a string.

  • Input: string reference.
  • Returns number of vowels.

int countVowels(const std::string& text);

3. Write a function that returns true if a character is a digit.

  • One character input.
  • Checks 0–9.

bool isDigit(char c);

4. Write a function that returns the middle value of three integers.

  • Three integer inputs.
  • Returns the median.

int middleOfThree(int a, int b, int c);

5. Write a function that checks if a string ends with a period.

  • One string input.
  • Return true if last char is '.'.

bool endsWithPeriod(const std::string& s);

6. Write a function that multiplies all elements of an integer array by a constant factor.

  • Array pointer + size + factor.
  • No return value.

void scaleArray(int arr[], int size, int factor);

7. Write a function that returns the number of words in a sentence.

  • String input.
  • Count spaces + 1.

int wordCount(const std::string& s);

8. Write a function that returns whether an integer is within a given range.

  • Input: value, min, max.
  • Return true if min ≤ value ≤ max.

bool inRange(int value, int low, int high);

9. Write a function that returns a new string containing only uppercase characters from the original.

  • String input.
  • Return filtered uppercase copy.

std::string extractUpper(const std::string& s);

10. Write a function that swaps two integers by reference.

  • Two integer references.
  • No return value.

void swapValues(int& a, int& b);

Today, Thursday Nov 13th

  1. Review Functions
  2. Review Namespaces
  3. Module Review
  4. Homework, Lab
Functions Diagram

History of C

  • Developed at Bell Labs
  • Efficient for system programming
// Simple C function
int add(int a, int b){ return a + b; }

Question

What was C originally created for?

  • A) Games
  • B) System programming
  • C) Agriculture robots

History of C++

  • Created by Bjarne Stroustrup
  • Added classes to C
// C++ class intro
class Farm{}; Farm f;

Question

C++ extended C by adding…

  • A) Graphics
  • B) Classes
  • C) Crops

Compilation Flow

  • C++ → Assembly → Machine code
  • Handled by compiler toolchain
// Assembly sample
mov eax, edi
add eax, esi

Question

Which step comes right after C++ code?

  • A) Harvesting crops
  • B) Assembly code
  • C) Binary sensors

Basic I/O

  • cin for input
  • cout for output
int age;
cin >> age;
cout << age;

Question

Which object reads input?

  • A) cout
  • B) cin
  • C) tractor

Variables

  • Store values
  • Need a type
int cropCount = 10;

Question

Which is a valid variable?

  • A) 2corn
  • B) corn2
  • C) corn-amount

Multiple Declarations

  • Same type, many variables
int a, b, c;

Question

Which is correct?

  • A) int x, y;
  • B) float 2x;
  • C) char = 'A';

Initialization

  • Avoids garbage values
int moisture = 40;

Question

Why initialize?

  • A) Avoid garbage data
  • B) Faster tractors
  • C) Bigger files

Type Casting

  • Explicit and implicit
double y = (double)5;

Question

Explicit cast uses…

  • A) (type)
  • B) tractor
  • C) semicolon

Scope

  • Local vs global
int g=0; void f(){int x=5;}

Question

A local variable lives…

  • A) entire farm
  • B) inside block
  • C) until reboot

Strings

  • Store text
string crop = "Wheat";

Question

Access first letter with…

  • A) crop(0)
  • B) crop[0]
  • C) crop.first

Classes

  • Blueprint for objects
class Farmer{public:string name;};

Question

A class represents…

  • A) template
  • B) tractor wheel
  • C) kernel

OOP

  • Encapsulation
  • Inheritance
class Crop{}; class Corn: public Crop{};

Question

Inheritance means…

  • A) sharing fields
  • B) planting crops
  • C) reading files

Decision Making

  • If / else based on conditions
if(moisture>50) cout less than "Wet";

Question

Condition executes when…

  • A) true
  • B) false
  • C) random

For Loop

for(int i=0;i<5;i++) cout less than i;

Question

A for loop runs…

  • A) until condition false
  • B) forever

While Loop

while(x less than 5){x++;}

Question

While checks condition…

  • A) before
  • B) after

Do While

do{x++;}while(x less than 5);

Question

Do-while runs…

  • A) at least once
  • B) zero times

Nested Loops

for(r) for(c) print

Question

Nested loops are good for…

  • A) grids
  • B) tractors

Break / Continue

if(i==3) continue;

Question

continue means…

  • A) skip iteration
  • B) stop loop

Streams

// istream/ostream

Question

Which writes output?

  • A) ostream
  • B) farmland

Files

ofstream out("farm.txt");

Question

ofstream is for…

  • A) writing
  • B) harvesting

Formatted Output

setw(10)

Question

setw changes…

  • A) width
  • B) crop size

String Streams

istringstream ss("10 20");

Question

stringstream helps…

  • A) parse text
  • B) plant seeds

Exceptions

try{throw 1;}catch(...){}

Question

Exceptions prevent…

  • A) crashes
  • B) crop disease

Complexity

if(a>b)

Question

More paths means…

  • A) higher complexity
  • B) larger field

Course Wrap

  • All core C++ foundations covered
  • From variables to exceptions
// Mini agri example
if(moisture < 30){ cout<<"Irrigate"; }

Final Question

What should a program do when moisture is low?

  • A) Recommend irrigation
  • B) Print random numbers

Today, Thursday Nov. 20th

  1. Build a farm game
  2. Practice Final Exam
Agenda Image

1. Game setup: headers and basic structure.

  • Basic console input and output.
  • Store player names with string.
  • Single .cpp file for simplicity.
  • Declare functions before main().
  • Simple, reusable functions only.
  • Each round players pick a crop to earn coins.
  • Player with the most coins after all rounds wins.

This program uses a simple setup: a Farmer class to store each player’s name and coins, small helper functions to initialize farmers, show the crop menu, read a player’s choice, map that choice to a coin reward, run each round, and finally print the winner after all rounds. The signatures keep the structure clean so the game logic in main() stays easy to follow.

2. Explain the game setup and forward declarations.

  • #include <iostream> for cin / cout.
  • #include <string> to store farmer names.
  • using namespace std; to avoid writing std::.
  • Declarations specify functions and classes.
  • All functions in main() declared before main().

// Signantures and setup
class Farmer;
void initFarmer(Farmer& farmer, const string& name);
void printCropMenu();
int readCropChoice(const string& playerName);
int cropReward(int cropChoice);
int askNumberOfRounds();
void printRoundResult(const Farmer& p1, const Farmer& p2, int roundNumber);
void printFinalResult(const Farmer& p1, const Farmer& p2, int rounds);
void playSingleRound(Farmer& p1, Farmer& p2, int roundNumber);

3. Farmer building block: requirements and structure.

  • Each farmer needs a name.
  • Each farmer tracks total coins.
  • No complex methods, just data.
  • Use a simple C++ class.
  • Keep all data public to avoid getters/setters.

class Farmer {

};

4. Explain the Farmer class and its role.

  • Farmer groups together related data.
  • name: used when asking for choices and scores.
  • coins: starts at 0 and increases each round.
  • All data is public for simple access in this game.
  • No behavior inside the class;.

class Farmer {
public:
    string name;
    int coins;
};

5. Initialize a farmer: requirements and function signature.

  • Set the farmer’s name.
  • Set the initial coin count to 0.
  • Modify an existing Farmer object.
  • Do not create or return a new object.
  • Use reference so changes are visible to caller.

void initFarmer(Farmer& farmer, const string& name);

6. Initialize a farmer: implementation and logic.

  • Assign the provided name directly to farmer.name.
  • Reset farmer.coins to 0 at the start of every game.
  • Farmer& farmer passes the object by reference.
  • const string& name avoids copying the string.
  • This is a re-usable building block for any farmer.

void initFarmer(Farmer& farmer, const string& name) {
    farmer.name = name;
    farmer.coins = 0;
}

7. Crop menu: requirements and function signature.

  • Show all available crops and their rewards.
  • Use very simple reward values.
  • Use fixed integer choices (0, 1, 2).
  • Do not read any input here, only print.
  • Use a void function, no return value.
  • 0) Wheat +2, 1) Corn +3, 2) Cows +4 coins

void printCropMenu();

8. Crop menu: implementation and logic.

  • Print a short title so players know what to do.
  • Use one line per option for clarity.
  • Keep the rewards small and easy to remember.
  • Match numbers with the later input handling.
  • Use cout for all output.

void printCropMenu() {
    cout << "Choose your crop (enter the number):\n";
    cout << "  0 = Wheat (+2 coins)\n";
    cout << "  1 = Corn  (+3 coins)\n";
    cout << "  2 = Cows  (+4 coins)\n";
}

9. Read a crop choice: requirements and signature.

  • Ask one specific farmer for a choice.
  • Use the farmer’s name in the prompt.
  • Read an integer from the keyboard.
  • If input is outside [0, 2], fall back to 0 (Wheat).
  • Return the validated choice as an int.

int readCropChoice(const string& playerName);

10. Read a crop choice: implementation and validation.

  • Print a prompt that includes playerName.
  • Store the answer in a local int choice.
  • Check if choice is outside the valid range.
  • Print warning and correct invalid input to 0.
  • Return the final valid choice value.

int readCropChoice(const string& playerName) {
    int choice;
    cout << playerName << ", enter 0, 1, or 2: ";
    cin >> choice;

if (choice < 0 || choice > 2) {
    cout << "Invalid choice, using Wheat (0).\n";
    choice = 0;
}

return choice;

} 

11. Map crop choice to reward: requirements and signature.

  • Take a validated crop choice (0, 1, or 2).
  • Return the number of coins for that crop.
  • Use a simple mapping:
    • 0 → 2 coins
    • 1 → 3 coins
    • 2 → 4 coins
  • Keep the function pure: no input and no output.
  • Return an int with the reward.

int cropReward(int cropChoice);

12. Map crop choice to reward: implementation.

  • Use simple if statements (no complex logic).
  • Assume the input is already validated (0, 1, or 2).
  • Return 2 for Wheat, 3 for Corn, 4 for Cows.
  • Use a final else as a default for Cows.
  • Keep the function short and easy to read.

int cropReward(int cropChoice) {
    if (cropChoice == 0) {
        return 2; // Wheat
    }
    if (cropChoice == 1) {
        return 3; // Corn
    }
    return 4;     // Cows
}

13. Ask for number of rounds: requirements and signature.

  • Let the players decide how many rounds to play.
  • Read an integer from the keyboard.
  • Enforce range, for example 1 to 10 rounds.
  • If input is outside range, use a default value (3).
  • Return the final number of rounds as an int.

int askNumberOfRounds();

14. Ask for number of rounds: implementation and range checking.

  • Print a prompt that explains the allowed range.
  • Read the user input into a local variable.
  • Check if it is smaller than 1 or larger than 10.
  • If invalid, print a message and set it to 3.
  • Return the chosen number of rounds.

int askNumberOfRounds() {
    int rounds;
    cout << "How many rounds do you want to play (1-10)? ";
    cin >> rounds;

if (rounds < 1 || rounds > 10) {
    cout << "Invalid number, using 3 rounds.\n";
    rounds = 3;
}

return rounds;

} 

15. Print the result after each round: requirements and signature.

  • Show which round just finished.
  • Show both farmers’ current coin totals.
  • Do not change any values; only print.
  • Use const Farmer& to avoid copying.
  • Return nothing (type void).

void printRoundResult(const Farmer& p1,
                      const Farmer& p2,
                      int roundNumber);

16. Print the result after each round: implementation.

  • Print a small header for the round.
  • Display farmer’s name/coins on separate lines.
  • Use const Farmer& because we only read data.
  • Keep the output format consistent every round.
  • Provide blank line for readability after scores.

void printRoundResult(const Farmer& p1,
                      const Farmer& p2,
                      int roundNumber) {
    cout << "\n=== End of round "
         << roundNumber << " ===\n";
    cout << p1.name << " has "
         << p1.coins << " coins.\n";
    cout << p2.name << " has "
         << p2.coins << " coins.\n\n";
}

17. Print final result and winner: requirements and signature.

  • Show the total number of rounds played.
  • Print each farmer’s final coin count.
  • Announce the winner or a draw.
  • Use const Farmer& for both farmers.
  • Return nothing (type void).

void printFinalResult(const Farmer& p1,
                      const Farmer& p2,
                      int rounds);

18. Print final result and winner: implementation.

  • Print a clear final header.
  • Show both farmers’ total coins.
  • Compare the two values.
  • If one is larger, declare that farmer the winner.
  • If they are equal, print that it is a draw.

void printFinalResult(const Farmer& p1,
                      const Farmer& p2,
                      int rounds) {
    cout << "\n=== Final result after "
         << rounds << " rounds ===\n";
    cout << p1.name << ": "
         << p1.coins << " coins\n";
    cout << p2.name << ": "
         << p2.coins << " coins\n";

if (p1.coins > p2.coins) {
    cout << p1.name
         << " wins the farm game!\n";
} else if (p2.coins > p1.coins) {
    cout << p2.name
         << " wins the farm game!\n";
} else {
    cout << "It is a draw.\n";
}

} 

19. Play a single round: requirements and signature.

  • Print the round header.
  • Show the crop menu once.
  • Ask each farmer to choose a crop.
  • Update both farmers’ coin totals.
  • Call printRoundResult at the end of the round.

void playSingleRound(Farmer& p1,
                     Farmer& p2,
                     int roundNumber);

20. Play a single round: implementation and flow.

  • Print a header such as “Round 1”.
  • Call printCropMenu() once.
  • Call readCropChoice for each farmer.
  • Compute each reward using cropReward.
  • Add rewards to each farmer and show result.

void playSingleRound(Farmer& p1,
                     Farmer& p2,
                     int roundNumber) {
    cout << "\n=== Round "
         << roundNumber << " ===\n";
    printCropMenu();

int choice1 = readCropChoice(p1.name);
int choice2 = readCropChoice(p2.name);

int reward1 = cropReward(choice1);
int reward2 = cropReward(choice2);

p1.coins += reward1;
p2.coins += reward2;

printRoundResult(p1, p2, roundNumber);

} 

21. Main game loop: requirements and signature.

  • Ask for both farmers’ names.
  • Initialize each Farmer with 0 coins.
  • Ask for the number of rounds.
  • Run a for loop calling playSingleRound.
  • Call printFinalResult at the end.

int main();

22. Main game loop: full implementation.

  • Read names using getline to accept spaces.
  • Use initFarmer to set name and coins.
  • Call askNumberOfRounds once.
  • Loop from 1 to rounds and call playSingleRound.
  • Finally, call printFinalResult and return 0.

int main() {
    Farmer p1;
    Farmer p2;

cout << "Enter name for Farmer 1: ";
getline(cin, p1.name);
if (p1.name.empty()) {
    p1.name = "Farmer 1";
}

cout << "Enter name for Farmer 2: ";
string name2;
getline(cin, name2);
if (name2.empty()) {
    name2 = "Farmer 2";
}

initFarmer(p1, p1.name);
initFarmer(p2, name2);

int rounds = askNumberOfRounds();

for (int r = 1; r <= rounds; ++r) {
    playSingleRound(p1, p2, r);
}

printFinalResult(p1, p2, rounds);

return 0;

} 

Today, Tuesday Nov. 25th

  1. Thanksgiving dinner
Agenda Image

Exam Structure

Tuesday, Dec. 9, 3PM

  1. Dec. 9th at 3PM in Baun 214
  2. 20 total questions
  3. 18 multiple choice and 2 written questions
  4. Each module contributes 1–2 questions
  5. Exam duration: 1hour 20min
  6. Paper exam, closed book
  7. Bring pens only
  8. One paper page summary sheet (both sides)

How to Prepare

1. Function 1 – printWelcome: explanation.

Print a simple Thanksgiving banner. No parameters and no return value. Called at the start of the program.

void printWelcome();

2. Function 1 – printWelcome: implementation.

Prints several decorative lines. Only outputs text. No input or logic required.

void printWelcome() {
    cout << "==============================\n";
    cout << "  Thanksgiving Dinner Planner \n";
    cout << "==============================\n\n";
}

3. Function 2 – askHostName: explanation.

Asks the host for their name. Accepts full names including spaces. Returns the final name as text.

string askHostName();

4. Function 2 – askHostName: implementation.

Reads a line of text. Uses a default name if empty. Returns the chosen name.

string askHostName() {
    cout << "What is your name (the host)? ";
    string name;
    getline(cin, name);

    if (name.empty()) {
        name = "Host";
    }

    cout << "Welcome, " << name << "!\n\n";
    return name;
}

5. Function 3 – askGuestCount: explanation.

Asks how many guests will come. Valid range is 1 to 20. Defaults to 4 if invalid.

int askGuestCount();

6. Function 3 – askGuestCount: implementation.

Reads a number. Checks the allowed range. Returns the corrected result.

int askGuestCount() {
    cout << "How many guests will come (1-20)? ";
    int guests;
    cin >> guests;

    if (guests < 1 || guests > 20) {
        cout << "Number out of range, using 4 guests.\n";
        guests = 4;
    }

    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    return guests;
}

7. Function 4 – askDishCount: explanation.

Asks how many dishes will be prepared. Valid range is 1 to 15. Uses default 5 when invalid.

int askDishCount();

8. Function 4 – askDishCount: implementation.

Reads and validates the number of dishes. Ensures it is within the allowed range. Returns the final count.

int askDishCount() {
    cout << "How many different dishes (1-15)? ";
    int count;
    cin >> count;

    if (count < 1 || count > 15) {
        cout << "Number out of range, using 5 dishes.\n";
        count = 5;
    }

    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    return count;
}

9. Function 5 – askDishName: explanation.

Asks for one dish name. Accepts spaces in the name. Uses a default like “Dish 1” if empty.

string askDishName(int index);

10. Function 5 – askDishName: implementation.

Reads a full line. Checks for empty input. Returns safe dish name.

string askDishName(int index) {
    cout << "Enter name for dish " << index << ": ";
    string name;
    getline(cin, name);

    if (name.empty()) {
        name = "Dish " + to_string(index);
    }

    return name;
}

11. Function 6 – collectDishes: explanation.

Collects several dish names. Calls askDishName repeatedly. Stores each result in a list.

vector<string> collectDishes(int count);

12. Function 6 – collectDishes: implementation.

Loops from 1 to the dish count. Reads each name. Returns the vector of dishes.

vector<string> collectDishes(int count) {
    vector<string> dishes;

    for (int i = 1; i <= count; ++i) {
        string dish = askDishName(i);
        dishes.push_back(dish);
    }

    return dishes;
}

13. Function 7 – printMenu: explanation.

Prints all dishes in order. Shows dish numbers. Output only, no return value.

void printMenu(const vector<string>& dishes);

14. Function 7 – printMenu: implementation.

Loops through dish list. Prints each dish on its own line. Adds a small header.

void printMenu(const vector<string>& dishes) {
    cout << "\nThanksgiving Menu:\n";

    for (size_t i = 0; i < dishes.size(); ++i) {
        cout << "  " << (i + 1) << ". " << dishes[i] << "\n";
    }

    cout << "\n";
}

15. Function 8 – pickRandomDish: explanation.

Selects one dish at random. Requires the dish list. Returns one dish name.

string pickRandomDish(const vector<string>& dishes);

16. Function 8 – pickRandomDish: implementation.

Computes a random index. Returns the dish at that index. Handles empty list safely.

string pickRandomDish(const vector<string>& dishes) {
    if (dishes.empty()) {
        return "No dishes available";
    }

    int index = rand() % dishes.size();
    return dishes[index];
}

17. Function 9 – estimateTurkeySize: explanation.

Estimates turkey amount needed. Uses pounds per guest rule. Returns the total pounds.

double estimateTurkeySize(int guestCount);

18. Function 9 – estimateTurkeySize: implementation.

Multiplies guest count by constant. Returns the computed weight. No printing done here.

double estimateTurkeySize(int guestCount) {
    const double poundsPerGuest = 1.5;
    double total = guestCount * poundsPerGuest;
    return total;
}

19. Function 10 – printDinnerSummary: explanation.

Prints host name, guest count, and turkey size. Summarizes the core dinner plan. No return value.

void printDinnerSummary(const string& host,
                        int guests,
                        double turkey);

20. Function 10 – printDinnerSummary: implementation.

Prints a clear header. Shows the three pieces of information. Ends with a blank line.

void printDinnerSummary(const string& host,
                        int guests,
                        double turkey) {
    cout << "\nDinner summary\n";
    cout << "Host: " << host << "\n";
    cout << "Guests: " << guests << "\n";
    cout << "Turkey: " << turkey
         << " pounds (approx.)\n\n";
}

21. Function 11 – Guest class: explanation.

Stores basic guest info. Includes name and turkey preference. Simple structure for beginners.

class Guest {
public:
    string name;
    bool eatsTurkey;
};

22. Function 11 – Guest class: small usage example.

Shows how to create and fill a Guest. Name is text, eatsTurkey is true or false. Can be stored in a vector.

Guest g;
g.name = "Alice";
g.eatsTurkey = true;

23. Function 12 – readGuest: explanation.

Reads a single guest. Collects name and turkey preference. Returns a Guest object.

Guest readGuest(int index);

24. Function 12 – readGuest: implementation.

Reads name with full line input. Asks y/n for turkey preference. Cleans up the input buffer.

Guest readGuest(int index) {
    Guest g;

    cout << "Guest " << index << " name: ";
    getline(cin, g.name);
    if (g.name.empty()) {
        g.name = "Guest " + to_string(index);
    }

    cout << "Does " << g.name
         << " eat turkey (y/n)? ";
    char answer = 'y';
    cin >> answer;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    g.eatsTurkey = (answer == 'y' || answer == 'Y');
    return g;
}

25. Function 13 – printGuestTurkeyChoices: explanation.

Prints each guest’s turkey preference. Loops over the list of Guests. Output only.

void printGuestTurkeyChoices(
    const vector<Guest>& guests);

26. Function 13 – printGuestTurkeyChoices: implementation.

Iterates through the vector. Prints the correct message for each guest. Ends with blank line.

void printGuestTurkeyChoices(
    const vector<Guest>& guests) {
    cout << "\nTurkey choices:\n";

    for (size_t i = 0; i < guests.size(); ++i) {
        const Guest& g = guests[i];
        if (g.eatsTurkey) {
            cout << g.name
                 << " will eat turkey.\n";
        } else {
            cout << g.name
                 << " prefers side dishes.\n";
        }
    }

    cout << "\n";
}

27. Function 14 – playRandomSuggestion: explanation.

Suggests one random dish for fun. Uses pickRandomDish internally. No return value.

void playRandomSuggestion(
    const vector<string>& dishes);

28. Function 14 – playRandomSuggestion: implementation.

Checks if there are any dishes. Calls pickRandomDish. Prints the random result.

void playRandomSuggestion(
    const vector<string>& dishes) {
    if (dishes.empty()) {
        cout << "No dishes to suggest.\n";
        return;
    }

    string suggestion = pickRandomDish(dishes);
    cout << "Random dish suggestion: "
         << suggestion << "\n";
}

29. Function 15 – mainGameFlow: explanation.

Connects all earlier functions. Reads host and guests. Collects dishes. Prints menu and summary, plus a random suggestion.

int main();

30. Function 15 – mainGameFlow: implementation.

Seeds randomness. Calls all helper functions in order. Ends the program cleanly.

int main() {
    srand(static_cast<unsigned int>(time(NULL)));

    printWelcome();

    string host = askHostName();

    int guestCount = askGuestCount();
    int dishCount = askDishCount();

    vector<Guest> guests;
    for (int i = 1; i <= guestCount; ++i) {
        Guest g = readGuest(i);
        guests.push_back(g);
    }
    printGuestTurkeyChoices(guests);

    vector<string> dishes = collectDishes(dishCount);
    printMenu(dishes);

    double turkey = estimateTurkeySize(guestCount);
    printDinnerSummary(host, guestCount, turkey);

    playRandomSuggestion(dishes);

    return 0;
}

Today, Tuesday Dec. 2nd

  1. bool isCoffeeHot(double temperature);
  2. int grindBeans(int grams);
  3. double brewCoffee(int strengthLevel);
  4. void addMilk(double amount);
  5. string selectBeanType(int choice);
  6. bool isCupFull(int currentLevel);
  7. double calculateCaffeine(int shots);
  8. void warmCup();
  9. string roastLevelDescription(string level);
  10. int refillWaterTank(int currentLevel);
Agenda Image

bool isCoffeeHot(double temperature);

  • Return true if temperature is above a hot threshold (for example 60.0)
  • Return false otherwise
  • Temperature is given in degrees Celsius
  • Do not modify the parameter value

// Example
double t1 = 72.5;
double t2 = 45.0;

bool hot1 = isCoffeeHot(t1);  // true
bool hot2 = isCoffeeHot(t2);  // false
            

int grindBeans(int grams);

  • Parameter grams is the amount of beans put in the grinder
  • Return the number of cups that can be brewed from this amount
  • Assume a fixed ratio (for example 10 grams per cup)
  • For values less than one cup, return 0

// Example
int cups1 = grindBeans(25);  // 2
int cups2 = grindBeans(7);   // 0
            

double brewCoffee(int strengthLevel);

  • strengthLevel is an integer from 1 (mild) to 5 (strong)
  • Return the brewing time in minutes
  • Higher strengthLevel means longer brewing time
  • If strengthLevel is outside 1–5, clamp to the nearest valid value

// Example
double tMild   = brewCoffee(1);  // e.g. 3.0
double tStrong = brewCoffee(5);  // e.g. 6.0
double tClamp  = brewCoffee(8);  // treated as 5
            

void addMilk(double amount);

  • amount is given in milliliters
  • Add the given amount of milk to the current cup
  • If amount is negative, add nothing
  • Print or log the new total milk amount in the cup

// Example
addMilk(30.0);   // "Added 30 ml of milk"
addMilk(-10.0);  // ignored, no change
            

std::string selectBeanType(int choice);

  • choice is a menu number from 1 to 3
  • 1 = "Arabica", 2 = "Robusta", 3 = "Blend"
  • Return "Unknown" for any other value
  • Function does not print anything, it only returns the name

// Example
std::string a = selectBeanType(1);  // "Arabica"
std::string r = selectBeanType(2);  // "Robusta"
std::string x = selectBeanType(9);  // "Unknown"
            

bool isCupFull(int currentLevel);

  • currentLevel is the fill level in milliliters
  • Assume the cup capacity is 250 ml
  • Return true if currentLevel is greater than or equal to capacity
  • Return false otherwise

// Example
bool full1 = isCupFull(180);  // false
bool full2 = isCupFull(260);  // true
            

double calculateCaffeine(int shots);

  • shots is the number of espresso shots
  • Assume one shot has 80 mg of caffeine
  • Return the total caffeine amount in milligrams
  • If shots is negative, treat it as 0

// Example
double c1 = calculateCaffeine(1);   // 80.0
double c2 = calculateCaffeine(3);   // 240.0
double c3 = calculateCaffeine(-1);  // 0.0
            

void warmCup();

  • No parameters
  • Simulate warming the cup with hot water
  • May print messages such as "Warming cup..."
  • Does not return a value

// Example
warmCup();  // "Warming cup..." then "Cup is warm."
            

std::string roastLevelDescription(std::string level);

  • level is a word such as "light", "medium", or "dark"
  • Return a short description for the given level
  • Ignore case when comparing level
  • Return "Unknown roast level" for any other value

// Example
std::string d1 = roastLevelDescription("light");
// "Bright and mild flavor"

std::string d2 = roastLevelDescription("dark");
// "Bold flavor with stronger bitterness"
            

int refillWaterTank(int currentLevel);

  • currentLevel is the current water level in milliliters
  • Assume the tank capacity is 2000 ml
  • Return how many milliliters must be added to reach full capacity
  • If currentLevel is already above capacity, return 0

// Example
int add1 = refillWaterTank(500);   // 1500
int add2 = refillWaterTank(2100);  // 0
            

Questions?

Thanks

Course Syllabus – Fall 2025

  • Course Code: COMP 051
  • Units: 3
  • Time: Tue/Thu 03:00–04:45 PM
  • Location: Baun Hall 214

Instructor & TA

  • Instructor: Dr. Berhe, CTC 117
    Email: sberhe@pacific.edu
  • TA: Daniel Ming
    Email: d_ming@u.pacific.edu
    Office Hours: TBD

Course Resources

Course Description

This course provides an introduction to programming with C++, covering both procedural and object-oriented approaches. Students begin with the fundamentals of variables, control flow, loops, arrays, and functions, then progress to advanced topics such as classes, inheritance, pointers, recursion, and exception handling.

Course Topics

  • Introduction to C++
  • Variables and Assignments
  • Branches (Conditionals)
  • Loops
  • Arrays and Vectors
  • User-Defined Functions
  • Objects and Classes
  • Inheritance
  • Streams (I/O)
  • Recursion
  • Pointers
  • Exceptions

Course Goals by Terms

C++, Compiler, Linker, Variables, Data Types, Constants, Operators, Assignments, Expressions, Conditionals, Branches, If/Else, Switch, Loops, For, While, Do-While, Arrays, Vectors, Strings, Functions, Parameters, Return Values, Scope, Objects, Classes, Encapsulation, Constructors, Destructors, Inheritance, Polymorphism, Virtual Functions, Streams, cin, cout, File I/O, Recursion, Call Stack, 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.

Grading Schema

  • Attendance: 5%
  • Homework: 15%
  • Labs: 15%
  • Project: 30%
  • Midterm Exam: 15%
  • Final Exam: 20% (cumulative)

Policies

  • Late Work: 20% penalty; extensions only if requested before deadline by email.
  • Attendance: Required and tracked; email in advance if absent.
  • Collaboration & AI: Collaboration allowed on labs; work must be your own. AI tools allowed if you understand the output.

University Policies

  • ADA Accommodations: Contact SSD (ssd@pacific.edu).
  • Honor Code: Academic honesty required; violations reported.
  • Assessment: Student work may be retained for program evaluation.
  • Support Services: Tutoring, Writing Center, Care Managers.