- Declaration and Initialization:
- Declare an integer array
arr
.
- Declare variables
i
and pos
to be used in the program.
- User Input:
- Prompt the user to enter elements into the array.
- User Input for Deletion:
- Ask the user to enter the index at which they want to delete an element.
- Deletion Process:
- Check if the entered position is valid.
- If valid, perform the deletion by shifting elements after the specified index.
- Display the modified array after deletion.
C program to delete an element in an array
#include <stdio.h>
void main(){
int arr[2], i, pos;
printf("Enter the elements in the array: \n");
for (int i = 0; i < 2; i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the index at which you want to delete: ");
scanf("%d",&pos);
if(pos < 0 || pos > 2)
{
printf("Invalid position!");
}
else
{
for(i=pos-1; i<2; i++)
{
arr[i] = arr[i + 1];
}
printf("\nElements of array after deletion are : ");
for(i=0; i<1; i++)
{
printf("%d\t", arr[i]);
}
}
}
Explanation
- The program declares an integer array
arr
of size 2 and variables i
and pos
.
- It prompts the user to enter two elements for the array.
- The user is asked to enter the index (
pos
) at which they want to delete an element.
- If the entered position is invalid (less than 0 or greater than 2), it prints “Invalid position!”.
- If the position is valid, it performs deletion at the specified index, shifts the remaining elements, and displays the modified array.