Advertisement
FuadShezan

Untitled

Dec 18th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.99 KB | None | 0 0
  1. #include<stdio.h>
  2. #define MAX_SIZE 15
  3.  
  4. int add(int A[],int n,int x);
  5. int main()
  6. {
  7.    int i,n,arr[MAX_SIZE],x,result;
  8.    printf("How many elements: \n");
  9.    scanf("%d",&n);
  10.  
  11.    for(i=0;i<n;i++)
  12.    {
  13.        scanf("%d",&arr[i]);
  14.    }
  15.    printf("Enter new elements to insert: \n");
  16.    scanf("%d",&x);
  17.    result=add(arr,n,x);
  18.    if(result==-1)
  19.    {
  20.        printf("\n%d can't be added successfully\n",x);
  21.    }
  22.    else
  23.    {
  24.        printf("\n%d is inserted at position: %d\n",x,result);
  25.    }
  26.  
  27.     return 0;
  28. }
  29.  
  30. int add(int A[],int n,int x)
  31. {
  32.     int i,getIPos;
  33.     if(n>=MAX_SIZE)
  34.     {
  35.         return -1;  /// because n already occupied max size thus we can't add anymore
  36.     }
  37.  
  38.     for(i=n-1; i>=0 && A[i]> x ; i--)
  39.     {
  40.         A[i+1]=A[i];
  41.     }
  42.     A[i+1]=x;
  43.     getIPos=i+1;
  44.  
  45.     printf("After Insertion: \n");
  46.     for(i=0;i<n+1;i++)
  47.     {
  48.         printf("%d ",A[i]);    ///this printing is unnecessary as per the question guideline
  49.     }
  50.     return getIPos;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement