DS | Practical-3 | Stack Implementation Using Array in C

 

Do Stack Implementation Using Array Push, Pop , Peep,CHANGE and DISPLAY in C

GTU DS Practical-3

Implement a program for the stack that performs the following operations using an array.
PUSH, POP, PEEP, CHANGE, DISPLAY.

  1. #include<stdio.h>
  2. #define size 5
  3. struct stack{
  4. int a[size],top;
  5. int temp[size], tos;
  6. }s;
  7. // Push operation....
  8. void push(int item){
  9. s.a[++s.top] = item;
  10. }
  11. // Pop operation....
  12. int pop(){
  13. return s.a[s.top--];
  14. }
  15. // Display operation....
  16. void display(){
  17. int i;
  18. printf("\nThe stack contains: ");
  19. for(i = s.top; i>=0; i--){
  20. printf("\n\t%d", s.a[i]);
  21. }
  22. }
  23. // Peep operation....
  24. void peep(){
  25. printf("\n\tTop : %d", s.top);
  26. printf("\n\tValue: %d",s.a[s.top]);
  27. }
  28. void change(int row, int new_element){
  29. int i;
  30. int j = -1;
  31. printf("\n\tTop: %d", s.top);
  32. for(i=s.top; i>row; i--){
  33. s.temp[++j] = s.a[s.top--];
  34. /*
  35. display();
  36. printf("\n\tTop: %d", s.top);
  37. printf("\n\t j : %d", j);
  38. */
  39. }
  40. s.a[s.top] = new_element;
  41. /*
  42. display();
  43. printf("\n\tTop: %d", s.top);
  44. printf("\n\t j : %d", j);
  45. */
  46. for(i = j; i>-1; i--){
  47. s.a[++s.top] = s.temp[j--];
  48. /*
  49. display();
  50. printf("\n\tTop: %d", s.top);
  51. printf("\n\t j : %d", j);
  52. */
  53. }
  54. }
  55. int main(){
  56. s.top = -1;
  57. int item, choice, row, new_element;
  58. char ans;
  59. do{
  60. printf("\n-----------------------------");
  61. printf("\nSTACK IMPLEMENTATION PROGRAM\n");
  62. printf("-----------------------------");
  63. printf("\n 1. Push\n 2. Pop\n 3. Display\n 4. Peep\n 5. Change\n 6. Exit\n");
  64. printf("-----------------------------\n");
  65. printf("\n Enter your choice: ");
  66. scanf("%d", &choice);
  67. switch(choice){
  68. case 1:
  69. if(s.top >= size-1){
  70. printf("\nStack overflow..\n");
  71. break;
  72. }
  73. printf("\nEnter item to be pushed: ");
  74. scanf("%d", &item);
  75. push(item);
  76. break;
  77. case 2:
  78. if(s.top == -1){
  79. printf("\n..Stack underflow..\n");
  80. break;
  81. }
  82. pop();
  83. break;
  84. case 3:
  85. display();
  86. break;
  87. case 4:
  88. peep();
  89. break;
  90. case 5:
  91. printf("\n\tEnter row no : ");
  92. scanf("%d",&row);
  93. printf("\n\tEnter new element: ");
  94. scanf("%d", &new_element);
  95. change(row, new_element );
  96. break;
  97. case 6:
  98. return 0;
  99. }
  100. }while(choice != 6);
  101. return 0;
  102. }

Go To:
Home Page:
Practical 2 :
Practical 4:

Comments