C Program to Delete an Element in a Dynamically aloocated Array


 

// Program by Akash Tripathi (@proakash256) 
 
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n;
    printf("Enter the number of elements you want to enter : ");
    scanf("%d", &n);
    int *ar = (int *)malloc(n * sizeof(int));
    printf("\nEnter the Elements :\n");
    for (int i = 0i < ni = i + 1)
        scanf("%d", &ar[i]);
    printf("\nEnter the Position of the Element
             you want to Delete : \n");
    unsigned short a;
    scanf("%hu", &a);
    if ((a > n) || (a < 1))
    {
        printf("You have Entered a value outside
                of the size of the Array.");
    }
    else
    {    
        a = a - 1;
        n = n - 1;
        for (int i = ai < ni = i + 1)
            ar[i] = ar[i + 1];
        ar = realloc(ar, (n * sizeof(int)));
        printf("\nThe Elements are : \n\n");
        for (int i = 0i < ni = i + 1)
            printf("%d -> %d\n", (i + 1), ar[i]);
    }
    free(ar);
    return 0;
}

Comments