Write C program to insert an element in array


Introduction

Write C program to insert an element in array


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>

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

    // Reading 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]);
    }

    //Reading element to insert & position of the element

    printf("Enter element to insert : ");
    scanf("%d", &num);
    printf("Enter the element position : ");
    scanf("%d", &position);

    //checking elements valis position

    if(position>size+1 || position<=0)
    {
        printf("Invalid position! Please enter position between 1 to %d", num);
    }
    else
    {
        //Inserting element in an array & increasing the size of the array

        for(i=size; i>=position; i--)
        {
            arr[i] = arr[i-1];
        }
        arr[position-1] = num;
        size++;

         // Printing new array with new element

        printf("Array elements after insertion : ");
        for(i=0; i<size; i++)
        {
            printf("%d\t", arr[i]);
        }
    }

    return 0;
}

Result

C language

     





Related Topics




Popular Posts