Data Structure Lab
Data Structure Lab
Lab Submitted
By: Nitesh
Kumar
Roll No.
24PGCS06
Aim: Write a program to insert an element at given position
in linear array
#include <stdio.h>
// Function to insert an element at a given position in an array
void insertElement(int arr[], int n, int pos, int element) {
// Check if position is valid
if (pos < 0 || pos > n) {
printf("Invalid position! Position should be between 0 and %d.\
n", n);
return;
}
// Shift elements to the right to make space for the new element
for (int i = n; i > pos; i--) {
arr[i] = arr[i - 1];
}
// Insert the new element
arr[pos] = element;
// Print the updated array
printf("Updated array: ");
for (int i = 0; i <= n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[10] = {1, 2, 3, 4, 5};
int n = 5; // Number of elements in the array
int pos = 2; // Position where the new element will be inserted
int element = 10; // New element to be inserted
_Output:_
Heap: 50 40 30 10 20
Heap after deletion: 40 20 30 10