C program to insert an element in array

Write a C program to insert an element in array at specified position. C program to insert element in an array at given position. The program should also print an error message if the insert position is invalid.

Example:
If the elements of array are: 10, 20, 30, 40, 50
After inserting 25 at position 3
Elements of array are: 10, 20, 25, 30, 40, 50

Required knowledge:

Basic C programming, For loop, Array

Program:

/**
 * C program to insert an element in array at specified position
 */

#include <stdio.h>

int main()
{
    int arr[100];
    int i, size, num, position;

    /*
     * Reads size and elements of array
     */
    printf("Enter size of the array : ");
    scanf("%d", &size);
    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    /*
     * Read element to insert and position of the element
     */
    printf("Enter element to insert : ");
    scanf("%d", &num);
    printf("Enter the element position : ");
    scanf("%d", &position);

    /*
     * If the position of element is not valid
     */
    if(position>size+1 || position<=0)
    {
        printf("Invalid position! Please enter position between 1 to %d", n);
    }
    else
    {
        /*
         * Inserts element in array and increases the size of the array
         */
        for(i=size; i>=position; i--)
        {
            arr[i] = arr[i-1];
        }
        arr[position-1] = num;
        size++;

        /*
         * Prints the new array after insert operation
         */
        printf("Array elements after insertion : ");
        for(i=0; i<size; i++)
        {
            printf("%d\t", arr[i]);
        }
    }

    return 0;
} 
Output
X
_
Enter size of the array : 5
Enter elements in array : 10 20 30 40 50
Enter element to insert : 25
Enter the element position : 3
Array elements after insertion : 10      20      25      30      40      50

Happy coding ;)


You may also like

Labels: , ,