Example:
If the elements of array are: 10, 20, 30, 40, 50
After inserting 25 at position 3
Elements of array are: 10, 20, 25, 30, 40, 50
Required knowledge:
Basic C programming, For loop, ArrayProgram:
/**
* C program to insert an element in array at specified position
*/
#include <stdio.h>
int main()
{
int arr[100];
int i, size, num, position;
/*
* Reads size and elements of array
*/
printf("Enter size of the array : ");
scanf("%d", &size);
printf("Enter elements in array : ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/*
* Read element to insert and position of the element
*/
printf("Enter element to insert : ");
scanf("%d", &num);
printf("Enter the element position : ");
scanf("%d", &position);
/*
* If the position of element is not valid
*/
if(position>size+1 || position<=0)
{
printf("Invalid position! Please enter position between 1 to %d", n);
}
else
{
/*
* Inserts element in array and increases the size of the array
*/
for(i=size; i>=position; i--)
{
arr[i] = arr[i-1];
}
arr[position-1] = num;
size++;
/*
* Prints the new array after insert operation
*/
printf("Array elements after insertion : ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
}
return 0;
}
Output
Enter size of the array : 5
Enter elements in array : 10 20 30 40 50
Enter element to insert : 25
Enter the element position : 3
Array elements after insertion : 10 20 25 30 40 50
Enter elements in array : 10 20 30 40 50
Enter element to insert : 25
Enter the element position : 3
Array elements after insertion : 10 20 25 30 40 50
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to find sum of all array elements.
- C program to find maximum and minimum element in array.
- C program to delete an element from array at given position.
- C program to print all unique elements in the array.
- C program to find reverse of an array.
- C program to search an element in array.
- C program to find HCF of two numbers.
- C program to find LCM of two numbers.
- C program to add two matrices.
- C program to check whether two matrices are equal or not.
- C program to interchange diagonals of a matrix.
- C program to find transpose of a matrix.
- C program to print Fibonacci series up to n terms.
- C program to print Pascal triangle up to n rows.
- C program to print different star(*) patterns.