In this tutorial you will learn about the C Program to Insert an Element in an Array and its application with practical example.
C Program to Insert an Element in an Array
In this tutorial, we will learn to create a C program that will Insert an Element in an Array using C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C Programming.
Insert an Element of Array
As we all know array is a collection of similar data type elements. In an array, only one variable is declared which can store multiple values. First will take the number of elements of an array from the user. Then will take the elements from the user for the array. And at last, we will insert the array element by asking the user with the help of C Programming Language.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Step 1. Initialize variable. Step 2. Take size of array . Step 3. Take elements of array. Step 4. Take location to insert a element. Step 5. insert the element. Step 6. Print result. Step 7. End |
Program:-
To insert an element in the array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <stdio.h> int main() { //declaring variables int array[100], position, i, no, value; //taking size of array printf("Enter number of elements in array\n"); scanf("%d", &no); //taking elements of array printf("Enter %d elements\n", no); //for loop for input for (i = 0; i < no; i++) scanf("%d", &array[i]); //taking insertion position i.e. location for inserting element printf("Enter the location where you wish to insert an element\n"); scanf("%d", &position); //value to be inserted printf("Enter the value to insert\n"); scanf("%d", &value); for (i = no - 1; i >= position - 1; i--) array[i+1] = array[i]; array[position-1] = value; //printing output printf("Resultant array is\n"); for (i = 0; i <= no; i++) printf("%d\n", array[i]); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- arrah[] = it will hold the elements in an array.
- no = it will hold the number of elements in an array.
- i = it will hold the integer value to control the array.
- value = it will hold the value to be inserted.
- position = it will hold the location for the insert element of the array.
Taking input from the user in an array number of elements in the array
Taking input from the user in array elements in the array
Insert location for elements.
inert value.
Printing output