Sunday 24 July 2016

Program to Insert an Element to an Array at Valid Position

Write a program to Insert an Element to an Array at Valid Position


#include<stdio.h>
#include<stdlib.h>
#define MAX 5

int a[MAX], pos, elem;
int n = 0;
void create();
void display();
void insert();

void main()
{
                int i;
                printf("\nEnter the number of elements: ");
                scanf("%d", &n);
                if(n != 0)
                                printf("\nEnter the elements: ");
                                for(i=0; i<n; i++)
                                {
                                                scanf("%d", &a[i]);
                                }
                insert();
                display();
}
void display()
{
                int i;
                if(n == 0)
                {
                                printf("\nNo elements to display");
                                return;
                }
                printf("\nArray elements are: ");
                for(i=0; i<n; i++)
                                printf("%d\t ", a[i]);
}
void insert()
{
                int i;
                if(n == MAX)
                {
                                printf("\nArray is full. Insertion is not possible");
                                return;
                }
                do
                {
                                printf("\nEnter a valid position where element to be inserted:    ");
                                scanf("%d", &pos);
                }while(pos>n);

                printf("\nEnter the value to be inserted:   ");
                scanf("%d", &elem);
                for(i =n-1; i>=pos ; i--)
                {
                                a[i+1] = a[i];
                }
                a[pos] = elem;
                n = n+1;
    }

Output:

Case 1:
Enter the number of elements: 3
Enter the elements: 11                  22           33
Enter a valid position where element to be inserted:    5
Enter a valid position where element to be inserted:    1
Enter the value to be inserted:   44
Array elements are: 11   44      22      33


Case 2:
Enter the number of elements: 5
Enter the elements: 11                  22           33           44           55
Array is full. Insertion is not possible
Array elements are: 11   22      33      44      55

Also Check,



No comments:

Post a Comment