Adsense 728 * 15

Search

Custom Search

C, C++ Program to Insert an Element in an Array

Write a C, C++ program to insert an element in an array. In this program, we have to insert a new element at in an array.

Let's take an example -

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

Input position - 3

New element - 7

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

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 a position and new element as an input.

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


C Program to Insert an Element in an Array


#include <stdio.h>

int main(void) {
 
 int arr[100], size, pos, val, i, temp;
 
 printf("Enter the size of an array (MAX 100) \n");
 scanf("%d", &size);
 
 // Create an input array

 printf("Enter an elements in an array \n");
 
 for(i = 0; i < size; i++) {
    scanf("%d", &arr[i]);
 }
 
 // Take a position of a new element

 printf("Enter a position( To insert a new element in an array)\n");
 scanf("%d", &pos);
 
 printf("Enter a value to insert\n");
 scanf("%d", &val);
 
 //Shift element by one position
 
 for(i = size; i >= pos; i--) {
  
  arr[i] = arr[i-1];
  
 }
 
 //Increase the length of an array

 size++;
 
 //Insert new value in an array

 arr[pos] = val;
 
 printf("Array after inserting a new value");
 
 for(i = 0; i < size; i++) {
  printf(" %d ", arr[i]);
 }
 
 return 0;
}


C++ Program to Insert an Element in an Array


#include <iostream>
using namespace std;

 int main() {
 
 int arr[100], size, pos, val, i, temp;
 
 cout << "Enter the size of an array (MAX 100) \n";
 cin  >> size;
 
 // Create an input array
 
 cout << "Enter an elements in an array \n";
 
 for(i = 0; i < size; i++) {
  cin >> arr[i];
 }
 
 // Take a position of a new element
 cout << "Enter a position( To insert a new element in an array)\n";
 cin  >> pos;
 
 cout << "Enter a value to insert\n";
 cin  >> val;
 
 //Shift element by one position
 
 for(i = size; i >= pos; i--) {
  
  arr[i] = arr[i-1];
  
 }
 
 //Increase the length of an array
 size++;
 
 //Insert new value in an array
 arr[pos] = val;
 
 printf("Array after inserting a new value");
 
 for(i = 0; i < size; i++) {
  cout << 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