Teaching Session 1
Teaching Session 1
C++ is a powerful, high-performance programming language that has been widely used in
various domains, including systems programming, game development, and applications
requiring real-time processing. Below is an overview of its history, features, advantages, and
applications.
• Origins: C++ was developed by Bjarne Stroustrup at Bell Labs in the early 1980s. It
was designed as an extension of the C programming language, with added support for
object-oriented programming (OOP).
• Name: Initially called "C with Classes," it was renamed to C++ in 1983. The "++"
symbolizes the incremental improvement over C.
• Standardization: The language was standardized in 1998 (C++98), with subsequent
updates in 2003 (C++03), 2011 (C++11), 2014 (C++14), 2017 (C++17), and 2020
(C++20). Each update introduced new features and improvements.
1
o Supports multiple programming paradigms, including OOP, procedural, and
generic programming.
8. Rich Library Support:
o Comes with a vast standard library and supports third-party libraries for
additional functionality.
1. High Performance:
o C++ is compiled directly to machine code, resulting in faster execution
compared to interpreted languages.
2. Control Over Hardware:
o Provides low-level memory manipulation, making it ideal for systems
programming and embedded systems.
3. Scalability:
o Suitable for both small-scale and large-scale applications.
4. Community and Ecosystem:
o Has a large and active community, along with extensive documentation and
resources.
5. Backward Compatibility:
o Maintains compatibility with C, allowing developers to reuse existing C code.
6. Versatility:
o Can be used for a wide range of applications, from operating systems to game
engines.
1. Systems Programming:
o Used to develop operating systems (e.g., Windows, Linux) and device drivers.
2. Game Development:
o Powers many game engines (e.g., Unreal Engine) and AAA games due to its
performance and control over hardware.
3. Embedded Systems:
o Ideal for programming microcontrollers and IoT devices.
4. Real-Time Systems:
o Used in applications requiring real-time processing, such as robotics and flight
control systems.
5. Graphics and GUI Applications:
o Used in software like Adobe Photoshop and AutoCAD for rendering and
graphical computations.
6. Web Browsers:
o Core components of browsers like Chrome and Firefox are written in C++.
7. Database Systems:
o Used in database management systems like MySQL and MongoDB.
2
8. Financial Applications:
o Employed in high-frequency trading systems due to its speed and efficiency.
9. Scientific Computing:
o Used in simulations, modeling, and other computationally intensive tasks.
I.6 - Conclusion
C++ is a versatile and powerful language that combines the efficiency of low-level
programming with the flexibility of high-level abstractions. Its rich feature set, performance,
and wide range of applications make it a popular choice for developers across industries.
Whether you're building a game, an operating system, or a real-time system, C++ provides the
tools and capabilities to get the job done efficiently.
3
II - Differences between procedural and object-oriented programming C++ with
examples of code
Example in C++:
cpp
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 5;
cout << "Sum: " << add(x, y) << endl; // Output: Sum: 15
cout << "Difference: " << subtract(x, y) << endl; // Output: Difference: 5
return 0;
}
• Here, add and subtract are standalone functions that operate on data passed to them.
• Focus: The program is divided into objects that encapsulate data and behavior.
4
• Data and Functions: Data and functions are combined into objects. Functions
(methods) operate on the object's data.
• Approach: Bottom-up approach, where the program is designed using classes and
objects.
• Reusability: High reusability through inheritance and polymorphism.
• Key Concepts: Encapsulation, Inheritance, Polymorphism, and Abstraction.
• Example: C++, Java, Python.
Example in C++:
cpp
#include <iostream>
using namespace std;
// Class definition
class Calculator {
private:
int x, y;
public:
// Constructor to initialize data
Calculator(int a, int b) : x(a), y(b) {}
// Method to add
int add() {
return x + y;
}
// Method to subtract
int subtract() {
return x - y;
}
};
int main() {
Calculator calc(10, 5); // Create an object
cout << "Sum: " << calc.add() << endl; // Output: Sum: 15
cout << "Difference: " << calc.subtract() << endl; // Output: Difference: 5
return 0;
}
• Here, Calculator is a class that encapsulates data (x and y) and methods
(add and subtract).
a) Key Differences
5
Procedural
Aspect Object-Oriented Programming
Programming
Data and
Separate Combined into objects
Functions
C++ supports both paradigms, allowing you to mix procedural and object-oriented
programming as needed.
6
cpp
#include <iostream>
using namespace std;
// Procedural function
void greet() {
cout << "Hello, World!" << endl;
}
// OOP class
class Greeter {
public:
void greet() {
cout << "Hello from Greeter class!" << endl;
}
};
int main() {
// Procedural approach
greet();
// OOP approach
Greeter greeter;
greeter.greet();
return 0;
}
• Output:
Hello, World!
Hello from Greeter class!
7
III - Key OOP concepts: Classes, Objects, Encapsulation, Abstraction, Inheritance,
syntax with example and code C++
III. 1. Classes
A class is a blueprint for creating objects. It defines properties (attributes) and behaviors
(methods) that the objects will have.
Syntax:
cpp
class ClassName {
// Access specifier
private:
// Private members (attributes/methods)
public:
// Public members (attributes/methods)
};
Example:
cpp
#include <iostream>
using namespace std;
class Car {
private:
string brand;
int year;
public:
void setBrand(string b) {
brand = b;
}
void setYear(int y) {
year = y;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
8
};
int main() {
Car myCar;
myCar.setBrand("Toyota");
myCar.setYear(2020);
myCar.display(); // Output: Brand: Toyota, Year: 2020
return 0;
}
III.2. Objects
Syntax:
cpp
Copy
ClassName objectName;
Example:
cpp
Car myCar; // myCar is an object of the Car class
III.3. Encapsulation
Encapsulation is the bundling of data (attributes) and methods that operate on the data into a
single unit (class). It also restricts direct access to some of the object's components, which is
achieved using access specifiers (private, public, protected).
Example:
cpp
class Car {
private:
string brand; // Encapsulated data
public:
void setBrand(string b) {
brand = b; // Controlled access to private data
}
string getBrand() {
return brand;
}
};
9
III.4. Abstraction
Abstraction means hiding complex implementation details and showing only the necessary
features of an object. It is achieved using classes and access specifiers.
Example:
cpp
class Car {
private:
string engineDetails; // Hidden from the user
public:
void start() {
engineDetails = "Engine started";
cout << "Car started!" << endl;
}
};
int main() {
Car myCar;
myCar.start(); // User doesn't need to know about engineDetails
return 0;
}
III.5. Inheritance
Inheritance allows a class (derived class) to inherit attributes and methods from another class
(base class). It promotes code reusability.
Syntax:
cpp
class DerivedClass : access-specifier BaseClass {
// Derived class members
};
Example:
cpp
#include <iostream>
using namespace std;
// Base class
class Vehicle {
public:
10
void honk() {
cout << "Honk honk!" << endl;
}
};
// Derived class
class Car : public Vehicle {
public:
string brand;
};
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.honk(); // Inherited from Vehicle
return 0;
}
III.6. Polymorphism
Example:
cpp
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
virtual void sound() {
cout << "Animal sound" << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void sound() override {
cout << "Woof woof!" << endl;
}
};
int main() {
Animal* myAnimal = new Dog();
myAnimal->sound(); // Output: Woof woof!
return 0;
}
11
III.7. Syntax Summary
• Class Definition:
cpp
class ClassName {
private:
// Private members
public:
// Public members
};
• Object Creation:
cpp
ClassName objectName;
• Inheritance:
cpp
• Polymorphism:
cpp
Copy
12
IV -Basic structure and syntax of a C++ program with example flowchart
cpp
#include <iostream> // Preprocessor directive to include the iostream library
1. #include <iostream>: Includes the input/output stream library, which allows the
program to use std::cout for output.
2. int main(): The starting point of the program. The int indicates that the function
returns an integer.
3. std::cout << "Hello, World!" << std::endl;: Outputs the text "Hello, World!" to the
console. std::endl adds a newline.
4. return 0;: Indicates that the program executed successfully.
13
6. End: The program terminates.
This is a basic example of a C++ program and its corresponding flowchart. As programs
become more complex, the structure and flowchart will include additional components like
variables, loops, conditionals, and functions.
14
V - Setting up the C++ development environment (compiler, IDE)
A compiler is required to compile and run C++ code. The most common C++ compiler
is GCC (GNU Compiler Collection).
Windows
g++ --version
Linux
bash
o Fedora:
bash
g++ --version
15
macOS
• Install Xcode Command Line Tools, which include the Clang compiler:
bash
xcode-select --install
g++ --version
An IDE or code editor makes writing and debugging C++ code easier.
Popular IDEs
Code Editors
16
V.3. Write and Compile Your First C++ Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
4. Compile and run the program:
o Using Command Line:
bash
o Using an IDE:
▪ Click the "Build" or "Run" button in the IDE.
4. Debugging
• Use the built-in debugger in your IDE (e.g., Visual Studio, Code::Blocks, or VS
Code).
• Set breakpoints, inspect variables, and step through your code.
5. Additional Tools
17
VI. Input/output operations in C++ (cin, cout) with examples of code
Input and output operations in C++ are primarily handled using the cin and cout objects,
which are part of the iostream library. cin is used for input operations, while cout is used for
output operations. Below are examples and explanations of how to use these in C++.
cout is used to display output to the standard output device (usually the screen). It is used with
the insertion operator <<.
Example:
cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl; // Outputs "Hello, World!" followed by a newline
cout << "C++ is fun!"; // Outputs "C++ is fun!"
return 0;
}
Output:
Hello, World!
C++ is fun!
• << is the insertion operator, used to insert data into the output stream.
• endl is used to insert a newline character and flush the output buffer.
cin is used to read input from the standard input device (usually the keyboard). It is used with
the extraction operator >>.
Example:
cpp
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: "; // Prompt the user
cin >> age; // Read input into the variable 'age'
cout << "You are " << age << " years old." << endl;
18
return 0;
}
Example:
cpp
#include <iostream>
using namespace std;
int main() {
string name;
int age;
cout << "Hello, " << name << "! You are " << age << " years old." << endl;
return 0;
}
Example:
19
cpp
#include <iostream>
using namespace std;
int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2; // Read two integers
cout << "You entered: " << num1 << " and " << num2 << endl;
return 0;
}
cin stops reading input at the first whitespace character. To read an entire line of input
(including spaces), use getline.
Example:
cpp
#include <iostream>
using namespace std;
int main() {
string fullName;
cout << "Enter your full name: ";
cin.ignore(); // Ignore any leftover newline character in the buffer
getline(cin, fullName); // Read the entire line
cout << "Hello, " << fullName << "!" << endl;
return 0;
}
You can check if the input operation was successful using the cin.fail() method.
20
Example:
cpp
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (cin.fail()) {
cout << "Invalid input! Please enter a number." << endl;
} else {
cout << "You entered: " << number << endl;
}
return 0;
}
Summary
These are the basics of input/output operations in C++! Let me know if you need further
clarification or examples.
21
VII. Data types, operators, and control structures in c++ with examples for each case
C++ is a powerful programming language that supports various data types, operators, and
control structures. Below is an explanation of each with examples:
Data types define the type of data a variable can hold. C++ supports the following basic data
types:
• Array: Collection of similar data types (e.g., int numbers[5] = {1, 2, 3, 4, 5};)
• Pointer: Stores memory address (e.g., int* ptr = &age;)
• Reference: Alias for a variable (e.g., int& ref = age;)
• struct: Group of variables (e.g., struct Person { string name; int age; };)
• class: Blueprint for objects (e.g., class Car { public: string model; int year; };)
• enum: Enumerated type (e.g., enum Color { RED, GREEN, BLUE };)
a. Arithmetic Operators
b. Relational Operators
22
• < (Less than): if (a < b) { ... }
• >= (Greater than or equal to): if (a >= b) { ... }
• <= (Less than or equal to): if (a <= b) { ... }
c. Logical Operators
d. Assignment Operators
e. Increment/Decrement Operators
• ++ (Increment): x++; // x = x + 1
• -- (Decrement): x--; // x = x - 1
f. Ternary Operator
a. Decision-Making Structures
• if statement:
cpp
if (a > b) {
cout << "a is greater than b";
}
• if-else statement:
cpp
if (a > b) {
cout << "a is greater than b";
} else {
cout << "b is greater than or equal to a";
}
• switch statement:
23
cpp
switch (grade) {
case 'A': cout << "Excellent"; break;
case 'B': cout << "Good"; break;
default: cout << "Invalid grade";
}
b. Looping Structures
• for loop:
cpp
• while loop:
cpp
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
• do-while loop:
cpp
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
c. Jump Statements
• break: Exits a loop or switch statement.
cpp
24
cout << i << " ";
}
cpp
#include <iostream>
using namespace std;
int main() {
// Data types
int a = 10, b = 20;
float pi = 3.14;
char grade = 'A';
bool isActive = true;
// Operators
int sum = a + b;
bool isGreater = (a > b);
// Control structures
if (isGreater) {
cout << "a is greater than b" << endl;
} else {
cout << "b is greater than or equal to a" << endl;
}
return 0;
}
This program demonstrates the use of data types, operators, and control structures in C++. Let
me know if you need further clarification!
25