Pages

Monday, 3 August 2015

Element insert at end

C program to insert an element in array at end

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 end:");
    scanf("%f",&s);
    a=(float*)realloc(a,(n+1)*sizeof(float));
    a[n]=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 end:50
After insertion array elements are:  10.00   20.00   30.00   40.00   50.00