Array

 

#include <iostream>
using namespace std;

// Function to generate the array
int generateArray(int arr[], int max, int &size) {
    cout << "Enter elements of array: ";
    for (int i = 0; i < max; i++) {
        cin >> arr[i];
        size++;
    }
    return 0;
}

// Function to display the array
int displayArray(int arr[], int size) {
    cout << "Current array: ";
    for (int i = 0; i < size; i++) { // Traverse only up to `size`
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}

// Function to insert an element into the array
int insertInArray(int arr[], int max, int &size) {
    if (size >= max) { // Prevent insertion if the array is full
        cout << "Array is full. Cannot insert more elements.\n";
        return 1;
    }

    int pos, data;
    cout << "Enter position: ";
    cin >> pos;

    if (pos < 0 || pos > size) { // Validate position
        cout << "Invalid position.\n";
        return 1;
    }

    cout << "Enter data: ";
    cin >> data;

    // 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] = data; // Insert the new element
    size++; // Increment size to reflect the new element
    return 0;
}

// Function to insert an element into the array
int deleteFromArray(int arr[], int max, int &size) {
    if (size <= 0) { // Prevent deletion if the array is empty
        cout << "Array is empty.\n";
        return 1;
    }

    int pos;
    cout << "Enter position: ";
    cin >> pos;

    if (pos < 0 || pos >= size) { // Validate position
        cout << "Invalid position.\n";
        return 1;
    }

    // Shift elements to the left to fill space
    for (int i = pos; i < size-1; i++) {
        arr[i] = arr[i + 1];
    }

    size--; // Decrement size to reflect the new element
    return 0;
}


int main() {
    int max, currSize = 0; // `currSize` starts at 0
    cout << "Enter maximum size of array: ";
    cin >> max;

    if (max <= 0) {
        cout << "Please enter a valid size.\n";
        return 1;
    }

    int arr[max];

    char exit = 'n';
    do{
        int m;
        cout<<"1 Generate Array"<<endl<<"2 Insert into Array"<<endl<<"3 Delete from Array"<<endl<<"4 Display Array"<<endl;
        cout<<"select from menu: ";
        cin>>m;
        switch(m){
            case 1:
                generateArray(arr,max,currSize);
                break;
            case 2:
                insertInArray(arr, max, currSize);
                break;
            case 3:
                deleteFromArray(arr, max, currSize);
                break;
            case 4:
                displayArray(arr, currSize);
                break;
            default:
                cout<<"Select valid number from menu."<<endl;
                break;
        }
        cout<<"Exit? (y or n) ";
        cin>>exit;
    }
    while(exit='n');

    return 0;
}

Comments