Advertisement
Mr_kindle

deleteprime.c

Nov 9th, 2022 (edited)
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.86 KB | None | 0 0
  1. //This code found the prime number in array and delete it;
  2. #include<stdio.h>
  3. #include<malloc.h>
  4.  
  5. int n; //taking n as global variables because it is being used by shrink fun as well and its value is changing in both mains and shrink function.
  6.  
  7.  
  8. int isprime(int n)
  9. {   int i,flag=0;
  10.      for(i=2;i<=n/2;i++)
  11.         {    if(n%i==0)
  12.                 { flag++;
  13.                     break;
  14.             }
  15.         }
  16.         if(flag==0 && n!=1)
  17.         return 1;
  18.         else
  19.             return 0;
  20. }
  21.  
  22. void shrink_arr(int *arr, int j)
  23. {       printf("\n%d",j);
  24.         if(j==n-1)
  25.              arr[j]=4;//replacing last element with a non-prime number to stop the while loop in main function
  26.                  
  27.            
  28.      else
  29.         { while(j<n-1)//keep shrinking till the last element
  30.         /*'j' can maximum travel up to the 2nd last element so that j+1 become the last one*/
  31.             {arr[j]=arr[j+1];
  32.             j++;
  33.             }
  34.         }
  35.         /*Since each time the shrink fun called, the array shrink by 1 element so n--;*/
  36.         n--;
  37.         return;
  38. }
  39.  
  40. int main()
  41. {
  42.    int *arr,i,j;
  43.      printf("Enter number of elements:. ");
  44.     scanf("%d",&n);
  45.     arr= calloc(n,sizeof(int));
  46.     //Enter all (distinct) elements of array/
  47.     for(i=0;i<n;i++)
  48.     {    printf("Enter element %d: ",i+1);
  49.         scanf("%d",&arr[i]);
  50.     }
  51.    
  52.     printf("\n Here is the list:\n");
  53.     for(i=0;i<n;i++)
  54.       printf("%d ",arr[i]);
  55.    
  56.     for(i=0;i<n;i++)
  57.     {    while(isprime(arr[i])==1)
  58.             shrink_arr(arr,i);
  59.     }
  60.     printf("\n List without prime number:\n");
  61.     if (n==0)
  62.     printf("\nList is empty:");
  63.     /*Since if 'n' = 0 then below for loop will not excecute hence no need for else statement*/
  64.     for(i=0;i<n;i++)
  65.       printf("%d ",arr[i]);
  66.    
  67.    
  68.    
  69.    
  70.    
  71.     free(arr);
  72.    
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement