Array Based on Previous PF and Printing Array-1
Array Based on Previous PF and Printing Array-1
ON PREVIOUS
PF AND
PRINTING
ARRAY
Mam Iram
TABLE OF CONTENT
Array based on previous PF and
Printing array (loop, pointer addresses)
Time and space complexity
§ Passing array by reference
§ Object Array, pointer to (integer,
character and object) array
OOP concepts (static vs Dynamic Array)
in c++
ARRAYS IN C++: CONCEPTS AND PRACTICES
Arrays in C++ are fundamental data
structures used to store collections of
data elements of the same type. This
guide integrates key aspects of arrays
with problem-solving techniques, object-
oriented programming (OOP) principles,
and practical topics in C++.
1. TYPES OF ARRAYS
Static vs Dynamic Arrays
Static Arrays:
Size is fixed at compile time.
Stored in the stack.
Memory allocation occurs during program
compilation.
Example:
Example:
int* dynamic Array = new int[5];
for (int i = 0; i < 5; i++)
{
dynamic Array[i] = i + 1;
}
Advantages: Flexible size and efficient memory
usage.
Limitations: Must manage memory
explicitly using delete[].
OBJECT ARRAYS
Arrays can store objects of a class, enabling
encapsulation and abstraction.
Example:
class Student
{
public:
string name;
int age;
Student(string n, int a) : name(n), age(a) { }
};
Student students[3] = {Student("Alice", 20),
Student("Bob", 22), Student("Charlie", 21)};
POINTERS TO ARRAYS
Using Loops
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++)
{
cout << arr[i] << " ";
}
Using Pointers
int arr[5] = {1, 2, 3, 4, 5};
int* ptr = arr;
for (int i = 0; i < 5; i++)
{
cout << *(ptr + i) << " ";
}
Printing Addresses
for (int i = 0; i < 5; i++)
{
cout << &arr[i] << " ";
}
4. TIME AND SPACE COMPLEXITY
Time Complexity
Access: O(1) (Direct access using an index).
Traversal: O(n)
Insertion/Deletion:
Static Arrays: O(n) (due to shifting elements).
Dynamic Arrays: O(n) (if resizing is required).
Space Complexity
Static Arrays: Requires pre-allocated memory (O(n)).
Dynamic Arrays: Includes the memory for elements
plus overhead for managing dynamic allocation.
Practical Example
#include <iostream>
using namespace std;
class Product
{ public:
string name;
double price;
Product(string n, double p) : name(n), price(p) {}
void display()
{
cout << "Product: " << name << ", Price: $" << price << endl;
}
};
int main()
{
Product* products = new Product[3]
{
Product("Laptop", 999.99), Product("Phone", 699.99), Product("Tablet",
499.99)
};
for (int i = 0; i < 3; i++)
{
products[i].display();
}
This program demonstrates a dynamic array of
objects with encapsulated properties and
methods.
By leveraging C++'s flexibility, you can use
static and dynamic arrays effectively, optimize
memory management, and apply OOP
principles for enhanced modularity and
abstraction.
Any Question
Thanks