Skip to content

Commit 3cfa199

Browse files
authored
Merge pull request #319 from BibhuPrasad012/BibhuPrasad012-patch-1
add array-adt in c++
2 parents 289cfac + 8290740 commit 3cfa199

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed

Coding/C++/array_adt.cpp

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
class Array
5+
{
6+
7+
private:
8+
int *A;
9+
int size;
10+
int length;
11+
12+
public:
13+
Array(int size)
14+
{
15+
this->size = size;
16+
A = new int[size];
17+
}
18+
19+
void create()
20+
{
21+
cout << "Enter number of elements: " << flush;
22+
cin >> length;
23+
cout << "Enter the array elements: " << endl;
24+
for (int i = 0; i < length; i++)
25+
{
26+
cout << "Array element: " << i << " = " << flush;
27+
cin >> A[i];
28+
}
29+
}
30+
31+
void display()
32+
{
33+
for (int i = 0; i < length; i++)
34+
{
35+
cout << A[i] << " ";
36+
}
37+
}
38+
39+
// ~Array()
40+
// {
41+
// delete[] A;
42+
// cout << "Array destroyed" << endl;
43+
}
44+
45+
void Append(struct Array *arr, int x)
46+
{
47+
if (arr->length < arr->size)
48+
arr->A[arr->length++] = x;
49+
}
50+
51+
void Insert(struct Array *arr, int index, int x)
52+
{
53+
int i;
54+
if (index >= 0 && index <= arr->length)
55+
{
56+
for (i = arr->length; i > index; i--)
57+
arr->A[i] = arr->A[i - 1];
58+
arr->A[index] = x;
59+
arr->length++;
60+
}
61+
}
62+
63+
int Delete(struct Array *arr, int index)
64+
{
65+
int x = 0;
66+
int i;
67+
if (index >= 0 && index < arr->length)
68+
{
69+
x = arr->A[index];
70+
for (i = index; i < arr->length - 1; i++)
71+
arr->A[i] = arr->A[i + 1];
72+
arr->length--;
73+
return x;
74+
}
75+
return 0;
76+
}
77+
78+
void shiftArray(int arr[], int n, int k)
79+
{
80+
int temp[k];
81+
82+
// Store the last k elements in a temporary array
83+
for (int i = n - k, j = 0; i < n; i++, j++)
84+
{
85+
temp[j] = arr[i];
86+
}
87+
88+
// Shift the remaining elements to the right
89+
for (int i = n - 1; i >= k; i--)
90+
{
91+
arr[i] = arr[i - k];
92+
}
93+
94+
// Copy the temporary array to the beginning of the original array
95+
for (int i = 0; i < k; i++)
96+
{
97+
arr[i] = temp[i];
98+
}
99+
}
100+
};
101+
102+
int main()
103+
{
104+
105+
Array arr(10);
106+
arr.create();
107+
arr.display();
108+
109+
return 0;
110+
}

0 commit comments

Comments
 (0)