C Program to Insert 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 at which you want to
             Insert the Element : \n");
    unsigned short a;
    scanf("%hu", &a);
    if((a > (n + 1)) || (a < 1))
    {
        printf("You have Entered a value outside
                of the size of the Array.");
    }
    else
    {
    printf("Enter the Element : \n");
    int b;
    scanf("%d", &b);
    a = a - 1;
    n = n + 1;
    ar = realloc(ar , (n * sizeof(int)));
    for (int i = n - 2i >= ai = i - 1)
    {
        ar[i + 1] = ar[i];
    }
    ar[a] = b;
    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