fork download
  1. #include<stdio.h>
  2. #include<string.h>
  3.  
  4. #define ARR_SIZE 10
  5. int main()
  6. {
  7. /*Array to hold elements of (ARR_SIZE+1) size , +1 for extra space for our element.*/
  8. int arr[ARR_SIZE+1] = {10,20,30,40,50,60,70,80,90,100,0};
  9. int pos,num; /*Number and postion to insert.*/
  10.  
  11. printf("\nBefore insertion : ");
  12. for(int i = 0; i < ARR_SIZE+1 ; ++i)
  13. {
  14. printf("%d ",arr[i]);
  15. }
  16.  
  17. printf("\nEnter number to insert : ");
  18. scanf("%d",&num);
  19. printf("\nEnter its position : ");
  20. scanf("%d",&pos);
  21.  
  22. if(pos < 0 || pos > ARR_SIZE+1){
  23. fprintf(stderr,"Invalid position '%d' provided.",pos);
  24. return 1;
  25. }
  26.  
  27. pos -= 1; /*Map according to index of array.*/
  28. /*Make space for number to insert.*/
  29. memmove(&arr[pos+1],&arr[pos],(ARR_SIZE+1-pos)*sizeof(int));
  30. arr[pos] = num;/*insert the number.*/
  31.  
  32. printf("\nAfter insertion : ");
  33. for(int i = 0; i < ARR_SIZE+1 ; ++i)
  34. {
  35. printf("%d ",arr[i]);
  36. }
  37.  
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0s 9424KB
stdin
99
4
stdout
Before insertion : 10 20 30 40 50 60 70 80 90 100 0 
Enter number to insert : 
Enter its position : 
After insertion : 10 20 30 99 40 50 60 70 80 90 100