0% found this document useful (0 votes)
81 views30 pages

C++ Revision Guide for Exams

This C++ Revision Guide provides a comprehensive overview of the C++ programming language, covering its key features, advantages, and disadvantages. It includes sections on environment setup, basic syntax, data types, operators, loops, decision-making statements, functions, and mathematical operations. The guide is structured to enhance understanding and prepare for exams, making it a valuable resource for learners.

Uploaded by

Jibril Wk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views30 pages

C++ Revision Guide for Exams

This C++ Revision Guide provides a comprehensive overview of the C++ programming language, covering its key features, advantages, and disadvantages. It includes sections on environment setup, basic syntax, data types, operators, loops, decision-making statements, functions, and mathematical operations. The guide is structured to enhance understanding and prepare for exams, making it a valuable resource for learners.

Uploaded by

Jibril Wk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

This guide is structured to cover all the topics in a clear, concise, and professional manner,

ensuring you have a top-tier understanding of C++ for your exams.

C++ Revision Guide (Enhanced)

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

int main() { // Main function where execution begins


cout << "Hello World!"; // Print "Hello World!"
return 0; // Return 0 to indicate successful execution
}

• 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

• Constants: Used to store data that cannot change.


const int PI = 3.14; // Declare a constant
// PI = 3.15; // Error: Cannot change a constant

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.

10. Storage Classes


• auto: Default storage class for local variables.
• register: Suggests the compiler to store the variable in a CPU register.
• static: Retains the value between function calls.
• extern: Declares a global variable or function in another file.
• mutable: Allows a member of an object to be modified by a const function.

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);

13. Decision-Making Statements


• If Statement:
Executes a block of code if a condition is true.
int age = 18;
if (age >= 18) {
cout << "You are an adult.";
}

• 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

A function definition consists of:

• 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;
}

2. Function Declaration (Prototype)

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)

• These functions do not return any value.


Example:
void printMessage() {
cout << "Hello, World!";
}

int main() {
printMessage(); // Output: Hello, World!
return 0;
}
b) Functions with Return Type

• These functions return a value of a specific 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

• These functions do not take any input.

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;
}

double add(double a, double 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;
}

8. Pass by Value vs. Pass by Reference


a) Pass by Value

• A copy of the argument is passed to the function.


• Changes made to the parameter do not affect the original argument.

Example:
void increment(int x) {
x++;
}

int main() {
int a = 5;
increment(a);
cout << a; // Output: 5 (unchanged)
return 0;
}
b) Pass by Reference

• The memory address of the argument is passed to the function.


• Changes made to the parameter affect the original argument.

Example:
void increment(int &x) {
x++;
}

int main() {
int a = 5;
increment(a);
cout << a; // Output: 6 (changed)
return 0;
}

9. Lambda Functions (C++11 and later)

• Anonymous functions that can be defined inline.

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;
}

10. Best Practices

1. Use meaningful names for functions.


2. Keep functions short and focused on a single task.
3. Use pass by reference to avoid copying large objects.
4. Use const for parameters that should not be modified.
5. Avoid global variables; prefer passing arguments to functions.

Example: Program to Calculate Area of a Circle


#include <iostream>
using namespace std;

// Function to calculate area of a circle


double calculateArea(double radius) {
return 3.14159 * radius * radius;
}

int main() {
double radius;
cout << "Enter radius: ";
cin >> radius;
cout << "Area: " << calculateArea(radius);
return 0;
}

• Functions: Reusable blocks of code.


int add(int a, int b) {
return a + b;
}

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.

1. Numeric Data Types


Data Description Size Range
Type
int Integer numbers 4 bytes -2,147,483,648 to 2,147,483,647
float Single-precision floating- 4 bytes ~7 decimal digits of precision
point
double Double-precision floating- 8 bytes ~15 decimal digits of precision
point
long Larger integer numbers 4 or 8 -2,147,483,648 to 2,147,483,647 (or
bytes larger)
short Smaller integer numbers 2 bytes -32,768 to 32,767
unsigned Non-negative integers Same as int 0 to 4,294,967,295

2. Basic Arithmetic Operations


Operator Description Example

+ Addition 5+3 →8

- Subtraction 5-3 →2

* Multiplication 5*3 → 15

/ Division 5/2 →2

% Modulus (remainder) 5%2 →1


Example:
int a = 10, b = 3;
cout << a + b << endl; // Output: 13
cout << a - b << endl; // Output: 7
cout << a * b << endl; // Output: 30
cout << a / b << endl; // Output: 3 (integer division)
cout << a % b << endl; // Output: 1

3. Mathematical Functions
C++ provides a <cmath> library for advanced mathematical operations.

Function Description Example

sqrt(x) Square root of x sqrt(16) → 4.0

pow(x, y) x raised to the power of y pow(2, 3) → 8.0

abs(x) Absolute value of x abs(-5) →5

ceil(x) Rounds x up to the nearest integer ceil(3.2) → 4.0

floor(x) Rounds x down to the nearest integer floor(3.8) → 3.0

round(x) Rounds x to the nearest integer round(3.5) → 4.0

log(x) Natural logarithm of x log(10) → 2.30259

sin(x), cos(x), tan(x) Trigonometric functions (in radians) sin(0) → 0.0

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

Numbers can be converted between different types using type casting.

Example:
int a = 10;
double b = 3.5;

// Implicit conversion
double result1 = a + b; // int + double → double
cout << result1 << endl; // Output: 13.5

// Explicit conversion (type casting)


int result2 = (int)b + a; // double → int
cout << result2 << endl; // Output: 13
7. Handling Large Numbers

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)

Example: Program to Calculate Compound Interest


#include <cmath>
#include <iostream>
using namespace std;

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

Arrays can be initialized at the time of declaration.

Example:
int numbers[5] = {10, 20, 30, 40, 50}; // Initializes an array with 5 values

• If fewer values are provided, the remaining elements are initialized to 0.


• int numbers[5] = {10, 20}; // [10, 20, 0, 0, 0]
• If no size is specified, the array size is determined by the number of values.
• int numbers[] = {10, 20, 30}; // Size is 3

3. Accessing Array Elements

Array elements are accessed using an index (starting from 0).

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

Array elements can be modified by assigning new values.

Example:
int numbers[5] = {10, 20, 30, 40, 50};
numbers[1] = 25; // Changes the second element to 25
cout << numbers[1]; // Output: 25

5. Iterating Through an Array

Use a loop to access all elements of an array.

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

Arrays can have multiple dimensions (e.g., 2D arrays for matrices).

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;
}

7. Passing Arrays to Functions

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

1. Fixed Size: The size of an array must be known at compile time.


2. No Bounds Checking: Accessing elements outside the array bounds can cause
undefined behavior.
3. Memory Wastage: If the array size is larger than needed, memory is wasted.

9. Dynamic Arrays (Using Pointers)

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

10. Standard Library Arrays (C++11 and later)

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
}

12. Best Practices

1. Use std::array or std::vector for safer and more flexible arrays.


2. Always check array bounds to avoid undefined behavior.
3. Use dynamic arrays when the size is not known at compile time.
4. Prefer range-based for loops for iterating through arrays (C++11 and later).

int numbers[5] = {1, 2, 3, 4, 5};


for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
17. Strings
Strings in C++

Strings are used to store and manipulate sequences of characters. In C++, strings can be
handled in two ways:

1. C-style strings (character arrays).


2. C++ std::string class (from the <string> library).

1. C-Style Strings

C-style strings are arrays of characters terminated by a null character (\0).

Syntax:
char string_name[size];
Example:
char name[20] = "John"; // Declares a C-style string

2. Initializing C-Style Strings

• Direct Initialization:
• char name[] = "John"; // Automatically adds '\0' at the end
• Character-by-Character Initialization:
• char name[5] = {'J', 'o', 'h', 'n', '\0'};

3. Accessing C-Style Strings

• Use indexing to access individual characters.


• Use pointer arithmetic to traverse the string.

Example:
char name[] = "John";
cout << name[0]; // Output: J
cout << name[2]; // Output: h

4. Common C-Style String Functions

The <cstring> library provides functions to manipulate C-style strings.


Function Description Example
strlen(str) Returns the length of the string strlen("Hello") →5
strcpy(dest, src) Copies src to dest strcpy(dest, "Hello")

strcat(dest, src) Concatenates src to dest strcat(dest, "World")

strcmp(str1, str2) Compares two strings (0 if equal) strcmp("Hello", "Hello") →0

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";

cout << strlen(str1) << endl; // Output: 5


strcat(str1, str2);
cout << str1 << endl; // Output: HelloWorld
cout << strcmp(str1, str2) << endl; // Output: Non-zero (not equal)
return 0;
}

5. C++ std::string Class

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]() Same as length() [Link]() →4


[Link](str2) Concatenates str2 to str [Link](" Doe") → "John Doe"

[Link](str2) Compares two strings (0 if equal) [Link]("John") →0

[Link](pos, len) Extracts a substring [Link](1, 2) → "oh"


[Link](substr) Finds the first occurrence of substr [Link]("oh") →1

[Link](pos, len, str2) Replaces part of the string with str2 [Link](1, 2, "ane") → "Jane"

[Link](pos, len) Removes part of the string [Link](1, 2) → "Jn"


[Link](pos, str2) Inserts str2 at position pos [Link](2, "ane") → "Joanen"

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;
}

7. Input and Output with std::string


a) Reading a String from User
string name;
cout << "Enter your name: ";
getline(cin, name); // Reads the entire line
cout << "Hello, " << name << "!";
b) Reading Multiple Words
string firstName, lastName;
cout << "Enter your full name: ";
cin >> firstName >> lastName; // Reads two words
cout << "Hello, " << firstName << " " << lastName << "!";

8. Converting Between C-Style Strings and std::string


a) C-Style String to std::string
char cstr[] = "Hello";
string str = cstr; // Automatically converts
b) std::string to C-Style String
string str = "Hello";
const char* cstr = str.c_str(); // Returns a C-style string

9. Iterating Through a String


a) Using Indexing
string str = "Hello";
for (int i = 0; i < [Link](); i++) {
cout << str[i] << " "; // Output: H e l l o
}
b) Using Range-Based For Loop (C++11 and later)
string str = "Hello";
for (char ch : str) {
cout << ch << " "; // Output: H e l l o
}

10. Common String Manipulations


a) Reversing a String
string str = "Hello";
reverse([Link](), [Link]());
cout << str; // Output: olleH
b) Converting to Uppercase/Lowercase
#include <algorithm>
#include <cctype>

string str = "Hello";


transform([Link](), [Link](), [Link](), ::toupper);
cout << str; // Output: HELLO

11. Best Practices


1. Prefer std::string over C-style strings for better safety and functionality.
2. Use getline() to read strings with spaces.
3. Avoid hardcoding string sizes when using C-style strings.
4. Use c_str() to convert std::string to C-style strings when necessary.
Example: Program to Check if a String is Palindrome
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;

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

2. Assigning Addresses to Pointers

Use the address-of operator (&) to get the memory address of a variable.

Example:
int num = 10;
int* ptr = &num; // 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 = &num;
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

cout << *ptr << endl; // Output: 10


ptr++; // Moves to the next element
cout << *ptr << endl; // Output: 20

5. Pointers and Arrays

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

cout << *(ptr + 1) << endl; // Output: 20 (second element)


cout << ptr[2] << endl; // Output: 30 (third element)

6. Pointers to Pointers

A pointer can point to another pointer, creating a pointer to a pointer.

Syntax:
data_type** pointer_name;
Example:
int num = 10;
int* ptr = &num;
int** ptr2 = &ptr; // ptr2 points to ptr

cout << **ptr2; // Output: 10 (value of num)


7. Dynamic Memory Allocation

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

8. Passing Pointers to Functions

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;
}

9. Pointers and const

• Pointer to a constant: The value pointed to cannot be changed.


• const int* ptr = &num;
• // *ptr = 20; // Error: Cannot modify the value
• Constant pointer: The pointer itself cannot point to a different address.
• int* const ptr = &num;
• // ptr = &anotherNum; // Error: Cannot change the pointer
• Constant pointer to a constant: Neither the pointer nor the value can be changed.
• const int* const ptr = &num;
• // *ptr = 20; // Error: Cannot modify the value
• // ptr = &anotherNum; // Error: Cannot change the pointer
10. Null Pointers

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)

11. Common Pitfalls

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

12. Best Practices

1. Always initialize pointers to nullptr or a valid address.


2. Use smart pointers (std::unique_ptr, std::shared_ptr) for automatic memory management.
3. Avoid raw pointers when possible; prefer references or smart pointers.
4. Always free dynamically allocated memory using delete or delete[].

Example: Program to Swap Two Numbers Using Pointers


#include <iostream>
using namespace std;

void swap(int* a, int* b) {


int temp = *a;
*a = *b;
*b = temp;
}

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

• A reference acts as an alias for the variable it refers to.


• Any changes made to the reference are reflected in the original variable.

Example:
int num = 10;
int& ref = num;

ref = 20; // Modifies num through ref


cout << num; // Output: 20

3. References vs. Pointers


Feature References Pointers

Declaration int& ref = num; int* ptr = &num;

Reassignment Cannot be reassigned Can be reassigned

Null Value Cannot be null Can be null

Memory Address Does not have its own memory address Has its own memory address

Syntax Easier to use (no dereferencing needed) Requires dereferencing (*ptr)


4. Passing References to Functions

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;
}

5. Returning References from Functions

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

• references prevent modification of the original variable.


const
• They are often used to pass large objects to functions without copying them.

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

References can be used to create aliases for arrays.

Example:
int arr[3] = {10, 20, 30};
int(&ref)[3] = arr; // ref is a reference to the array

cout << ref[1]; // Output: 20

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.

Example: Program to Swap Two Numbers Using References


#include <iostream>
using namespace std;

void swap(int& a, int& b) {


int temp = a;
a = b;
b = temp;
}

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;
}

You might also like