Advertisement
a_pramanik

Searching and Deletion in C

Jun 3rd, 2020
1,170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3.  
  4. int searchElement(int arr[], int size, int value){
  5.  
  6.     int i;
  7.     for(i=0; i<size; i++){
  8.         if(arr[i]==value){
  9.             return i;
  10.         }
  11.     }
  12.  
  13.     return -1;
  14.  
  15. }
  16.  
  17. int removeElement(int arr[], int size, int value){
  18.  
  19.     int pos, i;
  20.  
  21.     pos = searchElement(arr, size, value);
  22.  
  23.     if(pos==-1){
  24.         return -1;
  25.     }
  26.  
  27.     for(i = pos; i<size-1; i++){
  28.         arr[i] = arr[i+1];
  29.     }
  30.  
  31.     return size-1;
  32.  
  33. }
  34.  
  35.  
  36.  
  37. int main()
  38. {
  39.     int a[50], i;
  40.  
  41.     int n, value, location;
  42.     printf("Enter how many numbers: ");
  43.     scanf("%d", &n);
  44.  
  45.     for(i=0; i<n; i++){
  46.         scanf("%d", &a[i]);
  47.     }
  48.  
  49.  
  50.     printf("Enter the element to be deleted: ");
  51.     scanf("%d", &value);
  52.     //Searching
  53. //    location = searchElement(a, n, value);
  54. //
  55. //    if(location==-1){
  56. //        printf("Item not found!!\n");
  57. //    }
  58. //    else{
  59. //        printf("Item found at index %d\n", location+1);
  60. //    }
  61.  
  62.  
  63.     //Deletion
  64.     int size;
  65.  
  66.     size = removeElement(a, n, value);
  67.  
  68.     if(size==-1){
  69.         printf("Deletion is not possible, element not found!!");
  70.     }
  71.  
  72.     else{
  73.         printf("Element %d is deleted!!", value);
  74.  
  75.         printf("Updated array is: \n");
  76.  
  77.         for(i = 0; i<size; i++){
  78.             printf("%d ", a[i]);
  79.         }
  80.         printf("\n");
  81.  
  82.     }
  83.  
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement