Unit 4: Looping

Unit 1: Introduction to Programming and Basic C++ Structure

  • History and Evolution of C++

    • The C programming language originated from the B language, which was developed as a simplified version of BCPL (Basic Combined Programming Language).
    • C was developed by Dennis Ritchie at AT&T Bell Labs in the 1970s primarily to construct and maintain UNIX systems.
    • C++ was developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s to overcome several shortcomings of C and incorporate object-oriented programming paradigms.
    • The name "C++" uses the C increment operator (++) to symbolize that it is an enhanced, next-generation version of C. C remains a valid subset of C++.
  • Why C++ is Used

    • Highly versatile, efficient, and known for performance and low-level memory control.
    • Combines procedural and object-oriented programming paradigms for modular, reusable code.
    • Widely used in system/software development, game engines, embedded systems, and competitive programming.
  • Core Terminology & Definitions

    • Programming: The overarching process of formulating and solving problems using computer code.
    • Programming Language: A defined set of rules, symbols, and special keywords used to construct software.
    • Algorithm: A step-by-step problem-solving procedure that arrives at a correct solution in a finite amount of time.
    • Source Program: Program code written in a high-level language like C++.
    • Preprocessor Directives: Statements beginning with # (e.g., #include <iostream>) processed before compilation.
    • Object Program: The equivalent machine-language program produced by compiling source code.
    • Library: A pre-compiled repository containing standard helper routines and functions.
    • Linker: A tool that combines the object program with required library binaries into an executable.
    • Loader: A system utility that loads an executable binary file into main memory (RAM) for execution.
  • The C++ Program Processing Pipeline

    1. Editor: Writing and saving C++ source code files (Step 1).
    2. Preprocessor: Handling directives starting with # before compilation (Step 2).
    3. Compiler: Translating source code into machine-language object code. If syntax errors exist, execution halts and returns to the Editor (Step 3).
    4. Linker: Combining object code with pre-compiled standard library binaries (Step 4).
    5. Loader: Placing the final executable code into main system memory (Step 5).
    6. Execution: The computer processor executes the program instructions line by line (Step 6).

Processing a C++ program

  • Anatomy of a C++ Source File
    • Preprocessor directives (e.g., #include <iostream>, #include <conio.h>) load header files.
    • Definition/Declaration section establishes namespaces (using namespace std;).
    • int main() represents the main entry point where execution begins.
    • Opening brace { and closing brace } define block scopes.
    • return 0; signals successful program completion back to the operating system.

Structure of a C++ Program

  • Variables, Identifiers, Keywords, and Constants
    • Variables: Named locations in memory. Metaphorically like small blackboards where values can be written and updated, though computer memory locations always contain some data and are never truly empty.
    • Identifiers: User-defined names for variables and functions. Rules:
    • Must begin with a letter or an underscore (_).
    • Remaining characters can be letters, digits, or underscores.
    • Must be meaningful names representing data stored.
    • Keywords (Reserved Words): Words predefined by C++ (e.g., int, double, return, const) that cannot be used as user identifiers.
    • Constants: Variables defined using const whose values cannot be altered after declaration. Constants must be assigned a value immediately upon declaration.
#include <iostream>
using namespace std;

int main() {
    int radius = 20;
    const double PI = 3.1416;
    float area = PI * (radius * radius);
    cout << "Area is " << area << endl;
    return 0;
}
  • Primitive Data Types in C++

    • int: Holds whole integer values without decimals (e.g., int age = 20;).
    • float: Single-precision floating-point numbers (e.g., float grade = 89.5;).
    • double: Double-precision floating-point numbers offering higher accuracy than float (e.g., double pi = 3.14159;).
    • char: Single characters enclosed in single quotes (e.g., char grade = 'A';).
    • bool: Boolean logic flags (true or false) (e.g., bool isPass = true;).
    • void: Denotes "no value", used primarily as return types for functions that perform actions without returning values.
  • Assignment Statements and Compound Assignment

    • Basic assignment uses =: assigns the value on the right to the variable on the left.
    • Compound assignments perform an operation and update the variable directly:
    • x += 5; is equivalent to x=x+5x = x + 5
    • y -= 3; is equivalent to y=y−3y = y - 3
    • z *= 2; is equivalent to z=z×2z = z \times 2
    • a /= 4; is equivalent to a=a/4a = a / 4
    • b %= 2; is equivalent to b=b%2b = b \% 2
  • Type Conversion and Casting

    • Implicit Conversion (Type Promotion/Coercion): Automatic promotion by the compiler when performing operations across compatible types (e.g., double result = num / 2.0;).
    • Explicit Conversion (Casting): Manual type conversion using (type)value. Casting from floating-point types to integers truncates decimal digits completely without rounding.
#include <iostream>
using namespace std;

int main() {
    double d = 7.9;
    int i = (int)d; // Explicit cast: truncates decimal part, storing 7 in i
    cout << "Double: " << d << endl;
    cout << "After casting to int: " << i << endl;
    return 0;
}
  • Input and Output Operations

    • Output is performed using cout << (stream insertion operator).
    • Standard input uses cin >> (stream extraction operator), which extracts input up to whitespace.
    • Unformatted string input using getline(cin, fullName) captures complete lines including spaces.
    • Buffer clearing routines (cin.ignore() or cin.ignore(numeric_limits<streamsize>::max(), ' ')) clear lingering newline characters left in the input buffer prior to invoking getline().
  • Practical Assignments Requirements

    1. Print block letters "I T !" inside a border of asterisks (*), followed by two blank lines and the statement "Information Technology is Cool Stuff".
    2. Prompt users for first name, middle name, and last name using word-by-word cin extraction into separate string variables (without getline()), displaying the full name on a single line (e.g., output: Your Name is Karen Madoline Abancio Cabrillos).

Unit 2: Basic Programming Constructs, Operators, and Control Flow

  • Expressions and Operands
    • An expression combines operands (variables, literals) and operators to evaluate to a value.
    • Arithmetic Expressions: Evaluate mathematical calculations (e.g., a+b×ca + b \times c).
    • Relational Expressions: Compare values to evaluate truth (e.g., x>yx > y).
    • Logical Expressions: Evaluate logical truth flags (e.g., (x>0 & & y>0)(x > 0 \,\&\,\&\, y > 0)).

Operand vs. operator

  • Classification of Operators

    • Arithmetic Operators: + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulo/Remainder).
    • Relational Operators: == (Equal to), != (Not equal to), < (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to). Results evaluate to 1 (true) or 0 (false).
    • Logical Operators: && (AND), || (OR), ! (NOT).
  • Binary Numbers and Bitwise Operations

    • Computers store all data in binary (Base 2 using bits 0 and 1).
    • Binary literals can be written directly in C++ code using the 0b prefix (e.g., int a = 0b1010; represents 10).
    • Binary formatting output can be inspected using #include <bitset> with bitset<8>(num).
    • Bitwise Operators (acting directly on corresponding bits):
    • & (Bitwise AND): a & ba \,\&\, b outputs 1 only if both bits are 1.
    • | (Bitwise OR): a∣ba \mid b outputs 1 if at least one bit is 1.
    • ^ (Bitwise XOR): a∧ba \wedge b outputs 1 if bits differ.
    • ~ (Bitwise NOT): ∼a\sim a inverts all bits.
    • << (Left Shift): a<<1a << 1 shifts bits left (multiplies integer value by 2).
    • >> (Right Shift): a>>1a >> 1 shifts bits right (divides integer value by 2).
#include <iostream>
#include <bitset>
using namespace std;

int main() {
    int a = 5; // Binary: 0101
    int b = 3; // Binary: 0011
    cout << "a & b: " << bitset<4>(a & b) << endl; // 0001 (1)
    cout << "a | b: " << bitset<4>(a | b) << endl; // 0111 (7)
    cout << "a ^ b: " << bitset<4>(a ^ b) << endl; // 0110 (6)
    cout << "a << 1: " << bitset<4>(a << 1) << endl; // 1010 (10)
    cout << "a >> 1: " << bitset<4>(a >> 1) << endl; // 0010 (2)
    return 0;
}
  • Operator Precedence and Associativity
    • Precedence: Establishes which operator evaluates first in complex expressions. Higher precedence operators execute before lower precedence operators.
    • Order Rules (PEMDAS):
    1. Parentheses () first (innermost to outermost).
    2. Exponents.
    3. Multiplication (*), Division (/), and Modulo (%) from left to right.
    4. Addition (+) and Subtraction (-) from left to right.
    • Associativity: Specifies execution direction (left-to-right or right-to-left) when multiple operators share identical precedence.
    • Left-to-right evaluation example: 10/2×5=(10/2)×5=5×5=2510 / 2 \times 5 = (10 / 2) \times 5 = 5 \times 5 = 25.
    • Right-to-left evaluation example: Assignment statements (x=y=5x = y = 5).
    • Expression example: 5+2×3−4/2=5+6−2=95 + 2 \times 3 - 4 / 2 = 5 + 6 - 2 = 9.

Rules of the Order of Operations

  • Modes of Control Flow in Programs

    • Sequential Flow: Default execution line by line from top to bottom.
    • Decision-Making (Branching): Selective execution paths based on evaluated conditions (if, if-else, switch).
    • Iteration (Looping): Repetitive execution cycles that loop execution back to prior steps (for, while, do-while).
    • Jump Statements: Direct transfer of control immediately (break, continue, goto, return).
  • Flowcharts: Visual Logic Modeling

    • A flowchart is a language-independent visual blueprint representing algorithmic steps.
    • Standard Flowchart Symbols:
    • Oval: Start / End points.
    • Rectangle: Process steps (calculations, variable assignments).
    • Diamond: Decisions / Conditions.
    • Parallelogram: Input / Output operations.
    • Arrow: Flow lines indicating execution direction.

Flowchart Symbols Table

  • Pseudocode Design Principles
    • High-level, language-agnostic algorithm descriptions combining English phrases with programming structures.
    • General Rules:
    • Write clear English statements.
    • Use indentation to depict nesting and scope hierarchy.
    • Capitalize keywords: BEGIN, END, IF...THEN...ELSE, WHILE, FOR, INPUT, OUTPUT.
    • Avoid language-specific syntax (omit semicolons, curly braces, and headers).
BEGIN
    INPUT a, b
    IF a > b THEN
        PRINT "A is greater"
    ELSE
        PRINT "B is greater"
    ENDIF
END

Unit 3: Decision Making Control Structures

  • Fundamentals of Decision Making
    • Allows software to dynamically evaluate condition expressions and branch along different execution paths.
    • Leverages Boolean expressions that evaluate strictly to 1 (true) or 0 (false).
#include <iostream>
using namespace std;

int main() {
    int x = 10, y = 20;
    cout << (x == y) << endl; // 0 (false)
    cout << (x < y) << endl;  // 1 (true)
    cout << (x != y) << endl; // 1 (true)
    cout << ((x < y) && (y > 15)) << endl; // 1 (true)
    cout << ((x > y) || (y > 15)) << endl; // 1 (true)
    return 0;
}
  • The if Statement
    • Executes a designated block of code only when the condition evaluates to true; skips the block entirely if false.
    • Metaphor: Checking weather—if raining, take an umbrella.

If Statement Flowchart

  • The if-else Statement
    • Provides two explicit execution branches: the if block executes when the condition is true, while the else block executes when false.
    • Metaphor: Checking weather—if raining, bring an umbrella; else, wear sunglasses.

If-Else Statement Flowchart

  • Nested if-else Statements
    • Places if or if-else structures inside outer conditional blocks to perform multi-stage logical evaluations.
    • Metaphor: Building security—first checking if a visitor has an ID, then checking if they hold a valid visitor pass.
#include <iostream>
using namespace std;

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

    if (score >= 0 && score <= 100) {
        if (score >= 90) {
            cout << "Grade: A" << endl;
        } else if (score >= 75) {
            cout << "Grade: B" << endl;
        } else if (score >= 50) {
            cout << "Grade: C" << endl;
        } else {
            cout << "Grade: F" << endl;
        }
    } else {
        cout << "Invalid score entered." << endl;
    }
    return 0;
}

Nested If-Else Flowchart

  • The switch Statement
    • Evaluates a single integral/character expression against fixed match values labeled as case options.
    • Clean alternative to extensive if-else if chains.
    • Uses break to exit the structure after executing a matching case, and an optional default block when no match occurs.
    • Metaphor: TV remote control—pressing button 1 opens channel 1, button 2 opens channel 2, and unassigned buttons open a default screen.
#include <iostream>
using namespace std;

int main() {
    int num = 2;
    switch (num) {
        case 1: cout << "One"; break;
        case 2: cout << "Two"; break;
        case 3: cout << "Three"; break;
        default: cout << "Other number";
    }
    return 0;
}

Switch Statement Flowchart

Unit 4: Looping and Iteration Control Structures

  • Introduction to Loops and Concept of Repetition

    • Loops repeat an execution block until a specific exit condition is fulfilled.
    • Eliminates code duplication when processing arrays, printing patterns, or running repetitive processes.
    • Metaphor: Writing "I will not be late to class" 100 times on a blackboard manually vs. directing a loop program to execute the text in seconds.
  • The for Loop

    • Ideal when the precise number of iterations is known prior to loop entry.
    • Syntax structure contains three parameters inside parentheses:
    1. Initialization: Loop counter starting variable.
    2. Condition: Continuation condition checked prior to each cycle.
    3. Update: Counter increment/decrement step executed after each cycle.
    • Metaphor: Climbing 10 stairs with known start step, stop step, and step increments.
#include <iostream>
using namespace std;

int main() {
    // Factorial calculation example: 5!
    int n = 5, fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i; // fact = fact * i
    }
    cout << "Factorial = " << fact;
    return 0;
}
  • The while Loop
    • Continuously executes code as long as its Boolean condition remains true.
    • Used when the exact number of iterations is unknown in advance.
    • Metaphor: Repeatedly rolling a die until rolling a 6.
#include <iostream>
using namespace std;

int main() {
    int num, sum = 0;
    cout << "Enter positive numbers (-1 to stop): ";
    cin >> num;
    while (num != -1) {
        sum += num;
        cin >> num;
    }
    cout << "Sum = " << sum;
    return 0;
}
  • The do-while Loop
    • Guaranteed to execute its body at least once because its termination condition is evaluated at the bottom of the loop cycle.
    • Metaphor: Vending machine—insert coin and select a drink first, then check whether you wish to purchase another.
#include <iostream>
using namespace std;

int main() {
    int number = 7, guess;
    do {
        cout << "Guess the number: ";
        cin >> guess;
    } while (guess != number);
    cout << "Correct!";
    return 0;
}
  • Nested Loops and Multi-Dimensional Data Handling
    • Placing one loop inside another. The inner loop completes all its iteration cycles for every single pass of the outer loop.
    • Metaphor 1: Clock hands—for every 1 increment of the outer hour hand, the inner minute hand completes 60 cycles.
    • Metaphor 2: Classroom layout—the outer loop iterates through seating rows, while the inner loop places individual chairs across columns.
#include <iostream>
using namespace std;

int main() {
    // Iterating a 2x3 Matrix
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (int i = 0; i < 2; i++) { // Outer loop controls rows
        for (int j = 0; j < 3; j++) { // Inner loop controls columns
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
  • Loop Control Statements: break and continue
    • break: Exits the loop structure immediately.
    • continue: Terminates the remaining statements in the current iteration and jumps directly to the next iteration pass.
    • Metaphor: Playing musical chairs—a break stops the entire game completely; a continue skips one player's turn while game rounds proceed.