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

- 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.
- Preprocessor directives (e.g.,

- 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
constwhose 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 (trueorfalse) (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 toy -= 3;is equivalent toz *= 2;is equivalent toa /= 4;is equivalent tob %= 2;is equivalent to
- Basic assignment uses
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.
- Implicit Conversion (Type Promotion/Coercion): Automatic promotion by the compiler when performing operations across compatible types (e.g.,
#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()orcin.ignore(numeric_limits<streamsize>::max(), ' ')) clear lingering newline characters left in the input buffer prior to invokinggetline().
- Output is performed using
Practical Assignments Requirements
- Print block letters "I T !" inside a border of asterisks (
*), followed by two blank lines and the statement "Information Technology is Cool Stuff". - Prompt users for first name, middle name, and last name using word-by-word
cinextraction into separate string variables (withoutgetline()), displaying the full name on a single line (e.g., output:Your Name is Karen Madoline Abancio Cabrillos).
- Print block letters "I T !" inside a border of asterisks (
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.,
). - Relational Expressions: Compare values to evaluate truth (e.g.,
). - Logical Expressions: Evaluate logical truth flags (e.g.,
).

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 to1(true) or0(false). - Logical Operators:
&&(AND),||(OR),!(NOT).
- Arithmetic Operators:
Binary Numbers and Bitwise Operations
- Computers store all data in binary (Base 2 using bits
0and1). - Binary literals can be written directly in C++ code using the
0bprefix (e.g.,int a = 0b1010;represents10). - Binary formatting output can be inspected using
#include <bitset>withbitset<8>(num). - Bitwise Operators (acting directly on corresponding bits):
&(Bitwise AND):outputs1only if both bits are1.|(Bitwise OR):outputs1if at least one bit is1.^(Bitwise XOR):outputs1if bits differ.~(Bitwise NOT):inverts all bits.<<(Left Shift):shifts bits left (multiplies integer value by 2).>>(Right Shift):shifts bits right (divides integer value by 2).
- Computers store all data in binary (Base 2 using bits
#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):
- Parentheses
()first (innermost to outermost). - Exponents.
- Multiplication (
*), Division (/), and Modulo (%) from left to right. - 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:
. - Right-to-left evaluation example: Assignment statements (
). - Expression example:
.

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.

- 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) or0(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
ifStatement- Executes a designated block of code only when the condition evaluates to
true; skips the block entirely iffalse. - Metaphor: Checking weather—if raining, take an umbrella.
- Executes a designated block of code only when the condition evaluates to

- The
if-elseStatement- Provides two explicit execution branches: the
ifblock executes when the condition istrue, while theelseblock executes whenfalse. - Metaphor: Checking weather—if raining, bring an umbrella; else, wear sunglasses.
- Provides two explicit execution branches: the

- Nested
if-elseStatements- Places
iforif-elsestructures 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.
- Places
#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;
}

- The
switchStatement- Evaluates a single integral/character expression against fixed match values labeled as
caseoptions. - Clean alternative to extensive
if-else ifchains. - Uses
breakto exit the structure after executing a matching case, and an optionaldefaultblock 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.
- Evaluates a single integral/character expression against fixed match values labeled as
#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;
}

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
forLoop- Ideal when the precise number of iterations is known prior to loop entry.
- Syntax structure contains three parameters inside parentheses:
- Initialization: Loop counter starting variable.
- Condition: Continuation condition checked prior to each cycle.
- 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
whileLoop- 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.
- Continuously executes code as long as its Boolean condition remains
#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-whileLoop- 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:
breakandcontinuebreak: 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
breakstops the entire game completely; acontinueskips one player's turn while game rounds proceed.