Adsense 728 * 15

Search

Custom Search

C Program to Insert an Element in an Array

Write a c program to insert an element in an array at specified position.  This question can also be asked as, Write a c program to insert an element at a given position.

In this program, we are going to write a code which takes an input array, position and value of a new element from a user and insert it at a specified position.

For example -

Input array - {4, 3, 1, 5}

Input position - 3

New element - 7

After inserting an element - {4, 3, 7, 1, 5}

C Program to Insert an Element in an Array



C Program to delete an element from an array

Programming questions on Arrays

Program to print smallest element of an array


Logic of a Inserting an Element in an Array

i) Take an array, position and new element as an input from a user.

ii) Move an existing element one position up until  the position is reached where a new element is need to be inserted.

Algorithm to insert an element in an array


C Program to Insert an Element in an Array


Let's write a c code to insert an element in an array. First, we take an input array, position and new element from a user.


#include <stdio.h>

int main() {
    
    int n, pos, arr[100], i, num;
    
    printf(" Enter the size of an array (Max 100) \n");
    scanf( " %d ", &n);
    
    printf( " Enter the element of an array \n");
    
    //Input value of an array
    for(i = 0; i < n; i++) {
        scanf(" %d ", &arr[i]);
    }
    
    //Position to insert a new element
    
    printf(" Enter the position \n");
    scanf(" %d ", &pos);
    
    // Number to be inserted in an array
    
    printf(" Enter number to be inserted \n");
    scanf(" %d ", &num);
    
    for( i = n; i >= pos; i--) {
        arr[i] = arr[i-1];
    }
    
    arr[pos-1] = num;
    
    //Increment the size of an array
    n++;
    
    
    printf(" Array after inserting new element \n");
    
    //Array after inserting new element
    for( i = 0; i < n; i++) {
        printf(" %d ", arr[i]);
    }
    return 0;
}




Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

No comments:

Post a Comment