Here we are going to write a c program to insert an element in an array using while loop. We will insert element given by user at the end of the array. We can do this program in this way also that is c program to insert an element in an array at a particular position. But here we will insert at the end.
For example - we have array
a[ ]={1, 2, 6, 7, 8}
Element to insert - 9
New array, a[ ]={1, 2, 6, 7, 8, 9}
C program to insert an element in an array can be done using while loop as well as for loop if you do it in while loop then you will be able to do the same using for loop also and vice versa is also true.
Approach -
• Take length of the array from the user
• Take array input from the user
• Take a number from the user to insert in the array
• Insert the number
• Print new array
C program to insert an element in an array using while loop
#include <stdio.h>
int main(){
int n;
printf("Enter length of array: ");
scanf("%d",&n);
int a[100];
printf("Enter array elements: ");
for(int i=0; i<n; i++){
scanf("%d",&a[i]);
}
int c=0;
int e;
while(c==0){
printf("Enter element to insert: ");
scanf("%d",&e);
a[n++]=e;
printf("Enter 0: to continue 1: to terminate: ");
scanf("%d",&c);
}
for(int i=0; i<n; i++){
printf("%d ",a[i]);
}
return 0;
}
Output -
Enter length of array: 3
Enter elements in array: 1 2 3
Enter element to insert: 4
Enter 0: to continue 1: to terminate: 0
Enter element to insert: 5
Enter 0: to continue 1: to terminate: 1
1 2 3 4 5More like this -
• Program to find length of array
• Program to insert an element in an array at a particular position

Post a Comment
If you have any doubts, please let me know