forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
array_operations
91 lines (75 loc) · 2.47 KB
/
array_operations
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
#include <iostream>
// Function to initialize an array with values
void initializeArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] = i + 1; // Initialize with values 1, 2, 3, ...
}
}
// Function to insert an element at a specific position in the array
void insertElement(int arr[], int& size, int element, int position) {
if (position < 0 || position > size) {
std::cout << "Invalid position for insertion." << std::endl;
return;
}
for (int i = size; i > position; i--) {
arr[i] = arr[i - 1];
}
arr[position] = element;
size++;
}
// Function to delete an element from a specific position in the array
void deleteElement(int arr[], int& size, int position) {
if (position < 0 || position >= size) {
std::cout << "Invalid position for deletion." << std::endl;
return;
}
for (int i = position; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
size--;
}
// Function to search for an element in the array and return its position
int searchElement(int arr[], int size, int element) {
for (int i = 0; i < size; i++) {
if (arr[i] == element) {
return i; // Element found at position i
}
}
return -1; // Element not found
}
// Function to print the elements of the array
void printArray(const int arr[], int size) {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main() {
const int maxSize = 100;
int arr[maxSize];
int size = 0;
// Initialize the array
initializeArray(arr, size);
std::cout << "Original Array: ";
printArray(arr, size);
// Insert an element at a specific position
int elementToInsert = 42;
int insertPosition = 3;
insertElement(arr, size, elementToInsert, insertPosition);
std::cout << "Array after insertion: ";
printArray(arr, size);
// Delete an element from a specific position
int deletePosition = 2;
deleteElement(arr, size, deletePosition);
std::cout << "Array after deletion: ";
printArray(arr, size);
// Search for an element
int elementToSearch = 5;
int searchResult = searchElement(arr, size, elementToSearch);
if (searchResult != -1) {
std::cout << "Element " << elementToSearch << " found at position " << searchResult << std::endl;
} else {
std::cout << "Element " << elementToSearch << " not found in the array." << std::endl;
}
return 0;
}