Pages

Monday, 3 August 2015

Element insert at begin

C program to insert an element at beginning
Coding:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    float *a,s,t,t1;
    int n,i;
    printf("Please enter total number of elements:");
    scanf("%d",&n);
    a=(float*)malloc(n*sizeof(float));
    for(i=0;i<n;i++)
    {
        printf("Enter element %d:",i+1);
        scanf("%f",&a[i]);
    }
    printf("Enter the elements you want to insert at begin:");
    scanf("%f",&s);
    a=(float*)realloc(a,(n+1)*sizeof(float));
    t=a[0];
    for(i=0;i<=n;i++)
    {
        t1=a[i+1];
        a[i+1]=t;
      t=t1;
    }
    a[0]=s;
    printf("After insertion array elements are:");
    for(i=0;i<=n;i++)
        printf("%7.2f ",a[i]);
    return 0;
}

Output:

Please enter total number of elements:4
Enter element 1:10
Enter element 2:20
Enter element 3:30
Enter element 4:40
Enter the elements you want to insert at begin:50
After insertion array elements are:  50.00   10.00   20.00   30.00   40.00