Program to insert an element in array using function

2 years ago Admin 0

Insert an element in array using function

This article illustrates the concept how to insert an element in array using function in c/c++.

insert an element in array using function

Here is the source code and output of both the programs.

C Programming language

Program


#include<stdio.h>
#include<conio.h>
void insert(int[],int,int,int);
void main()
{
int ar[50],n,i,num,ins,poc;
clrscr();
printf("Enter number of elements:- ");
scanf("%d",&n);
printf("Enter elements in array:- ");
for(i=0;i<n;i++)
{
 scanf("%d",&ar[i]);
}
printf("Enter element to insert:- ");
scanf("%d",&ins);
printf("Enter Position to insert:- ");
scanf("%d",&poc);
insert(ar,n,ins,poc);
getch();
}

void insert(int arr[],int x,int ins,int loc)
{
 int i;
 for(i=x;i>loc;i--)
  {
  arr[i]=arr[i-1];
  }
  arr[loc]=ins;
 printf("Array after inserting element is:-\n ");
 for(i=0;i<x+1;i++)
   {
    printf("%d\n",arr[i]);
   }
}

After successfully compiling and executing the above C program,output is:-

insert an element in array using function


C++ Programming language

Program


#include<iostream.h>
#include<conio.h>
void insert(int[],int,int,int);
void main()
{
clrscr();
int ar[50],n,i,num,ins,poc;
cout<<"Enter number of elements:- ";
cin>>n;
cout<<"Enter elements in array:- ";
for(i=0;i<n;i++)
{
 cin>>ar[i];
}
cout<<"Enter element to insert:- ";
cin>>ins;
cout<<"Enter Position to insert:- ";
cin>>poc;
insert(ar,n,ins,poc);
getch();
}

void insert(int arr[20],int x,int ins,int loc)
{
 int i;
 for(i=x;i>loc;i--)
  {
  arr[i]=arr[i-1];
  }
  arr[loc]=ins;
 cout<<"Array after inserting element is:-\n "<<endl;
 for(i=0;i<x+1;i++)
   {
    cout<<arr[i]<<endl;
   }
}

After successfully compiling and executing the above C++ program,output is:-

insert an element in array using function


Comment below if you are facing any problem or you find any error in the above program and also subscribe to our newsletter for more updates.


Read more c/c++ Programs published by snapcout:-

Program to find largest element in array using function
Program to search an element in an array
Program to add two numbers using function
Program to search an element in array using function
Program to swap two numbers using function


About article

Written By:- Admin

Published on:- 10/01/2018

Published By:- Snapcout


Don't forget to share the article if you like it:-