C++ Revision Guide for Exams
C++ Revision Guide for Exams
1. Overview
• What is C++?
o C++ is a high-performance programming language used for developing
software, games, and system applications.
o It supports object-oriented programming (OOP), which organizes code into
reusable objects.
• Key Features:
o Object-Oriented Programming (OOP): Encapsulation, inheritance, and
polymorphism.
o Standard Template Library (STL): Provides pre-built data structures and
algorithms.
o Portability: C++ code can run on multiple platforms (Windows, Mac, Linux).
• Why Learn C++?
o It offers fine-grained control over system resources and memory.
o It is widely used in industries like gaming, finance, and robotics.
o It is fast and efficient, making it ideal for performance-critical applications.
Advantages of C++
1. High Performance:
o Compiled language with direct machine code execution.
o Allows low-level memory manipulation for fine-grained control.
2. Object-Oriented Programming (OOP):
o Supports encapsulation, inheritance, and polymorphism.
o Promotes code reusability and modularity.
3. Rich Standard Library (STL):
o Provides pre-built data structures and algorithms.
o Reduces the need to write code from scratch.
4. Portability:
o Code can run on multiple platforms (Windows, Linux, macOS) with minimal
changes.
5. Memory Management:
o Manual memory management gives developers control over system resources.
Disadvantages of C++
1. Complexity:
o Steep learning curve due to advanced features like pointers and OOP.
o Can be overcomplicated for small projects.
2. Manual Memory Management:
o No garbage collection, leading to potential memory leaks or dangling pointers.
3. Verbose Syntax:
o Requires more code compared to modern languages like Python.
4. Security Vulnerabilities:
o Prone to issues like buffer overflows and pointer misuse.
5. Slow Development Cycle:
o Compilation process can be time-consuming for large projects.
o Not ideal for rapid prototyping.
2. Environment Setup
• Tools Needed:
o Text Editor: VS Code, Notepad++, or Sublime Text.
o Compiler: GCC, Clang, or Visual Studio.
• Online Compiler:
o Use [Link] to run C++ code without installation.
• Local Setup:
o Windows: Install MinGW or Visual Studio.
o Linux: Use sudo apt-get install g++ to install GCC.
o Mac: Install Xcode from the App Store.
3. Basic Syntax
• Structure of a C++ Program:
#include <iostream> // Include input/output library
using namespace std; // Use the standard namespace
• Explanation:
o #include <iostream>: Allows input/output operations.
o using namespace std;: Lets you use cout and cin without writing std::.
o int main(): The starting point of the program.
o cout << "Hello World!";: Prints text to the console.
o return 0;: Ends the program successfully.
4. Comments in C++
• Single-line Comments:
// This is a single-line comment
• Multi-line Comments:
/* This is a
multi-line comment */
5. Data Types
• Primitive Data Types:
Data Type Description Example
int Integer numbers int age = 25;
float Floating-point numbers float pi = 3.14;
double Double-precision floating-point double salary = 5000.50;
char Single character char grade = 'A';
bool Boolean (true/false) bool isTrue = true;
6. Variable Types
• Variables: Used to store data that can change.
int x = 10; // Declare and initialize a variable
x = 20; // Change the value of x
7. Variable Scope
• Local Variables: Declared inside a function and accessible only within that function.
void myFunction() {
int x = 10; // Local variable
cout << x;
}
• Global Variables: Declared outside all functions and accessible throughout the program.
int x = 10; // Global variable
void myFunction() {
cout << x;
}
8. Constants/Literals
• Integer Literals: Whole numbers (e.g., 10, -5).
• Floating-point Literals: Decimal numbers (e.g., 3.14, -0.5).
• Boolean Literals: true or false.
• Character Literals: Single characters enclosed in single quotes (e.g., 'A', '1').
• String Literals: Sequence of characters enclosed in double quotes (e.g., "Hello").
9. Modifier Types
• Type Modifiers: Change the meaning of the base data type.
o signed: Can store positive and negative values.
o unsigned: Can store only positive values.
o short: Reduces the size of the data type.
o long: Increases the size of the data type.
11. Operators
• Arithmetic Operators: +, -, *, /, %
• Relational Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !
• Bitwise Operators: &, |, ^, ~, <<, >>
• Assignment Operators: =, +=, -=, *=, /=
12. Loop Types
Loops are used to repeat a block of code multiple times until a specific condition is met. C++
provides three types of loops:
• For Loop:
Used when the number of iterations is known in advance.
Combines initialization, condition, and update in a single line
Key Points:
Initialization: Executed once at the start.
Condition: Checked before each iteration. If false, the loop ends.
Update: Executed after each iteration.
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
• While Loop:
Used when the number of iterations is not known in advance.
Continues executing as long as the condition is true.
Key Points:
The condition is checked before each iteration.
If the condition is false initially, the loop never executes.
int i = 0;
while (i < 5) {
cout << i << endl;
i++;
}
• Do-While Loop:
Similar to the while loop, but the condition is checked after the loop body.
Ensures the loop executes at least once.
Key Points:
The loop body executes at least once, even if the condition is false.
Useful for scenarios where the loop must run before checking the condition.
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 5);
• if-else Statement
Executes one block of code if the condition is true and another if it is false.
int age = 15;
if (age >= 18) {
cout << "You are an adult.";
} else {
cout << "You are a minor."; // Output: You are a minor.
}
• Switch Statement:
Used to select one of many code blocks to execute based on the value of a variable.
int day = 3;
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
default: cout << "Invalid day";
}
14. Functions
Functions in C++
Functions are blocks of code that perform a specific task. They help in organizing code,
reducing redundancy, and improving readability. Functions can take inputs (parameters),
process them, and return a result.
1. Function Definition
• Return type: The type of value the function returns (e.g., int, void).
• Function name: The name of the function (e.g., add, printMessage).
• Parameters: Inputs to the function (optional).
• Function body: The code that performs the task.
Syntax:
return_type function_name(parameter_list) {
// Function body
return value; // Optional (only if return_type is not void)
}
Example:
int add(int a, int b) {
return a + b;
}
A function declaration tells the compiler about the function's name, return type, and
parameters. It is used when the function is defined after it is called.
Syntax:
return_type function_name(parameter_list);
Example:
int add(int a, int b); // Function declaration
3. Function Call
A function is executed by calling it with the required arguments.
Syntax:
function_name(arguments);
Example:
int result = add(5, 10); // Function call
cout << result; // Output: 15
4. Types of Functions
a) Functions with No Return Type (void)
int main() {
printMessage(); // Output: Hello, World!
return 0;
}
b) Functions with Return Type
Example:
int multiply(int a, int b) {
return a * b;
}
int main() {
int result = multiply(3, 4);
cout << result; // Output: 12
return 0;
}
c) Functions with No Parameters
Example:
int getRandomNumber() {
return rand();
}
int main() {
cout << getRandomNumber();
return 0;
}
d) Functions with Default Arguments
• Default values can be assigned to parameters. If the caller does not provide a value, the
default is used.
Example:
int add(int a, int b = 10) {
return a + b;
}
int main() {
cout << add(5); // Output: 15 (uses default b = 10)
cout << add(5, 3); // Output: 8 (overrides default b)
return 0;
}
5. Function Overloading
• Multiple functions can have the same name but different parameters (number or type).
Example:
int add(int a, int b) {
return a + b;
}
int main() {
cout << add(5, 10) << endl; // Output: 15 (int version)
cout << add(3.5, 2.5) << endl; // Output: 6.0 (double version)
return 0;
}
6. Recursive Functions
• A function that calls itself is called a recursive function.
Example:
int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}
int main() {
cout << factorial(5); // Output: 120
return 0;
}
7. Inline Functions
• Inline functions are expanded in place (like macros) to reduce the overhead of function
calls.
Syntax:
inline return_type function_name(parameters) {
// Function body
}
Example:
inline int square(int x) {
return x * x;
}
int main() {
cout << square(5); // Output: 25
return 0;
}
Example:
void increment(int x) {
x++;
}
int main() {
int a = 5;
increment(a);
cout << a; // Output: 5 (unchanged)
return 0;
}
b) Pass by Reference
Example:
void increment(int &x) {
x++;
}
int main() {
int a = 5;
increment(a);
cout << a; // Output: 6 (changed)
return 0;
}
Syntax:
[capture](parameters) -> return_type {
// Function body
}
Example:
auto add = [](int a, int b) -> int {
return a + b;
};
int main() {
cout << add(5, 10); // Output: 15
return 0;
}
int main() {
double radius;
cout << "Enter radius: ";
cin >> radius;
cout << "Area: " << calculateArea(radius);
return 0;
}
int main() {
int result = add(5, 10);
cout << "Sum: " << result;
return 0;
}
15. Numbers
Numbers in C++
In C++, numbers are represented using numeric data types like int, float, double, etc. C++
provides a wide range of mathematical operations and functions to work with numbers.
+ Addition 5+3 →8
- Subtraction 5-3 →2
* Multiplication 5*3 → 15
/ Division 5/2 →2
3. Mathematical Functions
C++ provides a <cmath> library for advanced mathematical operations.
Example:
#include <cmath>
#include <iostream>
using namespace std;
int main() {
cout << sqrt(25) << endl; // Output: 5
cout << pow(2, 3) << endl; // Output: 8
cout << abs(-10) << endl; // Output: 10
cout << ceil(3.2) << endl; // Output: 4
cout << floor(3.8) << endl; // Output: 3
cout << round(3.5) << endl; // Output: 4
return 0;
}
4. Random Numbers
Random numbers can be generated using the <cstdlib> and <ctime> libraries.
Example:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main() {
srand(time(0)); // Seed the random number generator
int randomNum = rand() % 100; // Random number between 0 and 99
cout << "Random number: " << randomNum;
return 0;
}
5. Number Formatting
C++ provides tools to format numbers, such as setting precision for floating-point numbers.
Example:
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
double pi = 3.141592653589793;
cout << fixed << setprecision(2); // Set precision to 2 decimal places
cout << "Pi: " << pi << endl; // Output: Pi: 3.14
return 0;
}
6. Type Conversion
Example:
int a = 10;
double b = 3.5;
// Implicit conversion
double result1 = a + b; // int + double → double
cout << result1 << endl; // Output: 13.5
For very large numbers, use the long long data type.
Example:
long long bigNum = 1234567890123456789LL;
cout << bigNum << endl; // Output: 1234567890123456789
8. Common Pitfalls
1. Integer Division:
o Dividing two integers results in an integer (truncates the decimal part).
2. int a = 5, b = 2;
3. cout << a / b; // Output: 2 (not 2.5)
4. Overflow:
o Exceeding the range of a data type can cause unexpected behavior.
5. int a = 2147483647; // Maximum value for int
6. cout << a + 1; // Output: -2147483648 (overflow)
7. Precision Loss:
o Floating-point numbers may lose precision due to their limited representation.
8. float f = 0.1f;
9. cout << f; // Output: 0.1 (but may not be exact)
int main() {
double principal = 1000, rate = 0.05, time = 5;
double amount = principal * pow(1 + rate, time);
cout << "Compound Interest: " << amount - principal;
return 0;
}
• Math Operations:
#include <cmath>
cout << sqrt(16); // Output: 4
• Random Numbers:
#include <cstdlib>
#include <ctime>
srand(time(0));
cout << rand(); // Output: Random number
16. Arrays
• Arrays: Store multiple values of the same type.
Arrays in C++
An array is a collection of elements of the same data type stored in contiguous memory
locations. Arrays are used to store multiple values in a single variable, making it easier to
manage and manipulate data.
1. Declaring an Array
Syntax:
data_type array_name[array_size];
Example:
int numbers[5]; // Declares an array of 5 integers
2. Initializing an Array
Example:
int numbers[5] = {10, 20, 30, 40, 50}; // Initializes an array with 5 values
Syntax:
array_name[index];
Example:
int numbers[5] = {10, 20, 30, 40, 50};
cout << numbers[0]; // Output: 10
cout << numbers[2]; // Output: 30
4. Modifying Array Elements
Example:
int numbers[5] = {10, 20, 30, 40, 50};
numbers[1] = 25; // Changes the second element to 25
cout << numbers[1]; // Output: 25
Example:
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " "; // Output: 10 20 30 40 50
}
6. Multidimensional Arrays
Syntax:
data_type array_name[row_size][column_size];
Example:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Accessing elements
cout << matrix[0][1]; // Output: 2
Iterating Through a 2D Array:
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
Arrays can be passed to functions by reference (the array name is a pointer to its first element).
Example:
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
printArray(numbers, 5); // Output: 10 20 30 40 50
return 0;
}
8. Array Limitations
For arrays with a size determined at runtime, use dynamic memory allocation.
Example:
int* arr = new int[5]; // Dynamically allocate an array of size 5
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
delete[] arr; // Free the allocated memory
The <array> header provides a safer and more flexible alternative to traditional arrays.
Example:
#include <array>
#include <iostream>
using namespace std;
int main() {
array<int, 5> numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < [Link](); i++) {
cout << numbers[i] << " "; // Output: 10 20 30 40 50
}
return 0;
}
11. Common Array Operations
a) Finding the Largest Element
int numbers[5] = {10, 20, 30, 40, 50};
int max = numbers[0];
for (int i = 1; i < 5; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
cout << "Max: " << max; // Output: Max: 50
b) Sum of Array Elements
int numbers[5] = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
cout << "Sum: " << sum; // Output: Sum: 150
c) Reversing an Array
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5 / 2; i++) {
swap(numbers[i], numbers[4 - i]);
}
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " "; // Output: 50 40 30 20 10
}
Strings are used to store and manipulate sequences of characters. In C++, strings can be
handled in two ways:
1. C-Style Strings
Syntax:
char string_name[size];
Example:
char name[20] = "John"; // Declares a C-style string
• Direct Initialization:
• char name[] = "John"; // Automatically adds '\0' at the end
• Character-by-Character Initialization:
• char name[5] = {'J', 'o', 'h', 'n', '\0'};
Example:
char name[] = "John";
cout << name[0]; // Output: J
cout << name[2]; // Output: h
strstr(str, substr) Finds the first occurrence of substr in str strstr("Hello", "lo") → "lo"
Example:
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
The std::string class (from the <string> library) provides a more convenient and safer way to
handle strings.
Syntax:
#include <string>
using namespace std;
string string_name;
Example:
#include <string>
#include <iostream>
using namespace std;
int main() {
string name = "John";
cout << name; // Output: John
return 0;
}
6. Common std::string Operations
Operation Description Example
[Link]() Returns the length of the string [Link]() →4
[Link](pos, len, str2) Replaces part of the string with str2 [Link](1, 2, "ane") → "Jane"
Example:
#include <string>
#include <iostream>
using namespace std;
int main() {
string name = "John";
cout << [Link]() << endl; // Output: 4
[Link](" Doe");
cout << name << endl; // Output: John Doe
cout << [Link](5, 3) << endl; // Output: Doe
return 0;
}
int main() {
string str = "madam";
string reversed = str;
reverse([Link](), [Link]());
if (str == reversed) {
cout << "Palindrome!";
} else {
cout << "Not a palindrome!";
}
return 0;
}
18. Pointers
Pointers in C++
Pointers are variables that store memory addresses of other variables. They are a powerful
feature of C++ that allows for dynamic memory management, efficient array handling, and
passing large structures to functions.
1. Pointer Declaration
Syntax:
data_type* pointer_name;
Example:
int* ptr; // Declares a pointer to an integer
Use the address-of operator (&) to get the memory address of a variable.
Example:
int num = 10;
int* ptr = # // ptr now holds the address of num
3. Accessing Values Using Pointers
Use the dereference operator (*) to access the value stored at the memory address a pointer
points to.
Example:
int num = 10;
int* ptr = #
cout << *ptr; // Output: 10 (value at the address stored in ptr)
4. Pointer Arithmetic
Pointers support arithmetic operations like addition, subtraction, increment, and decrement.
These operations are based on the size of the data type the pointer points to.
Example:
int arr[3] = {10, 20, 30};
int* ptr = arr; // Points to the first element of the array
Arrays and pointers are closely related. The name of an array is a pointer to its first element.
Example:
int arr[3] = {10, 20, 30};
int* ptr = arr; // ptr points to the first element of arr
6. Pointers to Pointers
Syntax:
data_type** pointer_name;
Example:
int num = 10;
int* ptr = #
int** ptr2 = &ptr; // ptr2 points to ptr
Pointers are used to manage dynamic memory (memory allocated at runtime) using new and
delete.
a) Allocating Memory
int* ptr = new int; // Allocates memory for one integer
*ptr = 10; // Assigns a value to the allocated memory
b) Deallocating Memory
delete ptr; // Frees the allocated memory
c) Allocating Arrays
int* arr = new int[5]; // Allocates memory for an array of 5 integers
arr[0] = 10; // Assigns a value to the first element
delete[] arr; // Frees the allocated array memory
Pointers can be passed to functions to modify the original variable or to avoid copying large
data structures.
Example:
void increment(int* ptr) {
(*ptr)++; // Increments the value at the address stored in ptr
}
int main() {
int num = 10;
increment(&num); // Passes the address of num
cout << num; // Output: 11
return 0;
}
A null pointer does not point to any memory location. It is used to indicate that the pointer is not
initialized or is invalid.
Example:
int* ptr = nullptr; // Modern C++ (preferred)
int* ptr2 = NULL; // Older C++ (avoid)
int* ptr3 = 0; // Avoid (confusing)
1. Dangling Pointers: Pointers that point to memory that has been freed.
2. int* ptr = new int;
3. delete ptr;
4. // ptr is now a dangling pointer
5. Memory Leaks: Forgetting to free dynamically allocated memory.
6. int* ptr = new int;
7. // Forgot to delete ptr
8. Uninitialized Pointers: Using a pointer before assigning it a valid address.
9. int* ptr;
10. *ptr = 10; // Undefined behavior
int main() {
int x = 10, y = 20;
swap(&x, &y);
cout << "x: " << x << ", y: " << y; // Output: x: 20, y: 10
return 0;
}
19. References
References in C++
References are aliases for existing variables. They provide an alternative way to access and
manipulate data without using pointers. References are safer and easier to use than pointers
because they cannot be null and cannot be reassigned to refer to a different variable.
1. Reference Declaration
Syntax:
data_type& reference_name = variable_name;
Example:
int num = 10;
int& ref = num; // ref is a reference to num
2. Using References
Example:
int num = 10;
int& ref = num;
Memory Address Does not have its own memory address Has its own memory address
References are commonly used to pass arguments to functions by reference, allowing the
function to modify the original variable.
Example:
void increment(int& ref) {
ref++; // Modifies the original variable
}
int main() {
int num = 10;
increment(num); // Passes num by reference
cout << num; // Output: 11
return 0;
}
Functions can return references, but care must be taken to avoid returning references to local
variables (which go out of scope after the function ends).
Example:
int& getLarger(int& a, int& b) {
return (a > b) ? a : b;
}
int main() {
int x = 10, y = 20;
getLarger(x, y) = 30; // Modifies the larger variable (y)
cout << y; // Output: 30
return 0;
}
6. const References
Example:
void print(const int& ref) {
cout << ref; // Can read but not modify ref
}
int main() {
int num = 10;
print(num); // Passes num by const reference
return 0;
}
7. References and Arrays
Example:
int arr[3] = {10, 20, 30};
int(&ref)[3] = arr; // ref is a reference to the array
8. Common Pitfalls
1. Uninitialized References:
o References must be initialized when declared.
2. int& ref; // Error: Reference must be initialized
3. Returning References to Local Variables:
o Returning a reference to a local variable results in undefined behavior.
4. int& badFunction() {
5. int num = 10;
6. return num; // Error: num goes out of scope
7. }
9. Best Practices
1. Use references to avoid copying large objects when passing them to functions.
2. Prefer const references when you don’t need to modify the original variable.
3. Avoid returning references to local variables.
4. Use references instead of pointers when possible for safer and cleaner code.
int main() {
int x = 10, y = 20;
swap(x, y); // Passes x and y by reference
cout << "x: " << x << ", y: " << y; // Output: x: 20, y: 10
return 0;
}