Page 54 - DCAP407_DATA_STRUCTURE
P. 54
Unit 3: Arrays
Figure 3.3 shows how to add elements to an array.
Figure 3.3: Adding Elements to an Array
Algorithm for Inserting an Element into an Array
Let a be an array of size N and I be the array index. Algorithm to insert an element in the M position
th
of the array a is as follows:
1. Start
2. read a[N], I<-0
3. repeat for I=N to M (Decrement I by one)
4. a[I+1]<- a[I]
5. a[M]<-ELEMENT
6. M<-M+1
7. Stop
The below program illustrates the concept of inserting an element into a one-dimensional array.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, data, po_indx, a[50]; //Variable declaration
clrscr();
printf("Enter number of elements in the array\n");
/*Get the number of elements to be added to the array from the user*/
scanf("%d", &n);
printf("\nEnter %d elements\n\n", n); //Print the number of elements
for(i=0;i<n;i++) //Iterations using for loop
scanf("%d",&a[i]); //Accepting the values in the array
printf("\nEnter a data to be inserted\n");
scanf("%d",&data); //Reads the data added by user
LOVELY PROFESSIONAL UNIVERSITY 47