Tuesday, June 15, 2010

C program to insert an element in the array

Today in our C  tutorial we will discuss about two operations on C array

To crerate an array and then to insert a value within the array.

#include < stdio.h>
void insert(int a[],int n)
{
int i,loc,temp,val;
printf("\nEnter the location where you want to insert(1 to %d):",n);
scanf("%d",&amp;loc);
printf("\nEnter the value:");
scanf("%d",&amp;val);
temp=a[loc-1];
a[loc-1]=val;
for(i=loc;i &lt;= n;i++)
{
loc=a[i]; a[i]=temp; temp=loc;
}
}

void main()
{
int arr[20],i,n;
clrscr();
printf("\nHow many values you want to insert(within 19):");
scanf("%d",&amp;n);
for(i=0;i &lt; n;i++)
{
printf("\nValue=");
scanf("%d",&amp;arr[i]);
}
insert(arr,n);
printf("\nAfter insertion\n");
for(i=0;i &lt; =n;i++)
{
printf("\nValue=%d",arr[i]);
}
getch();
}


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner