forked from abhijithshaji17/cpp-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23.cpp
More file actions
80 lines (70 loc) · 1.67 KB
/
Copy path23.cpp
File metadata and controls
80 lines (70 loc) · 1.67 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Insertion operation on Array using templates
#include <iostream>
using namespace std;
// Print Array
template<typename T>
void printarr(T a[], int size) {
cout << "Array: ";
cout<<"[";
for (int i = 0; i < size; i++)
cout << a[i] << " ";
cout<<"]";
}
// Insert at Beginning
template<typename T>
void insertbeg(T a[], int &size, T value) {
for (int i = size; i > 0; i--){
a[i] = a[i - 1]; //shift all elements one spot right
}
a[0] = value;
size++;
}
// Insert at End
template<typename T>
void insertend(T a[], int &size, T value) {
a[size] = value;
size++; //increment to increase array elements
}
// Insert at Position
template<typename T>
void insertpos(T a[], int &size, int pos, T value) {
if (pos < 0 || pos > size) {
cout << "Invalid Position!\n";
return;
}
for (int i = size; i > pos; i--){
a[i] = a[i - 1];
}
a[pos] = value;
size++;
}
int main() {
int a[20], size;
cout << "Enter number of elements: ";
cin >> size;
cout << "Enter elements:\n";
for (int i = 0; i < size; i++){
cin >> a[i];
}
printarr(a, size);
// Beginning
int value;
cout << "\nEnter value to insert at beginning: ";
cin >> value;
insertbeg(a, size, value);
printarr(a, size);
// End
cout << "\nEnter value to insert at end: ";
cin >> value;
insertend(a, size, value);
printarr(a, size);
// Position
int pos;
cout << "\nEnter position: ";
cin >> pos;
cout << "Enter value: ";
cin >> value;
insertpos(a, size, pos, value);
printarr(a, size);
return 0;
}