C PROGRAM
Program to delete an element of an array |C Program|
Introduction
Array manipulation is a crucial aspect of programming, and understanding how to efficiently delete elements from an array is a fundamental skill. In this blog post, we'll explore a C program that performs array deletion, shedding light on the process of removing an element at a specified position.
Code
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],pos,i,n;
clrscr();
printf("enter the no.of elements in an array:\n");
scanf("%d",&n);
printf("enter %d elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("which location you want to delete:");
scanf("%d",&pos);
if(pos>=n+1)
{
printf("deletion is not possible:\n");
}
else
{
for(i=pos-1;i<n-1;i++)
a[i]=a[i+1];
printf("after deletion:\n");
for(i=0;i<n-1;i++)
printf("%d\n",a[i]);
}
getch();
}
Output
enter the no.of elements in an array:
5
enter 5 elements:
1
2
3
4
5
which location you want to delete:4
after deletion:
1
2
3
5
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h> and the console I/O header <conio.h>.
2. Main Function:
The main function initiates the program.
Users are prompted to enter the number of elements in the array and the elements themselves.
3. Deletion Operation:
The program asks the user for the position at which they want to delete an element (pos).
It checks if the specified position is valid for deletion.
4. Element Removal:
If the deletion is possible, a for loop shifts the elements after the specified position to the left, effectively removing the element at the given position.
5. Result Display:
The program prints the array after the deletion operation, showcasing the modified array.
6. User Interaction:
Users receive clear feedback about the success or failure of the deletion operation, along with the modified array if deletion is possible.
Conclusion
This C program provides a concise implementation of array deletion, a process essential for managing and manipulating arrays in programming. While this code uses a basic linear shifting approach, it's worth noting that more advanced techniques, such as using dynamic memory allocation, can be explored for larger datasets.
Post a Comment
0 Comments