#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int arr[MAX_SIZE];
int size = 0;
// Function prototypes
void createArray();
void displayArray();
void insertElement();
void deleteElement();
int main() {
int choice;
do {
printf("\nMenu:\n");
printf("1. Create an Array of N Integer Elements\n");
printf("2. Display Array Elements\n");
printf("3. Insert an Element at a given valid Position\n");
printf("4. Delete an Element at a given valid Position\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
createArray();
break;
case 2:
displayArray();
break;
case 3:
insertElement();
break;
case 4:
deleteElement();
break;
case 5:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 5);
return 0;
}
void createArray() {
printf("Enter the number of elements (max %d): ", MAX_SIZE);
scanf("%d", &size);
if (size > MAX_SIZE || size <= 0) {
printf("Invalid size. Please enter a value between 1 and %d.\n", MAX_SIZE);
size = 0; // Reset size to indicate no valid array is created
return;
}
printf("Enter %d integer elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("Array created successfully.\n");
}
void displayArray() {
if (size == 0) {
printf("Array is empty. Please create an array first.\n");
return;
}
printf("Array Elements:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
void insertElement() {
if (size == 0) {
printf("Array is empty. Please create an array first.\n");
return;
}
int pos, element;
printf("Enter the position to insert (0 to %d): ", size);
scanf("%d", &pos);
if (pos < 0 || pos > size) {
printf("Invalid position. Please enter a valid position between 0 and %d.\n", size);
return;
}
if (size >= MAX_SIZE) {
printf("Array is full. Cannot insert new element.\n");
return;
}
printf("Enter the element to insert: ");
scanf("%d", &element);
// Shift elements to the right to make space for the new element
for (int i = size; i > pos; i--) {
arr[i] = arr[i - 1];
}
arr[pos] = element; // Insert the new element
size++;
printf("Element inserted successfully.\n");
}
void deleteElement() {
if (size == 0) {
printf("Array is empty. Please create an array first.\n");
return;
}
int pos;
printf("Enter the position to delete (0 to %d): ", size - 1);
scanf("%d", &pos);
if (pos < 0 || pos >= size) {
printf("Invalid position. Please enter a valid position between 0 and %d.\n", size - 1);
return;
}
// Shift elements to the left to fill the gap
for (int i = pos; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
size--;
printf("Element deleted successfully.\n");
}