0% found this document useful (0 votes)
2 views45 pages

Data Structure Mid

The document provides an overview of arrays in C++, including one-dimensional and two-dimensional arrays, their declaration, initialization, and methods for accessing and manipulating their elements. It includes examples of various operations such as summation of elements, counting even and odd elements, finding minimum values, searching for elements, and merging arrays. Additionally, it presents a simple program for inputting and displaying a 2D array.

Uploaded by

zim12621
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)
2 views45 pages

Data Structure Mid

The document provides an overview of arrays in C++, including one-dimensional and two-dimensional arrays, their declaration, initialization, and methods for accessing and manipulating their elements. It includes examples of various operations such as summation of elements, counting even and odd elements, finding minimum values, searching for elements, and merging arrays. Additionally, it presents a simple program for inputting and displaying a 2D array.

Uploaded by

zim12621
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
You are on page 1/ 45

Name: MD TANVIR RAHMAN ID: 23-51455-1

Array
An array can hold a series of elements of the same type placed in contiguous memory locations.

One Dimensional Array:

Declaration Syntax:

data_type array_name [array_size];

Initialization Syntax:

data_type array_name [array_size] = {comma_separated_element_list};

Example: 23-51455-1
int arr [10] ; // Declaring a 1D array of size 10

int roll_no [5] = {1, 2, 3, 4, 5} ; // Initializing a 1D array of size 5

char names[30] = {"Raj, John, Krish"} ; // Initializing a 1D array of type char


Input Elements in a 1D Array:

1. Direct Initialization

int num [10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10} ;

2. User Input Method

#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:

Note: Array Indexing always starts from 0.

Example 1

# To print a single element of an array

int arr [5] = {1, 3, 5, 7, 9} ;

cout << arr[3] ; // arr[3] i.e. index 3 of array will print the value 7

Example 2

# To print all the elements of an Array

int arr [5] = {1, 3, 5, 7, 9} ;


cout<<"The array elements are: \n";

23-51455-1
for (int i = 0; i < 5; i++)
{
cout << arr[i] << " ";
}

Output

The array elements are:


13579
Problem 1: Find the summation of the numbers of an array.

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:

arr[0] = 10 -> sum = 0 + 10 = 10


arr[1] = 15 -> sum = 10 + 15 = 25
arr[2] = 45 -> sum = 25 + 45 = 70
arr[3] = 20 -> sum = 70 + 20 = 90
arr[4] = 25 -> sum = 90 + 25 = 115
arr[5] = 6 -> sum = 115 + 6 = 121
arr[6] = 1 -> sum = 121 + 1 = 122
arr[7] = 100 -> sum = 122 + 100 = 222
arr[8] = 65 -> sum = 222 + 65 = 287
arr[9] = 99 -> sum = 287 + 99 = 386

Process:

23-51455-1
int arr[] = {10, 15, 45, 20, 25, 6, 1, 100, 65, 99};
int sum = 0;

for (int i = 0; i < 10; i++) {


sum += arr[i];
}

cout << sum; // The output should be the sum of all elements

Output: Print the value of sum.


Problem 2: Summation of odd elements in array.

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:

arr[0] % 2 == 0 -> skip


arr[1] % 2 == 1 -> sum = sum + arr[1] -> sum = 0 + 15 = 15
arr[2] % 2 == 1 -> sum = sum + arr[2] -> sum = 15 + 45 = 60
arr[3] % 2 == 0 -> skip
arr[4] % 2 == 1 -> sum = sum + arr[4] -> sum = 60 + 25 = 85
arr[5] % 2 == 0 -> skip
arr[6] % 2 == 1 -> sum = sum + arr[6] -> sum = 85 + 1 = 86
arr[7] % 2 == 0 -> skip
arr[8] % 2 == 1 -> sum = sum + arr[8] -> sum = 86 + 65 = 151

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;

for (int i = 0; i < 10; i++) {


if (arr[i] % 2 != 0) {
sum += arr[i];
}
}

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

Input (Declarations and Initializations):int arr[10], int count = 0;

Calculation Steps:

arr[0] % 2 == 0 -> count = count + 1 -> count = 1


arr[1] % 2 != 0 -> skip
arr[2] % 2 != 0 -> skip
arr[3] % 2 == 0 -> count = count + 1 -> count = 2
arr[4] % 2 != 0 -> skip
arr[5] % 2 == 0 -> count = count + 1 -> count = 3
arr[6] % 2 != 0 -> skip
arr[7] % 2 == 0 -> count = count + 1 -> count = 4
arr[8] % 2 != 0 -> skip
arr[9] % 2 != 0 -> skip

Process:
23-51455-1
int arr[] = {10, 15, 45, 20, 25, 6, 1, 100, 65, 99};
int count = 0;

for (int i = 0; i < 10; i++) {


if (arr[i] % 2 == 0) {
count++;
}
}

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

Input (Declarations and Initializations):int min_element = arr[0]; int count = 0;

Calculation Steps:

Initialize min to arr[0] which is 10.


Compare arr[1] (15) with min (10): 15 > 10, so min remains 10.
Compare arr[2] (45) with min (10): 45 > 10, so min remains 10.
Compare arr[3] (20) with min (10): 20 > 10, so min remains 10.
Compare arr[4] (25) with min (10): 25 > 10, so min remains 10.
Compare arr[5] (6) with min (10): 6 < 10, so update min to 6.
Compare arr[6] (1) with min (6): 1 < 6, so update min to 1.
Compare arr[7] (100) with min (1): 100 > 1, so min remains 1.
Compare arr[8] (65) with min (1): 65 > 1, so min remains 1.
Compare arr[9] (99) with min (1): 99 > 1, so min remains 1.
Thus, the minimum element of the array is 1.

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:

The loop starts from index 0:


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, so position = 4 and break the loop)

Process:

int soa = sizeof(arr) / sizeof(arr[0]); // size of the array

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

for (int i = 0; i < soa; i++) {


if (arr[i] == item) {
count++;
}
}

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

// Store elements of arr1 in m_array


for (int i = 0; i < size1; i++) {

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

// Output: Print the array m_array


cout << "Merged array m_array: ";
for (int i = 0; i < size1 + size2; i++) {
cout << m_array[i] << " ";
}
cout << endl;

Output: Print the array m_array.


2D Array
A two-dimensional arrays in C++ can be considered as Array of Arrays, which simple
means one array inside another.

General Declaration Syntax:

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 Arr[3][3] = {0,1,2,4,5,6,8,9,10};

Here’s an Example of a 3-D Array declaration:

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

Input (Declarations and Initializations): int arr[3][3], int sum = 0;

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;

// Iterate through each element of the 2D array


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += arr[i][j];
}
}

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

// Print the resulting sum array


cout << "The summation of the two 2D arrays is: " << endl;
for (int i = 0; i < 3; i++) {

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

Input (Declarations and Initializations): int arr[4][4], int sum = 0;

Process:
#include <iostream>
using namespace std;

int main() {
int arr[4][4] = {{12, 5, 8, 10},
{6, 7, 4, 11},
{18, 9, 2, 1},

int sum = 0; 23-51455-1


{20, 3, 15, 13}};

int nor = 4; // number of rows


int noc = 4; // number of columns

for (int row = 0; row < nor; row++) {


for (int col = 0; col < noc; col++) {
if (row == 0 || row == nor - 1 || col == 0 || col == noc - 1) {
sum = sum + arr[row][col];
}
}
}

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

Input (Declarations and Initializations): int arr[n][n], int sum = 0;

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

Input (Declarations and Initializations): int A[5][4], int A_Tr[4][5];

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

Calculation Steps: 23-51455-1


T[0][0] = A[0][0]
T[1][0] = A[0][1]
T[2][0] = A[0][2]
T[3][0] = A[0][3]
T[0][1] = A[1][0]
T[1][1] = A[1][1]
T[2][1] = A[1][2]
T[3][1] = A[1][3]
T[0][2] = A[2][0]
T[1][2] = A[2][1]
T[2][2] = A[2][2]
T[3][2] = A[2][3]
T[0][3] = A[3][0]
T[1][3] = A[3][1]
T[2][3] = A[3][2]
T[3][3] = A[3][3]
T[0][4] = A[4][0]
T[1][4] = A[4][1]
T[2][4] = A[4][2]
T[3][4] = A[4][3]
Structures in C++
A Structure in C++ is a group of data elements grouped together under one name. These data
elements, known as members, can have different types and different lengths. It is a user
defined data type which allows you to combine data items of different kinds.

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.

Example of structure Definition

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.

Example of Accessing members of a structure:

cout<<book.title;
cout<<book.author;
cout<<book.subject;
cout<<book.id;

Sample Program of Structures in C++:

#include <iostream>
using namespace std;

struct Person
{
char name[50];
int age;
23-51455-1
float salary;
};

int main()
{
Person p1;

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

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>

using namespace std;


struct Customer
{
int id;
string name;
};

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

Passing Structure as arguments to a function


#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books book );

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;

// Print Book1 info


printBook( Book1 );

// Print Book2 info


printBook( Book2 );

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:

customerId CustomerName PhoneNo Age


101 ABC 171111111 25
102 DEF 1722223333 32
103 XYZ 181111111 30
104 PQR 1611111111 50
105 MNO 1700001111 60
106 GHI 1910000001 35

1. Create a data type that can store the customer information.


2. Write a pseudocode to count the number of customers who are more than 30 years old.

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

// Output the result


cout << "Number of customers older than 30: " << count << endl;
Pointer

Basic Concept:

int x = 10;
x Value 10
x Memory Address AAAABBB0

cout<<x; Output: 10
cout<<&x; Output: AAAABBB0

int *p; //pointer holds memory address of a variable.


//int pointer holds memory address of an integer variable.

p Value
p Memory Address AAAADDDD

p = &x;
p Value AAAABBB0
p Memory Address AAAADDDD

cout<<p; 23-51455-1
Output: AAAABBB0

cout<<&p; Output: AAAADDDD


cout<<*p; Output: 10
int **q; //Pointer of a pointer.
//q will hold the memory location of another pointer.

q Value
q Memory Address BBBBDDDD

q = &p;
q Value AAAADDDD
q Memory Address BBBBDDDD

cout<<q; Output: AAAADDDD


cout<<&q; Output: BBBBDDDD
cout<<*q; Output: AAAABBB0
cout<<**q; Output: 10
int x = 10;
int *p = &x;
int *q = &x;

x = 20;
cout<<x<<endl; 20
cout<<*p 20
cout<<*q 20
*p = 30
cout<<*p 30
cout<<*q 30
(*q)++
cout<<*p 31

Array using Pointer

int arr[10];
cout<<*arr<<endl;

23-51455-1
int *a;
a = &arr[0];
cout<<*a<<endl;

12 25 9 2 22 23 140 180 30 194


0 1 2 3 4 5 6 7 8 9
01-04 05-08 09-0C 0D-10 11-14 15-18 19-1C 1D-20 21-24 25-28

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

swap (int *p, int *q)


{

int main( )
{
int x = 10;
int y = 20;

//swap(x,y); //pass by value


swap(&x, &y); //pass by reference
}
Returning Pointer from function

int *add(int x, int y)


{
int r = x+y;

} 23-51455-1
return &r;

int main( )
{
int x = 10;
int y = 20;
int *z = add(x,y);
}
C++ Pointer to an Array

Consider this example:

int Arr[] = {55,433,33,118};

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

Displaying address using pointers:


ptr + 0 = 0x7ffe1acbc850
ptr + 1 = 0x7ffe1acbc854
ptr + 2 = 0x7ffe1acbc858
ptr + 3 = 0x7ffe1acbc85c
ptr + 4 = 0x7ffe1acbc860
Example 2 of Pointer to Array in C++

#include <iostream>
using namespace std;

int main() {
float arr[5];

// Inserting data using pointer


cout<<"Enter 5 numbers: ";
for (int i = 0; i < 5; ++i) {
cin >> *(arr + i) ;
}

// Displaying data using pointer


cout<<"Displaying data: "<<endl;
for (int i = 0; i < 5; ++i) {
cout << *(arr + i) << endl ;
}

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

Here, you can:

● Put a new plate on top


● Remove the top 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;

bool isEmpty() bool isFull()


{ {
if(top==0) if(top==size)
{ {
return true; return true;
} }
else else
{ {
return false; return false;
} }
} }
bool push(int element) bool pop()
{ {
if(isFull()) if(isEmpty())
{
return false;
}
23-51455-1 {
return false;
}
else else
{ {
S[top] = element; top--;
top++; return true;
return true; }
} }
}
int getTopElement() void show()
{ {
if(isEmpty()) if(isEmpty())
{ {
return -999999999999; print “Can not Print”
} }
else else
{ {
return S[top-1]; for(int i=top-1; i>=0;i--)
} {
} print S[i]
}
}
}
int main()
{
push(10);
push(20);
push(30);
push(40);
pop();
show();
cout<<isEmpty();
cout<<isFull();
cout<<getTopElement();
}

Object Oriented Approach

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

Prefix: Operator-Operand-Operand // +AB

Infix: Operand-Operator-Operand // A+B

Postfix: Operand-Operand-Operator // AB+

Left to Right BODMAS PEMDAS


2+4*5–6/2+9 2+4*5–6/2+9 2+4*5–6/2+9
=6*5–6/2+9 =2+4*5–3+9 = 2 + 20 – 6/2 + 9
= 30 – 6 / 2 + 9 = 2 + 20 – 3 + 9 = 2 + 20 – 3 + 9
= 24 / 2 + 9 = 31 – 3 = 31 – 3
= 12 + 9 = 28 = 28
= 21

23-51455-1
Input: Infix Expression

Process:

1. Validate the Infix Expression.

2. Convert the Infix Expression to Postfix Expression.

3. Evaluate the Postfix Expression.

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

Input and Initialization: char infixExpr[ ], char validationStack[ ]

Process:

1. Read the Infix expression from left to right.


2. Check, each symbol.

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.

Output: Valid or Invalid


Part 2: Infix to Postfix Conversion

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 - + + * + -

Input and Initializations: char infixExpr[ ], char convertionStack[ ], char postfixExpr[ ]

Process:

1. Read the Infix expression from left to right.

2. Check, each symbol


a. If, it is an operand, insert it in postfix expression.
b. Else if, it is an opening parenthesis, push it in stack.
c. Else if, it is an operator, check the top element of the stack.
i. If it is an operator, compare the precedence of the
operator with the current symbol.
· If the precedence of top element is higher or equal to the current
symbol, repeatedly pop it from the stack and insert it in the postfix
expression.
· Else, the precedence of top element is less than the current symbol,
push the current symbol into the stack.
ii. Else, (if it is an opening parenthesis or nothing),
push the current symbol into stack.
d. Else if it is a closing parenthesis, repeatedly pop from stack and insert in the postfix
expression until the corresponding opening parenthesis is at the top. Now, remove the
opening parenthesis from the stack.

3. Repeat 1 and 2 till the end of the expression.

4. At the end of the expression, pop all the elements from stack and insert in postfix expression.

Output: char postfixExpr[ ]

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:

1. Read the Postfix Expression from left to right.

2. Check each symbol,


a. If, it is an operand, push it in stack.
b. Else, it is an operator. Do the followings:
i. Initialize the top element of the stack in a variable A.
ii. Pop from stack.
iii. Initialize the top element of the stack in a variable B.
iv. Pop from stack
v. Evaluate the operation B operator A.
vi. Push the result of the operation into the stack.

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

Basic features of Queue;

● 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.

Basics operations on the stack:

1. Enqueue
2. Dequeue
Linear Queue:

Queue Operations:

size = 5

isEmpty( ): front ==-1 and rear == -1.


isFull( ): rear == size-1
enqueue(x): insert an element x at rear position.
dequeue( ): remove an element from front position.
getFrontElement( ): returns the element at front position.
show( ): print the queue from front position to rear position.

23-51455-1
Linear Queue Implementation Circular Queue Implementation

#include <iostream> #include <iostream>


using namespace std; using namespace std;

const int size = 100; // Define the size const int size = 100; // Define the size
of the queue of the circular queue

class MyQueue { class MyCircularQueue {


int Q[size]; int CQ[size];
int front = -1, rear = -1; int front = -1, rear = -1;

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;

// Get the front element of mq1 // Enqueue elements into mcq1


int frontElement = mcq1.enqueue(10);
mq1.getFrontElement(); mcq1.enqueue(20);
cout << "Front element in mq1: " << mcq1.enqueue(30);
frontElement << endl; mcq1.enqueue(40);

// Enqueue elements into mq2 // Show elements in mcq1


mq2.enqueue(100); cout << "Circular Queue mcq1
mq2.enqueue(200); elements: ";
mcq1.show();
// Show elements in mq2
cout << "Queue mq2 elements: "; // Dequeue elements from mcq1
mq2.show(); mcq1.dequeue();
cout << "Circular Queue mcq1
return 0; elements after one dequeue: ";
} mcq1.show();

// Get the front element of mcq1


int frontElement =
mcq1.getFrontElement();
cout << "Front element in mcq1: " <<
frontElement << endl;

// Enqueue elements into mcq2


mcq2.enqueue(100);

23-51455-1
mcq2.enqueue(200);

// Show elements in mcq2


cout << "Circular Queue mcq2
elements: ";
mcq2.show();

return 0;
}
23-51455-1

You might also like