Course Introduction
beginner5mLearning Objectives
By the end of this course, students should be able to:
- Understand basic programming concepts
- Write basic C++ programs
- Use variables and data types
- Take input and produce output
- Use operators and expressions
- Make decisions using conditional statements
- Repeat operations using loops
- Create and use functions
- Work with arrays and strings
- Understand pointers and references
- Understand structures
- Understand Object-Oriented Programming
- Create classes and objects
- Apply inheritance and polymorphism
- Work with files
- Use the C++ Standard Library
- Solve programming problems
What is Programming?
beginner5mDefinition
Programming is the process of writing instructions that tell a computer how to perform a task.
Example Problem
Calculate the average marks of a student.
A human might think:
Get marks
Add marks
Divide by number of subjects
Display resultA computer needs these instructions expressed in a programming language.
Program
A program is a set of instructions written to solve a particular problem.
#include <iostream>
int main()
{
std::cout << "Hello World!";
return 0;
}What is C++?
beginner5mC++ is a general-purpose, compiled programming language that supports procedural, object-oriented, and generic programming.
Why Learn C++?
- Learning programming fundamentals
- Data structures and algorithms
- Competitive programming
- Game development
- System software
- Embedded systems
- High-performance applications
- Operating systems
- Software engineering
Compiler
beginner10mA computer does not directly understand normal C++ source code. The source code is processed by a compiler.
C++ Source Code
|
Compiler
|
Machine Code
|
Program
|
CPUImportant Terms
Source Code
Code written by the programmer.
Compiler
Software that translates source code into machine-executable code.
Executable
The resulting program that the computer can execute.
Installing C++
beginner10mStudents need:
- C++ compiler
- Code editor / IDE
- Terminal or build environment
Possible Setups
- Visual Studio
- VS Code with a C++ compiler
- Code::Blocks
- Other C++ IDEs
- Online C++ compiler
First C++ Program
beginner15m#include <iostream>
int main()
{
std::cout << "Hello World!";
return 0;
}Line-by-Line Explanation
Line 1: #include <iostream>
This includes the standard input/output library. We need it for std::cout and std::cin.
Line 2: int main()
main() is the entry point of a C++ program. Program execution begins from main().
{ }
These define a block of code.
std::cout
Used to display output.
return 0
Indicates that the program finished successfully.
Printing Output
beginner10mBasic Output
#include <iostream>
int main()
{
std::cout << "Hello";
return 0;
}Multiple Outputs
std::cout << "Hello";
std::cout << "World";Output: HelloWorld
New Line
std::cout << "Hello\n";
std::cout << "World";Output:
Hello
WorldOr:
std::cout << "Hello" << std::endl;Multiple Values
std::cout << "Age: " << 20;Output: Age: 20
Comments
beginner5mComments are ignored by the compiler.
Single-line Comment
// This is a commentMulti-line Comment
/*
This is
a multi-line
comment
*/Teaching Point: Comments are for humans, not for the computer.
Good Example
// Calculate total price
double total = price * quantity;Variables
beginner10mDefinition
A variable is a named location used to store data.
int age = 20;Think of it as:
age
|
+------+
| 20 |
+------+Variable Declaration
int age;Assignment
age = 20;Declaration + Initialization
int age = 20;Data Types
beginner10mImportant Beginner Data Types
| Type | Example | Purpose |
|---|---|---|
int | 10 | Whole numbers |
float | 10.5f | Decimal numbers |
double | 10.5 | More precise decimals |
char | 'A' | Single character |
bool | true | True/false |
std::string | "Ram" | Text |
Examples
int age = 20;
double salary = 50000.50;
char grade = 'A';
bool passed = true;
std::string name = "Ram";For strings, include #include <string>.
Character vs String
beginner5mImportant Beginner Concept
Character: 'A' (single quotes)
String: "A" (double quotes)
Character uses single quotes.
String uses double quotes.
Example
char c = 'A'; // Character
std::string s = "A"; // StringCommon Mistake: Students often confuse
'A'(char) with"A"(string).
Constants
beginner5mSometimes a value should not change.
const double PI = 3.14159;After this, PI = 5; is not allowed.
Teaching Example
const double TAX_RATE = 0.13;
double calculateTax(double amount)
{
return amount * TAX_RATE;
}Why constants? They make programs safer and easier to understand. If a value is named and constant, programmers know it won't change accidentally.
Input
beginner10mUse std::cin.
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You are " << age << " years old.";Multiple Inputs
int a, b;
std::cin >> a >> b;Students can enter: 10 20
Example - Student Information
beginner10m#include <iostream>
#include <string>
int main()
{
std::string name;
int age;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Name: " << name << "\n";
std::cout << "Age: " << age << "\n";
return 0;
}Arithmetic Operators
beginner10m| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
Example
int a = 10;
int b = 3;
std::cout << a + b; // 13
std::cout << a - b; // 7
std::cout << a * b; // 30
std::cout << a / b; // 3 (integer division!)
std::cout << a % b; // 1Integer Division
beginner5mVery Important!
int result = 10 / 3;Result: 3 (not 3.3333)
Because both operands are integers.
Compare
double result = 10.0 / 3;Result: 3.3333
Common Mistake: Students forget that integer division truncates the decimal part.
Assignment Operators
beginner5m=
+=
-=
*=
/=
%=Example
int x = 10;
x += 5; // x is now 15
x -= 3; // x is now 12
x *= 2; // x is now 24
x /= 4; // x is now 6
x %= 4; // x is now 2Increment and Decrement
beginner10mx++;Equivalent conceptually to: x = x + 1;
Similarly:
x--;means: x = x - 1;
Prefix vs Postfix
int a = 5;
int b = a++; // b = 5, a = 6 (postfix: use then increment)
int c = ++a; // c = 7, a = 7 (prefix: increment then use)Relational Operators
beginner5mUsed to compare values.
>
<
>=
<=
==
!=Example
int age = 20;
std::cout << (age >= 18); // 1 (true)
std::cout << (age < 18); // 0 (false)Note: In C++,
trueis represented as1andfalseas0when printed.
= vs ==
beginner5mVery Important!
x = 10; // Assignment: Assign 10 to x
x == 10 // Comparison: Is x equal to 10?Common Mistake
if (x = 10) // WRONG: This assigns 10 to x!
{
// Always executes because 10 is truthy
}Correct:
if (x == 10) // CORRECT: This checks equality
{
// Executes only if x is 10
}Conditional Statements
beginner20mif
if (age >= 18)
{
std::cout << "Adult";
}if-else
if (age >= 18)
{
std::cout << "Adult";
}
else
{
std::cout << "Minor";
}else if
if (marks >= 80)
{
std::cout << "A";
}
else if (marks >= 60)
{
std::cout << "B";
}
else if (marks >= 40)
{
std::cout << "C";
}
else
{
std::cout << "Fail";
}Logical Operators
beginner10mAND (&&)
Both conditions must be true.
if (age >= 18 && age <= 60)
{
std::cout << "Valid age";
}OR (||)
At least one condition must be true.
if (day == "Saturday" || day == "Sunday")
{
std::cout << "Weekend";
}NOT (!)
Reverses a Boolean condition.
if (!isFinished)
{
std::cout << "Still running";
}switch
beginner15mUseful when comparing one value against multiple fixed choices.
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
std::cout << "Add";
break;
case 2:
std::cout << "Delete";
break;
case 3:
std::cout << "Exit";
break;
default:
std::cout << "Invalid choice";
}Teaching Point: Explain the purpose of
break. Without it, execution "falls through" to the next case.
Loops
beginner15mWhy Loops?
Suppose we need to print:
1
2
3
4
5Without a loop:
std::cout << 1;
std::cout << 2;
std::cout << 3;
std::cout << 4;
std::cout << 5;With a loop:
for (int i = 1; i <= 5; i++)
{
std::cout << i << "\n";
}for Loop
beginner10mSyntax
for (initialization; condition; update)
{
// statements
}Example
for (int i = 1; i <= 10; i++)
{
std::cout << i << "\n";
}How a for Loop Executes
beginner10mFor:
for (int i = 1; i <= 3; i++)Execution Trace
i = 1
|
condition true (1 <= 3)
|
execute body
|
i++
|
condition true (2 <= 3)
|
execute body
|
i++
|
condition true (3 <= 3)
|
execute body
|
i++
|
condition false (4 <= 3)
|
stopwhile Loop
beginner10mint i = 1;
while (i <= 5)
{
std::cout << i << "\n";
i++;
}Use while when repetition depends primarily on a condition.
Example
int number;
std::cout << "Enter a positive number: ";
std::cin >> number;
while (number < 0)
{
std::cout << "Invalid! Try again: ";
std::cin >> number;
}do-while
beginner10mint i = 1;
do
{
std::cout << i << "\n";
i++;
}
while (i <= 5);Important Difference
do-whileexecutes the body at least once.
Example
int choice;
do
{
std::cout << "1. Play\n";
std::cout << "2. Settings\n";
std::cout << "3. Exit\n";
std::cout << "Enter choice: ";
std::cin >> choice;
}
while (choice != 3);break and continue
beginner10mbreak
Stops the loop.
for (int i = 1; i <= 10; i++)
{
if (i == 5)
break;
std::cout << i << "\n";
}Output: 1 2 3 4
continue
Skips the current iteration.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue;
std::cout << i << "\n";
}Output: 1 2 4 5
Functions
intermediate20mWhy Functions?
Functions help:
- Organize code
- Reuse code
- Reduce duplication
- Make programs easier to understand
- Break large problems into smaller problems
Simple Function
void greet()
{
std::cout << "Hello";
}Call: greet();
Function Parameters
intermediate10mvoid greet(std::string name)
{
std::cout << "Hello " << name;
}Call: greet("Ram");
Multiple Parameters
void add(int a, int b)
{
std::cout << a + b;
}Call: add(10, 20);
Return Values
intermediate10mint add(int a, int b)
{
return a + b;
}Usage:
int result = add(10, 20);
std::cout << result; // 30Function That Returns Boolean
bool isEven(int n)
{
return n % 2 == 0;
}Usage:
if (isEven(4))
{
std::cout << "Even";
}Function Structure
intermediate10mTeach students to identify:
int add(int a, int b)
{
return a + b;
}| Part | Meaning |
|---|---|
int | Return type |
add | Function name |
int a | Parameter |
int b | Parameter |
return | Sends value back |
Function Declaration vs Definition
Declaration (prototype):
int add(int a, int b);Definition:
int add(int a, int b)
{
return a + b;
}Arrays
intermediate15mAn array stores multiple values of the same type.
int marks[5];Initialize:
int marks[5] = {80, 70, 90, 60, 85};Partial Initialization
int arr[5] = {10, 20}; // {10, 20, 0, 0, 0}Zero Initialization
int arr[5] = {}; // {0, 0, 0, 0, 0}Array Indexing
intermediate10mC++ arrays start at index 0.
Index: 0 1 2 3 4
| | | | |
Marks: 80 70 90 60 85Therefore: marks[0] is 80.
std::cout << marks[0]; // 80
std::cout << marks[2]; // 90Common Mistake: Accessing
marks[5]on an array of size 5 is out of bounds!
Arrays + Loops
intermediate15mint marks[5] = {80, 70, 90, 60, 85};
for (int i = 0; i < 5; i++)
{
std::cout << marks[i] << "\n";
}This is an important point where students begin combining concepts.
Finding Maximum
int marks[5] = {80, 70, 90, 60, 85};
int max = marks[0];
for (int i = 1; i < 5; i++)
{
if (marks[i] > max)
{
max = marks[i];
}
}
std::cout << "Maximum: " << max;Strings
intermediate10mstd::string name = "Abhay";Useful Operations
name.length(); // 5
name.empty(); // falseConcatenation
std::string first = "Hello ";
std::string second = "World";
std::string result = first + second; // "Hello World"Accessing Characters
std::string name = "Hello";
std::cout << name[0]; // H
std::cout << name[4]; // ogetline()
intermediate10mDifference
std::cin >> name;Reads one whitespace-delimited value.
std::getline(std::cin, name);Reads a complete line.
Example
std::string fullName;
std::cout << "Enter your full name: ";
std::getline(std::cin, fullName);
std::cout << "Hello, " << fullName;Pointers
intermediate25mIntroduce pointers only after students understand variables.
A pointer stores an address.
int x = 10;
int* p = &x;Here:
x -> value
&x -> address
p -> address stored in pointer
*p -> value at that addressKey Operators
| Operator | Meaning |
|---|---|
& | Address-of |
* | Dereference |
Pointer Example
intermediate15mint x = 10;
int* p = &x;
std::cout << x << "\n"; // 10
std::cout << &x << "\n"; // address of x
std::cout << p << "\n"; // same address
std::cout << *p << "\n"; // 10 (dereference)Modifying via Pointer
int x = 10;
int* p = &x;
*p = 20; // Change value at address
std::cout << x; // 20References
intermediate15mint x = 10;
int& ref = x;ref becomes another name for x.
ref = 20;
std::cout << x; // 20References vs Pointers
| Feature | Reference | Pointer |
|---|---|---|
| Syntax | int& ref = x; | int* p = &x; |
| Null | Cannot be null | Can be null |
| Rebinding | Cannot rebind | Can rebind |
| Access | Direct: ref | Dereference: *p |
Structures
intermediate10mStructures allow us to group related data.
struct Student
{
std::string name;
int age;
double marks;
};Create:
Student s;
s.name = "Ram";
s.age = 20;
s.marks = 85.5;Initialization
Student s = {"Ram", 20, 85.5};Array of Structures
Student students[3] = {
{"Ram", 20, 85.5},
{"Shyam", 21, 90.0},
{"Hari", 19, 78.0}
};Introduction to OOP
intermediate15mObject-Oriented Programming is a way of designing programs around objects that contain data and behavior.
Important Concepts
Class
Object
Encapsulation
Inheritance
Polymorphism
AbstractionReal-World Analogy
Class -> Blueprint for a house
Object -> Actual house built from blueprintBenefits
- Code reusability
- Data hiding (security)
- Easier maintenance
- Real-world modeling
Classes
intermediate15mA class is a blueprint for objects.
class Student
{
public:
std::string name;
int age;
};Create object:
Student s1;
s1.name = "Ram";
s1.age = 20;Access Specifiers
| Specifier | Access |
|---|---|
public | Accessible from anywhere |
private | Accessible only within class |
protected | Accessible within class and derived classes |
Class vs Object
intermediate10mUse a real-world analogy.
Class
|
Blueprint
Object
|
Actual thing created from blueprintExample:
Class -> Student
Objects:
student1 (Ram, 20)
student2 (Shyam, 21)
student3 (Hari, 19)Constructors
intermediate15mA constructor is called when an object is created.
Default Constructor
class Student
{
public:
Student()
{
std::cout << "Student created";
}
};Parameterized Constructor
class Student
{
public:
std::string name;
int age;
Student(std::string n, int a)
{
name = n;
age = a;
}
};Create:
Student s("Ram", 20);Initializer List (Preferred)
Student(std::string n, int a) : name(n), age(a) {}Encapsulation
intermediate10mEncapsulation means controlling access to an object's data and behavior.
class BankAccount
{
private:
double balance;
public:
void deposit(double amount)
{
if (amount > 0)
balance += amount;
}
double getBalance()
{
return balance;
}
};private -> internal data
public -> controlled interfaceBenefits
- Data protection
- Controlled access
- Easy maintenance
- Flexibility to change internal implementation
Inheritance
advanced20mInheritance allows one class to derive from another.
Person
|
----------------
| |
Student Teacherclass Person
{
public:
std::string name;
};
class Student : public Person
{
public:
int rollNumber;
};Usage:
Student s;
s.name = "Ram"; // Inherited from Person
s.rollNumber = 101; // Own memberTypes of Inheritance
- Single
- Multiple
- Multilevel
- Hierarchical
- Hybrid
Polymorphism
advanced25mPolymorphism means: One interface can have different implementations.
Function Overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }Virtual Functions (Runtime Polymorphism)
class Animal
{
public:
virtual void sound()
{
std::cout << "Animal sound";
}
};
class Dog : public Animal
{
public:
void sound() override
{
std::cout << "Bark";
}
};Animal* a = new Dog();
a->sound(); // Output: BarkException Handling
advanced15mPrograms can encounter exceptional situations.
try
{
int a = 10;
int b = 0;
if (b == 0)
throw "Division by zero";
std::cout << a / b;
}
catch (const char* msg)
{
std::cout << "Error: " << msg;
}Keywords
| Keyword | Purpose |
|---|---|
try | Block of code that might throw |
catch | Handles the exception |
throw | Signals an exception |
Standard Exceptions
#include <stdexcept>
throw std::runtime_error("Something went wrong");File Handling
advanced15mWriting to File
#include <fstream>
std::ofstream file("data.txt");
file << "Hello World";
file.close();Reading from File
#include <fstream>
std::ifstream file("data.txt");
std::string text;
while (std::getline(file, text))
{
std::cout << text << "\n";
}
file.close();Check if File Exists
std::ifstream file("data.txt");
if (file.is_open())
{
// File exists, read it
file.close();
}STL
advanced25mIntroduce the Standard Template Library after students understand the basics.
Important Containers
| Container | Description |
|---|---|
vector | Dynamic array |
array | Fixed-size array |
string | String class |
map | Key-value pairs |
set | Unique sorted elements |
stack | LIFO |
queue | FIFO |
priority_queue | Sorted queue |
Important Algorithms
sort()
find()
reverse()vector
advanced15mA vector is a dynamic sequence container.
#include <vector>
std::vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);Loop
for (int number : numbers)
{
std::cout << number << "\n";
}Size and Access
numbers.size(); // 3
numbers[0]; // 10
numbers.at(1); // 20 (with bounds checking)
numbers.pop_back(); // Remove last element2D Vector
std::vector<std::vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};Problem-Solving Practice
intermediate30mStudents should solve problems continuously.
Beginner Problems
Problem 1
Input two numbers and calculate sum, difference, product, quotient.
Problem 2
Check whether a number is even or odd.
Problem 3
Find the largest of three numbers.
Problem 4
Calculate student grade.
Problem 5
Calculate factorial.
Problem 6
Check whether a number is prime.
Problem 7
Reverse a number.
Problem 8
Check whether a number is palindrome.
Array Problems
intermediate20mStudents should solve:
- Find maximum
- Find minimum
- Calculate sum
- Calculate average
- Search for an element
- Count even numbers
- Count odd numbers
- Reverse array
- Sort array
- Find duplicate values
Example: Find Maximum
int arr[5] = {23, 55, 2, 67, 12};
int max = arr[0];
for (int i = 1; i < 5; i++)
{
if (arr[i] > max)
max = arr[i];
}
std::cout << "Maximum: " << max;Mini Project Ideas
intermediate15mAfter fundamentals, give students small projects.
Project 1 - Student Grade System
Features:
- Enter student
- Enter marks
- Calculate total
- Calculate average
- Determine grade
- Display result
Project 2 - Calculator
Operations: +, -, *, /, %
Project 3 - Number Guessing Game
Computer chooses a number. Student guesses. Program responds: Too high, Too low, Correct.
Project 4 - Student Management System
Store: Student ID, Name, Age, Marks Operations: Add, Display, Search, Update, Delete