Page 55 - DCAP407_DATA_STRUCTURE
P. 55
Data Structure
printf("\nEnter the position of the item \n");
scanf("%d",&po_indx); //Reads the position where the data is inserted
/* Checking if the position is greater than the size of the array*/
if(po_indx-1>n)
printf("\nposition not valid\n"); //If the condition is true this will be printed
else //If the condition is false the ‘else’ part will get executed
{
for(i=n;i>=po_indx;i--) //Iterations using for loop
a[i]=a[i-1]; //Value of a[i-1] is assigned to a[i]
/*Value of data will be assigned to [po_indx-1] position*/
a[po_indx-1]=data;
n=n+1; //Incrementing the value of n
printf("\nArray after insertion\n"); //Print the array list after insertion
for(i=0;i<n;i++) //Use for loop and
printf("%d\t",a[i]); //Print the final array after insertion
}
getch(); //Display characters on screen
}
Output:
Enter number of elements in the array
5
Enter 5 elements
15 20 32 45 62
Enter a data to be inserted
77
Enter the position of the item
2
Array after insertion
15 77 20 32 45 62
In this example:
1. First, the header files are included using #include directive.
2. Then, the index, array, and the variables are declared.
3. The program accepts the number of elements in the array.
4. Using a for loop, the values are accepted and stored in the array.
5. Then, the program accepts the data along with the position where it needs to
be inserted.
6. If the position to be inserted is greater than the number of elements
(po_indx-1>n) then the program displays “position is not valid”. Otherwise,
the program by means of a for loop, checks whether i>=po_indx is true and
assigns the a[i-1] value to a[i].
7. Then data is assigned to a[po_indx-1].
8. Then, the program increments the number of elements and prints the array
after insertion.
9. getch() prompts the user to press a key and the program terminates.
48 LOVELY PROFESSIONAL UNIVERSITY