Write code to insert data in an array at a particular position
Long Answer
Views 590
Answer:
#include int main() { int arr[100], n, pos, value, i; // Read size of array printf("Enter number of elements: "); scanf("%d", &n); // Read array elements printf("Enter array elements:\n"); for (i = 0; i < n; i++) { scanf("%d", &arr[i]); } // Read position and value printf("Enter position to insert (1 to %d): ", n + 1); scanf("%d", &pos); printf("Enter value to insert: "); scanf("%d", &value); // Validate position if (pos < 1 || pos > n + 1) { printf("Invalid position!"); return 0; } // Shift elements to the right for (i = n; i >= pos; i--) { arr[i] = arr[i - 1]; } // Insert element arr[pos - 1] = value; n++; // Increase size // Print updated array printf("Array after insertion:\n"); for (i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Data Structure, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.