C Insertion-Array Operation

Insertion

Example:

//Write a Program To Insert an Element into One-dimensional Array.
#include<stdio.h>
#include<conio.h>

void main()
{
    int a[100];
    int i,j,n,pval,pos;
    clrscr();
    printf("Enter Array Size < 100:");
    scanf("%d",&n);
    printf("Enter Any %d Number\n\n",n);
    for(i=0;i<n;i++)
    {
        printf("Enter Value Of a[%d]: ",i);
        scanf("%d",&a[i]);
    }
    printf("\n\nEnter Position To Insert: ");
    scanf("%d",&pos);
    printf("Enter Value For Position a[%d]: ",pos);
    scanf("%d",&pval);
    for(j=n-1;j>=pos;j--)
    {
        a[j+1]=a[j];
    }
    a[pos]=pval;
    printf("Array After Insertion\n");
    for(i=0;i<=n;i++)
    {
        printf("\na[%d] = %d",i,a[i]);
    }
    getch();
}

Output:

Command Prompt
Enter Array Size: 5

Enter Value of a[0]: 10
Enter Value of a[1]: 20
Enter Value of a[2]: 40
Enter Value of a[3]: 50
Enter Value of a[4]: 60

Enter Position To Insert: 2
Enter Value For Position a[2]: 30

Array After Insertion
a[0] = 10
a[1] = 20
a[2] = 30
a[3] = 40
a[4] = 50
a[5] = 60

Share This Page to Download:

Share to Download

Share This Page on:


Ask Question