0% found this document useful (0 votes)
17 views2 pages

Exp 2

Uploaded by

abhisaxena5551
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views2 pages

Exp 2

Uploaded by

abhisaxena5551
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Exp-2

Aim - Write a C program to insert the element at the specific position of array.

Description

An array is a data structure that allows you to store multiple elements of the same type in a contiguo
us block of memory.

Algo-

1. Input:

• Array arr of size n

• Element elem to be inserted

• Position pos to insert elem

2. Check Validity:

• Ensure pos is within the bounds (0 to n)

3. Shift Elements:

• For i from n-1 to pos, do:

o arr[i + 1] = arr[i] (shift elements to the right)

4. Insert Element:

• Set arr[pos] = elem

5. Update Size:

• Increment size n by 1

6. Output:

• Array arr with elem inserted at pos

Code

#include <stdio.h>

int main() {

int n, pos, elem;

printf("Enter number of elements: ");

scanf("%d", &n);

int arr[n + 1]; // Array with an extra space for the new element
printf("Enter elements:\n");

for (int i = 0; i < n; i++) {

scanf("%d", &arr[i]);

printf("Enter element to insert: ");

scanf("%d", &elem);

printf("Enter position (0 to %d): ", n);

scanf("%d", &pos);

for (int i = n; i > pos; i--) {

arr[i] = arr[i - 1]; // Shift elements to the right

arr[pos] = elem; // Insert the element at the specified position

printf("Array after insertion:\n");

for (int i = 0; i <= n; i++) {

printf("%d ", arr[i]);

return 0;

Output:

Enter number of elements: 4

Enter elements:

10 20 30 40

Enter element to insert: 25

Enter position (0 to 4): 2

Array after insertion:

10 20 25 30 40

You might also like