Home > OS >  Why is my delete operation for array elements not functioning properly?
Why is my delete operation for array elements not functioning properly?

Time:12-24

I initialized an array and made some functions for performing operations such as traversing, inserting, deleting. Everything is working fine but the delete function is not giving the desired output. Rather than deleting the intended element it is deleting the last element. Please point out the mistake in my code because of which the delete operation is not getting executed properly.

#include <stdio.h>

int sizeofArray;
int atIndex;
int array[50];

void display(int array[], int elementsReq) //For traversing the array//
{
    if (elementsReq <= sizeofArray)
    {
        for (int i = 0; i < elementsReq; i  )
        {
            printf("%d ", array[i]);
        }
    }
    else
    {
        printf("Not enough elements to display\n");
    }
    printf("\n");
}

int insert(int array[], int elementToBeInserted, int atIndex, int sizeofArray) //For inserting elements//
{
    for (int i = sizeofArray - 1; i >= atIndex; i--)
    {
        array[i   1] = array[i];
    }
    array[atIndex] = elementToBeInserted;
    return 1;
}

int delete (int array[], int sizeofArray, int atIndex) //For deleting elements//
{
    for (int i = atIndex; i < sizeofArray - 1; i  )
    {
        array[i] = array[i   1];
    }
    return 1;
}

int main(int argc, char const *argv[])
{
    int array[7] = {1, 2, 4, 5, 6};
    sizeofArray = 5;
    display(array, 5); //Displaying an Array//

    int elementToBeInserted = 3;
    int atIndex = 2;
    insert(array, 3, 2, 5); //Inserting an element//
    sizeofArray  ;
    printf("NOW INSERTING THE MENTIONED ELEMENT\n");
    display(array, 6);
    if (insert(array, 3, 2, 5) == 1)
    {
        printf("ELEMENT INSERTED SUCCESSFULLY\n");
    }
    else
    {
        printf("ALAS!! ELEMENT NOT INSERTED\n");
    }

    printf("NOW DELETING...\n");
    delete(array, 6, 3);  //Trying to Delete the element at index no. 3//
    sizeofArray--;
    display(array, 5);
    if (delete (array, 6, 3) == 1)
    {
        printf("ELEMENT DELETED SUCCESSFULLY\n");
    }
    else
    {
        printf("ALAS!! ELEMENT NOT DELETED\n");
    }

    return 0;
}

CodePudding user response:

You call insert() twice, so the array contains { 1, 2, 3, 3, 4, 5 } before deleting.

Check this by calling display() before.

Note 1: You are also calling delete() twice.

Note 2: You might want to learn to debug small programs. You can use a debugger, and it's worth to learn that. Or you can insert more printf() at "strategic" places.

  • Related