Insert a new value in an array at proper position in C Language.
#include<stdio.h>
int main()
{
int arr[30]={8,10,13,18,20,21,25,34,41,47};
int n=10,i,nvalue,index,j,pos;
//printing the actual array.
printf("The Original Array has following values:\n");
for(i=0;i<n;i++)
{
printf("%4d",arr[i]);
}
printf("\n\nEnter the new value: ");
scanf("%d",&nvalue);
if(nvalue<arr[0])
{
pos=0;
}
else if(nvalue>arr[n-1])
{
pos=n;
}
else
{
for(i=0;i<n;i++)
{
if(nvalue>arr[i] && nvalue<=arr[i+1])
{
pos=i+1;
}
}
}
n++;
for(i=n-1;i>pos;i--)
{
arr[i]=arr[i-1];
}
arr[pos]=nvalue;
//printing the values after process
printf("\nThe Updated Array has following values:\n");
for(i=0;i<n;i++)
{
printf("%4d",arr[i]);
}
}
int main()
{
int arr[30]={8,10,13,18,20,21,25,34,41,47};
int n=10,i,nvalue,index,j,pos;
//printing the actual array.
printf("The Original Array has following values:\n");
for(i=0;i<n;i++)
{
printf("%4d",arr[i]);
}
printf("\n\nEnter the new value: ");
scanf("%d",&nvalue);
if(nvalue<arr[0])
{
pos=0;
}
else if(nvalue>arr[n-1])
{
pos=n;
}
else
{
for(i=0;i<n;i++)
{
if(nvalue>arr[i] && nvalue<=arr[i+1])
{
pos=i+1;
}
}
}
n++;
for(i=n-1;i>pos;i--)
{
arr[i]=arr[i-1];
}
arr[pos]=nvalue;
//printing the values after process
printf("\nThe Updated Array has following values:\n");
for(i=0;i<n;i++)
{
printf("%4d",arr[i]);
}
}
No comments
Post your comments