Insert an element in an Array
Q. Write a C program to insert an element in an array.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[24],i,n,position,value;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
printf("Enter the integer: ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
printf("Enter the location and value of an array: ");
scanf("%d %d", &position,&value);
for (i = n - 1; i >= position - 1; i--)
{
a[i+1] = a[i];
}
a[position-1] = value;
for(i=0; i<=n; i++)
{
printf("%d ",a[i]);
}
getch();
}
Q. Write an algorithm to insert an element in an array.
1. Start
2. Read the number of elements `n`
3. Initialize an array `a` with size sufficient to hold new element (e.g., 24)
4. Loop from `i = 0` to `n-1` to read `n` integer elements into the array `a[i]`
5. Read the `position` and the `value` to be inserted
6. Shift all elements from the last position (`n - 1`) down to `position - 1` one step to the right:
- For `i = n - 1` down to `position - 1`:
- Move `a[i]` to `a[i + 1]`
7. Insert the new `value` at `a[position - 1]`
8. Increase `n` by `1` since new element is inserted
9. Loop from `i = 0` to `n - 1` to print the updated array
10. End
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com