forked from abhijithshaji17/cpp-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path24.cpp
More file actions
100 lines (80 loc) · 1.92 KB
/
Copy path24.cpp
File metadata and controls
100 lines (80 loc) · 1.92 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Deletion operation on Array using templates
#include <iostream>
using namespace std;
// Function Prototypes (Declarations)
template <typename T>
void printarr(T a[], int size);
template <typename T>
void deletebeg(T a[], int &size);
template <typename T>
void deleteend(T a[], int &size);
template <typename T>
void deletepos(T a[], int &size, int pos);
int main()
{
int a[20], size, i;
cout << "Enter the number of elements: ";
cin >> size;
cout << "Enter elements:\n";
for (i = 0; i < size; i++)
{
cout << "Element " << i + 1 << ": ";
cin >> a[i];
}
printarr(a, size);
// 1. Delete from Beginning
cout << "\n--- Deleting from Beginning ---";
deletebeg(a, size);
printarr(a, size);
// 2. Delete from End
cout << "\n--- Deleting from End ---";
deleteend(a, size);
printarr(a, size);
// 3. Delete from Position
int pos;
cout << "\nEnter position index to delete (0-based): ";
cin >> pos;
deletepos(a, size, pos);
printarr(a, size);
return 0;
}
// Function Definitions
template <typename T>
void printarr(T a[], int size)
{
cout << "\nArray:\n[ ";
for (int i = 0; i < size; i++) // Fixed i-- to i++
{
cout << a[i] << " ";
}
cout << "]\n";
}
template <typename T>
void deletebeg(T a[], int &size)
{
if (size <= 0) return;
// Shift all elements one spot to the left
for (int i = 0; i < size - 1; i++) {
a[i] = a[i + 1];
}
size--;
}
template <typename T>
void deleteend(T a[], int &size)
{
if (size <= 0) return;
size--; // Decrement size to drop the last element
}
template <typename T>
void deletepos(T a[], int &size, int pos)
{
if (pos < 0 || pos >= size) {
cout << "Invalid Position!\n";
return;
}
// Shift elements left starting from 'pos'
for (int i = pos; i < size - 1; i++) {
a[i] = a[i + 1];
}
size--;
}