My issue
Enter the position to insert (0 to 5): Enter the new element to insert: Updated array: 10 20 0 30 40 50
My code
#include <stdio.h>
int main() {
// Step 1: Initialize the array with extra space for insertion
int arr[10] = {10, 20, 30, 40, 50}; // Initial array
int n = 5; // Current size of the array
int pos, newElement;
// Step 2: Input the position and new element
printf("Enter the position to insert (0 to %d): ", n);
scanf("%d", &pos);
printf("Enter the new element to insert: ");
scanf("%d", &newElement);
// Step 3: Validate the position
if (pos < 0 || pos > n) {
printf("Error: Invalid position.\n");
return 1;
}
// Step 4: Shift elements to the right from the last element to the position
for (int i = n; i > pos; i--) {
arr[i] = arr[i - 1];
}
// Step 5: Insert the new element at the specified position
arr[pos] = newElement;
// Step 6: Update the size of the array
n++;
// Step 7: Print the updated array
printf("Updated array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Learning course: Data structures & Algorithms lab
Problem Link: https://www.codechef.com/learn/course/muj-aiml-dsa-c/MUJADSAC05/problems/DSAAGP07