-
Notifications
You must be signed in to change notification settings - Fork 0
/
assignment 1 question 2.cpp
121 lines (107 loc) · 3.22 KB
/
assignment 1 question 2.cpp
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//Write a C program for the implementation operations on an array Insert, Delete, Update,
//Search and traverse
#include <stdio.h>
void insert(int arr[], int n, int pos, int val) {
if (pos < 0 || pos > n) {
printf("Invalid position\n");
return;
}
for (int i = n; i > pos; i--) {
arr[i] = arr[i-1];
}
arr[pos] = val;
printf("Value inserted successfully\n");
}
void delete(int arr[], int n, int pos) {
if (pos < 0 || pos >= n) {
printf("Invalid position\n");
return;
}
for (int i = pos; i < n-1; i++) {
arr[i] = arr[i+1];
}
printf("Value deleted successfully\n");
}
void update(int arr[], int n, int pos, int val) {
if (pos < 0 || pos >= n) {
printf("Invalid position\n");
return;
}
arr[pos] = val;
printf("Value updated successfully\n");
}
int search(int arr[], int n, int val) {
for (int i = 0; i < n; i++) {
if (arr[i] == val) {
return i;
}
}
return -1;
}
void traverse(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[100], n, choice, pos, val, result;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
while (1) {
printf("\nOperations on Array\n");
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Update\n");
printf("4. Search\n");
printf("5. Traverse\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the position to insert the value: ");
scanf("%d", &pos);
printf("Enter the value to be inserted: ");
scanf("%d", &val);
insert(arr, n, pos, val);
n++;
break;
case 2:
printf("Enter the position to delete the value: ");
scanf("%d", &pos);
delete(arr, n, pos);
n--;
break;
case 3:
printf("Enter the position to update the value: ");
scanf("%d", &pos);
printf("Enter the new value: ");
scanf("%d", &val);
update(arr, n, pos, val);
break;
case 4:
printf("Enter the value to search: ");
scanf("%d", &val);
result = search(arr, n, val);
if (result == -1) {
printf("Value not found\n");
} else {
printf("Value found at position %d\n", result);
}
break;
case 5:
traverse(arr, n);
break;
case 6:
printf("Exiting program\n");
return 0;
default:
printf("Invalid choice\n");
}
}
}