Write a C program to delete an element from an array.
#include <stdio.h>
#define MAX 256
int main() {
int i, n, ele, pos, flag, arr[MAX];
/* get the number of elements from the input array */
printf("Number of elements in the input array:");
scanf("%d", &n);
/* get the array entries from the user */
printf("Enter your array elements:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", &arr[i]);
}
/* get the element to be deleted */
printf("Enter the element to be deleted:");
scanf("%d", &ele);
/* find the position of the element to be deleted */
for (i = 0; i < n; i++) {
if (arr[i] == ele) {
flag = 1;
pos = i;
n--;
break;
}
}
#define MAX 256
int main() {
int i, n, ele, pos, flag, arr[MAX];
/* get the number of elements from the input array */
printf("Number of elements in the input array:");
scanf("%d", &n);
/* get the array entries from the user */
printf("Enter your array elements:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", &arr[i]);
}
/* get the element to be deleted */
printf("Enter the element to be deleted:");
scanf("%d", &ele);
/* find the position of the element to be deleted */
for (i = 0; i < n; i++) {
if (arr[i] == ele) {
flag = 1;
pos = i;
n--;
break;
}
}
if (!flag) {
printf("Given element is not found in source array!!\n");
return 0;
} else {
/* delete the desired element from the source array */
for (i = pos; i < n; i++) {
arr[i] = arr[i + 1];
}
}
/* print the elements in the resultant array */
printf("Elements in resultant array:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Number of elements in the input array:5
Enter your array elements:
Data[0]: 10
Data[1]: 20
Data[2]: 30
Data[3]: 40
Data[4]: 50
Enter the element to be deleted:10
Elements in resultant array:
20 30 40 50
Number of elements in the input array:5
Enter your array elements:
Data[0]: 10
Data[1]: 20
Data[2]: 30
Data[3]: 40
Data[4]: 50
Enter the element to be deleted:10
Elements in resultant array:
20 30 40 50
No comments:
Post a Comment