Guest User

Untitled

a guest
Sep 26th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. // Inserts an element. Returns the number of new elements.
  4. int insert(int arr[], int len, int num, int key) {
  5. int i;
  6.  
  7. if (len == key) {
  8. arr[key] = num;
  9. return len+1;
  10. }
  11. else {
  12. for (i=len-1; i>=key; i--) {
  13. // Shifting elements to right
  14. arr[i+1] = arr[i];
  15.  
  16. // Stop when key is reached.
  17. if (i == key) {
  18. arr[key] = num;
  19. return len+1;
  20. }
  21. }
  22. }
  23.  
  24. return len;
  25. }
  26.  
  27. // Inserts an element. Returns the number of new elements.
  28. int delete(int arr[], int len, int key) {
  29. int i;
  30.  
  31. for (i=key; i<len; i++) {
  32. arr[i] = arr[i+1];
  33. }
  34.  
  35. return len-1;
  36. }
  37.  
  38. // Display a menu
  39. int menu() {
  40. int option;
  41. printf("\nSelect an option:\n 1) Insert an element\n 2) Delete an element\n 3) Exit\nAns: ");
  42. scanf("%d", &option);
  43. return option;
  44. }
  45.  
  46. int display(int arr[], int len) {
  47. int i;
  48. for (i = 0; i < len; i++)
  49. printf("%d ",arr[i]);
  50. }
  51.  
  52. // Driver Code
  53. int main() {
  54. int arr[20] = {12, 16, 20, 40, 50, 70};
  55. int len = 6, num, key;
  56.  
  57. while (1) {
  58. printf("\nArray: ");
  59. display(arr, len);
  60.  
  61. switch (menu()) {
  62. case 1:
  63. printf("What do you want to insert? : ");
  64. scanf("%d", &num);
  65. printf("At which position do you want to insert %d? : ", num);
  66. scanf("%d", &key);
  67. len = insert(arr, len, num, key);
  68. break;
  69. case 2:
  70. printf("Enter the position of the element that you want to delete: ");
  71. scanf("%d", &key);
  72. len = delete(arr, len, key);
  73. break;
  74. case 3: return 0;
  75. default: printf("\nInvalid option\n");
  76. }
  77. }
  78. }
Add Comment
Please, Sign In to add comment