Data Structure Mid
Data Structure Mid
Array
An array can hold a series of elements of the same type placed in contiguous memory locations.
Declaration Syntax:
Initialization Syntax:
Example: 23-51455-1
int arr [10] ; // Declaring a 1D array of size 10
1. Direct Initialization
#include <iostream>
using namespace std;
int main()
{
int num [5] ;
cout<<"Enter array elements : \n";
for(int i = 0; i < 5 ; i++)
{
cin >> num[i] ;
}
}
Output –
23-51455-1
Enter array elements :
1
3
5
7
9
Accessing 1D Array Elements:
Example 1
cout << arr[3] ; // arr[3] i.e. index 3 of array will print the value 7
Example 2
23-51455-1
for (int i = 0; i < 5; i++)
{
cout << arr[i] << " ";
}
Output
10 15 45 20 25 6 1 100 65 99
Input (Declarations and Initializations): int arr[10], int sum = 0. // soa= size of array.
Calculation Steps:
Process:
23-51455-1
int arr[] = {10, 15, 45, 20, 25, 6, 1, 100, 65, 99};
int sum = 0;
cout << sum; // The output should be the sum of all elements
10 15 45 20 25 6 1 100 65 99
Input (Declarations and Initializations): int arr[10], int sum = 0. // soa= size of array.
Calculation Steps:
23-51455-1
arr[9] % 2 == 1 -> sum = sum + arr[9] -> sum = 151 + 99 = 250
Process:
int arr[] = {10, 15, 45, 20, 25, 6, 1, 100, 65, 99};
int sum = 0;
cout << sum; // The output should be the sum of odd elements
Problem 3: Find the number of even elements in the array.
10 15 45 20 25 6 1 100 65 99
Calculation Steps:
Process:
23-51455-1
int arr[] = {10, 15, 45, 20, 25, 6, 1, 100, 65, 99};
int count = 0;
cout << count; // The output should be the number of even elements
Problem 4: Find the minimum element of the array.
10 15 45 20 25 6 1 100 65 99
Calculation Steps:
Process: 23-51455-1
for (int i = 1; i < ; i++) {
if (arr[i] < min_element) {
min_element = arr[i];
}
}
cout << "Minimum element: " << min_element << endl; // The output should be the minimum
element 1.
Problem 5: Search for an element in an array.
10 15 45 20 25 6 1 100 65 99
Input (Declarations and Initializations):int arr[soa] ,int item = 25; int position = -1;
Calculation Steps:
Process:
23-51455-1
for (int i = 0; i < soa; i++) {
if (arr[i] == item) {
position = i;
break;
}
}
if (position != -1) {
cout << "Element " << item << " found at position: " << position << endl;
} else {
cout << "Element " << item << " not found in the array." << endl;
}
Problem 6: To find the number of times an element appears in an array.
10 15 45 20 25 6 1 100 65 99
Input (Declarations and Initializations):int arr[soa] ,int item = 25; int count = 0;
Calculation Steps:
For the array {10, 15, 45, 20, 25, 6, 1, 100, 65, 99, 25, 45, 25, 100} and item = 25:
The loop iterates through the array:
Index 0: arr[0] = 10 (not equal to 25)
Index 1: arr[1] = 15 (not equal to 25)
Index 2: arr[2] = 45 (not equal to 25)
Index 3: arr[3] = 20 (not equal to 25)
Index 4: arr[4] = 25 (equal to 25, count = 1)
Index 5: arr[5] = 6 (not equal to 25)
Index 6: arr[6] = 1 (not equal to 25)
Index 7: arr[7] = 100 (not equal to 25)
Index 8: arr[8] = 65 (not equal to 25)
23-51455-1
Index 9: arr[9] = 99 (not equal to 25)
Index 10: arr[10] = 25 (equal to 25, count = 2)
Index 11: arr[11] = 45 (not equal to 25)
Index 12: arr[12] = 25 (equal to 25, count = 3)
Index 13: arr[13] = 100 (not equal to 25)
Thus, the element 25 appears 3 times in the array.
Process:
int soa = sizeof(arr) / sizeof(arr[0]); // size of the array
cout << "Element " << item << " appears " << count << " times in the array." << endl;
Problem 7: Merge two arrays into one array.
40 30 70 90 100
10 15 45 20 65 6 1
40 30 70 90 100 10 15 45 20 65 6 1
Input (Declarations and Initializations): int arr1[size1], int arr2[size2], int m_array[size1+size2].
Process:
int arr1[] = {40, 30, 70, 90, 100};
int arr2[] = {10, 15, 45, 20, 65, 6, 1};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int m_array[size1 + size2];
}
m_array[i] = arr1[i];
23-51455-1
// Store elements of arr2 in m_array starting from index size1
for (int i = 0; i < size2; i++) {
m_array[size1 + i] = arr2[i];
}
dataType arrayName[rows][columns];
dataType: The type of data you want to store (e.g., int, double, char).
arrayName: A name to identify your array.
rows: The number of rows in your array.
columns: The number of columns in your array.
Example:
int grades[3][4]; // 3 students, 4 subjects
Initialization
Method 1:
23-51455-1
int Arr[3][3] = {
{0, 1, 2} , /* initializers for row indexed by 0 */
{4, 5, 6} , /* initializers for row indexed by 1 */
{8, 9, 10} /* initializers for row indexed by 2 */
};
Method 2:
int threeD[5][10][4];
2-D Arrays in C++ Example Program:
#include<iostream>
using namespace std;
int main()
{
int A[2][2];
// take input from user using 2 for loops
cout<<"Enter values of 2-D array A: "<<endl;
for(int i=0;i<2;i++)
{
for(int j = 0; j<2;j++)
{
cin>>A[i][j];
}
}
// print 2-d Array values as output on console
cout<<"Values of 2-D array A: "<<endl;
for(int i=0;i<2;i++)
{
for(int j = 0; j<2;j++)
{
}
23-51455-1
cout<<A[i][j]<<" ";
cout<<endl;
}
return 0;
}
Output
Enter Value of 2-D array A:
1234
Values of 2-D array A:
12
34
Problem 1: Find the summation of the elements of a 2D array.
0 1 2
0
12 5 8
1
6 7 4
2
18 9 2
Calculation Steps:
Start with sum = 0.
Iterate through the array:
arr[0][0] = 12 -> sum = sum + 12 = 12
arr[0][1] = 5 -> sum = sum + 5 = 17
arr[0][2] = 8 -> sum = sum + 8 = 25
arr[1][0] = 6 -> sum = sum + 6 = 31
arr[1][1] = 7 -> sum = sum + 7 = 38
arr[1][2] = 4 -> sum = sum + 4 = 42
arr[2][0] = 18 -> sum = sum + 18 = 60
arr[2][1] = 9 -> sum = sum + 9 = 69
23-51455-1
arr[2][2] = 2 -> sum = sum + 2 = 71
Process:
#include <iostream>
using namespace std;
int main() {
int arr[3][3] = {
{12, 5, 8},
{6, 7, 4},
{18, 9, 2}
};
int sum = 0;
cout << "The summation of the elements of the 2D array is: " << sum << endl;
return 0;
}
Problem 2: Find the summation of two 2D arrays and store the result in another 2D array.
0 1 2 0 1 2 0 1 2
0 0 0
12 5 8 2 8 18 14 13 26
1 1 1
6 7 4 + 16 14 5 = 22 21 9
2 2 2
18 9 2 8 19 12 26 28 24
Input (Declarations and Initializations): int A[3][3], int B[3][3], int S[3][3];
Process:
// Iterate through each element of the 2D arrays and calculate the sum
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
S[i][j] = A[i][j] + B[i][j];
}
}
23-51455-1
for (int j = 0; j < 3; j++) {
cout << S[i][j] << " ";
}
cout << endl;
}
Calculation Steps
S[0][0] = A[0][0] + B[0][0] = 12 + 2 = 14
S[0][1] = A[0][1] + B[0][1] = 5 + 8 = 13
S[0][2] = A[0][2] + B[0][2] = 8 + 18 = 26
S[1][0] = A[1][0] + B[1][0] = 6 + 16 = 22
S[1][1] = A[1][1] + B[1][1] = 7 + 14 = 21
S[1][2] = A[1][2] + B[1][2] = 4 + 5 = 9
S[2][0] = A[2][0] + B[2][0] = 18 + 8 = 26
S[2][1] = A[2][1] + B[2][1] = 9 + 19 = 28
S[2][2] = A[2][2] + B[2][2] = 2 + 12 = 14
Output
The summation of the two 2D arrays is:
14 13 26
22 21 9
26 28 14
Problem 3: Find the Summation of the boundary elements of a 2D array.
0 1 2 3
0 12 5 8 10
1 6 7 4 11
2 18 9 2 1
3 20 3 15 13
Process:
#include <iostream>
using namespace std;
int main() {
int arr[4][4] = {{12, 5, 8, 10},
{6, 7, 4, 11},
{18, 9, 2, 1},
cout << "Summation of boundary elements: " << sum << endl;
return 0;
}
Output:
Summation of boundary elements: 122
Problem 4: Find the summation of the diagonal elements of a 2D array.
0 1 2 3 0 1 2 3 4
0 12 5 8 10 0 12 5 8 10 18
1 6 7 4 11 1 6 7 4 11 21
2 18 9 2 1 2 18 9 2 1 31
3 20 3 15 13 3 20 3 15 13 28
4 30 3 35 23 29
Process:
int n = 5; // Size of the square matrix
int sum = 0;
23-51455-1
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
if (r == c || (r + c) == (n - 1)) {
sum += arr[r][c];
}
}
}
cout << "Sum of diagonal elements: " << sum <<endl;
Problem 5: Find the transpose matrix of a 2D Array.
0 1 2 3 0 1 2 3 4
0 0
12 5 8 10 12 6 18 20 30
1 1
6 7 4 11 5 7 9 3 21
2 2
18 9 2 1 ---Transpose—>> 8 4 2 15 35
3 3
20 3 15 13 10 11 1 3 23
4
30 21 35 23
Process:
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < 5; ++c) {
A_Tr[c][r] = A[r][c]; // Store the transpose element
}
}
23-51455-1
Defining a Structures in C++
To define a structure, you must use the struct keyword. The struct statement defines a
new data type, with more than one member, for your program.
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
}book;
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access.
cout<<book.title;
cout<<book.author;
cout<<book.subject;
cout<<book.id;
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
23-51455-1
float salary;
};
int main()
{
Person p1;
return 0;
}
Output:
Enter Full name: Tanvir Rahman
Enter age: 21
Enter salary: 50000
Displaying Information.
Name: Tanvir Rahman
Age: 21
Salary: 50000
Array of Structures:
#include <iostream>
#include <string>
int main()
{ 23-51455-1
// creating array of struct type Customer
Customer customerRecords[2];
// initializing values
customerRecords[0] = {25, "Bob Jones"};
customerRecords[1] = {26, "Jim Smith"};
/* initialization can also be done like this:
customerRecords[0].id=25;
customerRecords[1].id=26;
customerRecords[0].name="Bob Jones";
customerRecords[1].name="Jim Smith";
*/
// printing values
for(int i=0;i<2;i++)
{
cout<<"Customer-"<<(i+1)<<" ID: "<<customerRecords[i].id<<endl;
cout<<"Customer-"<<(i+1)<<" Name: "<<customerRecords[i].name<<endl;
}
return 0;
}
Output:
Customer-1 ID: 25
Customer-1 Name: Bob Jones
Customer-2 ID: 26
Customer-2 Name: Jim Smith
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
23-51455-1
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "C++ Tutorials");
strcpy( Book1.author, "Tanvir Rahman");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 21231;
// book 2 specification
strcpy( Book2.title, "Data Structure");
strcpy( Book2.author, "Noor");
strcpy( Book2.subject, "DS");
Book2.book_id = 6495;
return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
Output:
Book title : C++ Tutorials
Book author : Tanvir Rahman
Book subject : C++ Programming
Book id : 21231
Book title : Data Structure
Book author : Noor
Book subject : DS
Book id : 6495
23-51455-1
Data Structure OBE:
Answer:
1.
struct Customer {
int customerId;
string customerName;
23-51455-1
string phoneNo;
int age;
};
2.
// Count customers older than 30
int count = 0;
for (int i = 0; i < size; i++) {
if (clist[i].age > 30) {
count++;
}
}
Basic Concept:
int x = 10;
x Value 10
x Memory Address AAAABBB0
cout<<x; Output: 10
cout<<&x; Output: AAAABBB0
p Value
p Memory Address AAAADDDD
p = &x;
p Value AAAABBB0
p Memory Address AAAADDDD
cout<<p; 23-51455-1
Output: AAAABBB0
q Value
q Memory Address BBBBDDDD
q = &p;
q Value AAAADDDD
q Memory Address BBBBDDDD
x = 20;
cout<<x<<endl; 20
cout<<*p 20
cout<<*q 20
*p = 30
cout<<*p 30
cout<<*q 30
(*q)++
cout<<*p 31
int arr[10];
cout<<*arr<<endl;
23-51455-1
int *a;
a = &arr[0];
cout<<*a<<endl;
cout<<arr[0]<<endl; 12
cout<<*arr<<endl; 12
cout<<*(arr+1)<<endl; 25
cout<<*(arr+5)<<endl; 23
cout<<*a<<endl; 12
cout<<*(a+1)<<endl; 25
cout<<*(a+5)<<endl; 23
Passing Pointer inside function
int main( )
{
int x = 10;
int y = 20;
} 23-51455-1
return &r;
int main( )
{
int x = 10;
int y = 20;
int *z = add(x,y);
}
C++ Pointer to an Array
Now lets create a pointer variable of integer type and assign the address of the array Arr to this
pointer.
int *p;
p = Arr;// or p = &arr[0];
23-51455-1
Example 1 of Pointer to Array in C++:
#include <iostream>
using namespace std;
int main()
{
float arr[5];
float *ptr;
cout << "Displaying address using arrays: " << endl;
for (int i = 0; i < 5; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}
// ptr = &arr[0]
ptr = arr;
cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}
23-51455-1
return 0;
}
Output
Displaying address using arrays:
&arr[0] = 0x7ffe1acbc850
&arr[1] = 0x7ffe1acbc854
&arr[2] = 0x7ffe1acbc858
&arr[3] = 0x7ffe1acbc85c
&arr[4] = 0x7ffe1acbc860
#include <iostream>
using namespace std;
int main() {
float arr[5];
return 0;
23-51455-1
}
Output:
Enter 5 numbers: 50
35
5
5
20
Displaying data:
50
35
5
5
20
Stack
A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This means
the last element inserted inside the stack is removed first.
You can think of the stack data structure as the pile of plates on top of another.
23-51455-1
Stack representation similar to a pile of plate
And, if you want the plate at the bottom, you must first remove all the plates on top. This is
exactly how the stack data structure works.
LIFO Principle of Stack:
In programming terms, putting an item on top of the stack is called push and removing an item
is called pop
23-51455-1
Stack Push and Pop Operations
Stack Operations:
size = 6
int S[size]
top = 0
Empty: if(top == 0)
Full: if(top == size)
push(x): insert x at top position and increase the value of top by 1.
pop( ): decrease the value of top by 1.
getTopElement( ): returns the element in top-1 position.
print( ): print the stack from top-1 to 0.
Stack Implementation
Procedural Approach
int S[size];
int top=0;
class MyStack
{
int S[size]
int top = 0;
public:
23-51455-1
bool isEmpty(){. . .}
bool isFull(){. . .}
bool push(int element){. . .}
bool pop(){. . .}
int getTopElement(){. . .}
void show(){. . .}
};
int main()
{
MyStack ms1, ms2;
ms1.push(10);
ms2.push(11);
return 0;
}
Stack Applications:
Mathematical Expression
23-51455-1
Input: Infix Expression
Process:
Output: Result.
Part 1: Validate the Infix Expression
9 * [ 7 - 1 + ( 5 + 1 / 2 ) * 3 - { ( 6 + 3 ) - 8 } + 4 ]
(
( { { {
[ [ [ [ [ [ [
1 2 3 4 5 6 7 8
Process:
23-51455-1
a. If it is an opening parenthesis, push it in the stack.
b. Else if it is a closing parenthesis, check the top element of the stack.
i. If it pairs up with the current symbol, pop from stack and the
expression might be valid.
ii. Else, it does not pair up with the current symbol, the expression is
invalid. Exit.
c. Else, it is an operator or operand, ignore.
3. Repeat 1 and 2 till the end of the expression.
4. If the stack is empty, the expression is valid. Else, the expression is invalid.
9 * [ 7 - 1 + ( 5 + 1 / 2 ) * 3 - { ( 6 + 3 ) - 8 } + 4 ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
9 7 1 - 5 1 2 / + 3 * + 6 3 + 8 - - 4 + *
/ / + +
+ + + + ( ( ( ( - -
( ( ( ( ( ( * * { { { { { { { {
- - + + + + + + + + + + - - - - - - - - - - + +
[ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
23-51455-1
Current + / * - - +
Top - + + * + -
Process:
4. At the end of the expression, pop all the elements from stack and insert in postfix expression.
23-51455-1
Part 3: Evaluate the postfix expression
9 7 1 - 5 1 2 / + 3 * + 6 3 + 8 - - 4 + *
1 1 0 3 3 8
1 5 5 5 5 5 5 15 6 6 9 9 1 4
7 7 6 6 6 6 6 6 6 6 21 21 21 21 21 21 20 20 24
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 216
23-51455-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
B Op A Result
7 - 1 6
1 / 2 0
5 + 0 5
5 * 3 15
6 + 15 21
6 + 3 9
9 - 8 1
21 - 1 20
20 + 4 24
9 * 24 216
Input and Initializations: char postfixExpr[ ], int evaluationStack[ ];
Process:
3. At the end of the expression, the top element of the stack is the result of the postfix expression.
Output: result
23-51455-1
9 7 1 - 5 1 2 / + 3 * + 6 3 + 8 - - 4 + *
9 * [ 7 - 1 + ( 5 + 1 / 2 ) * 3 - { ( 6 + 3 ) - 8 } + 4 ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
= 9 * [7 – 1 + (5 + 0) * 3 – {9 – 8} + 4]
= 9 * [7 – 1 + 5 * 3 – 1 + 4]
= 9 * [7 – 1 + 15 – 1 +4]
= 9 * [26 – 2]
= 9 * 24
= 216
Queue
A queue is a linear data structure where elements are stored in the FIFO (First In
First Out) principle where the first element inserted would be the first element to be
accessed.
Queue follows the First In First Out (FIFO) rule - the item that goes in first is the item that comes
out first.
23-51455-1
● Like stack, queue is also an ordered list of elements of similar data types.
● Queue is a FIFO( First in First Out ) structure.
● Once a new element is inserted into the Queue, all the elements inserted before the new
element in the queue must be removed, to remove the new element.
● peek() function is used to return the value of first element without dequeuing it.
1. Enqueue
2. Dequeue
Linear Queue:
Queue Operations:
size = 5
23-51455-1
Linear Queue Implementation Circular Queue Implementation
const int size = 100; // Define the size const int size = 100; // Define the size
of the queue of the circular queue
public: public:
bool isEmpty() { bool isEmpty() {
return (front == -1 && rear == return (front == -1 && rear ==
-1); -1);
} }
23-51455-1
bool isFull() { bool isFull() {
return (rear == size - 1); return (front == (rear + 1) %
} size);
}
bool enqueue(int element) {
if (isFull()) { bool enqueue(int element) {
return false; if (isFull()) {
} else if (isEmpty()) { return false;
front = rear = 0; } else if (isEmpty()) {
} else { front = rear = 0;
rear++; } else {
} rear = (rear + 1) % size;
Q[rear] = element; }
return true; CQ[rear] = element;
} return true;
}
bool dequeue() {
if (isEmpty()) { bool dequeue() {
return false; if (isEmpty()) {
} else if (front == rear) { return false;
front = rear = -1; } else if (front == rear) {
} else { front = rear = -1;
front++; } else {
} front = (front + 1) % size;
return true; }
} return true;
}
int getFrontElement() {
if (isEmpty()) { int getFrontElement() {
return -999999999; if (isEmpty()) {
} else { return -999999999; // Error
return Q[front]; code for empty queue
} } else {
} return CQ[front];
}
void show() { }
if (isEmpty()) {
cout << "Cannot print, the void show() {
queue is empty." << endl; if (isEmpty()) {
} else { cout << "Cannot print, the
for (int i = front; i <= queue is empty." << endl;
rear; i++) { } else {
cout << Q[i] << " "; if (front <= rear) {
} for (int i = front; i <=
cout << endl; rear; i++) {
} cout << CQ[i] << "
23-51455-1
} ";
}; }
} else {
int main() { for (int i = front; i <
MyQueue mq1, mq2; size; i++) {
cout << CQ[i] << "
// Enqueue elements into mq1 ";
mq1.enqueue(10); }
mq1.enqueue(20); for (int i = 0; i <=
mq1.enqueue(30); rear; i++) {
mq1.enqueue(40); cout << CQ[i] << "
";
// Show elements in mq1 }
cout << "Queue mq1 elements: "; }
mq1.show(); cout << endl;
}
// Dequeue elements from mq1 }
mq1.dequeue(); };
cout << "Queue mq1 elements after one
dequeue: "; int main() {
mq1.show(); MyCircularQueue mcq1, mcq2;
23-51455-1
mcq2.enqueue(200);
return 0;
}
23-51455-1