0% found this document useful (0 votes)
0 views3 pages

Create A Stack Using Array

The document provides a C++ implementation of a stack data structure using an array. It includes functions for pushing and popping elements, checking if the stack is empty, and handling overflow conditions. The main function demonstrates the stack operations and handles edge cases such as popping from an empty stack.

Uploaded by

pranav1256kam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views3 pages

Create A Stack Using Array

The document provides a C++ implementation of a stack data structure using an array. It includes functions for pushing and popping elements, checking if the stack is empty, and handling overflow conditions. The main function demonstrates the stack operations and handles edge cases such as popping from an empty stack.

Uploaded by

pranav1256kam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

1.

Create a stack using array


2.Function for push
3.Function for pop
4.Function for isempty
5.Function for isfull
6. #include <iostream>
7. using namespace std;
8.
9. const int MAX_SIZE = 5; // Maximum size of the stack
10.
11. struct Stack
12. {
13. int arr[MAX_SIZE];
14. int top;
15.
16. Stack()
17. {
18. top = -1; // Initialize the top of the stack
19. }
20.
21. // Push an element onto the stack
22. void push(int value)
23. {
24. if (top >= MAX_SIZE - 1)
25. {
26. cout << "Stack overflow. Cannot push " << value << "
onto the stack." << endl;
27. }
28. else
29. {
30. arr[++top] = value;
31. }
32. }
33.
34. // Pop an element from the stack
35. int pop()
36. {
37. if (top < 0)
38. {
39. cout << "Stack is empty. Cannot pop." << endl;
40. return -1; // Return a sentinel value to indicate an
error
41. }
42. else
43. {
44. int value = arr[top];
45. top--;
46. return value;
47. }
48. }
49.
50. // Check if the stack is empty
51. bool isEmpty()
52. {
53. return (top == -1);
54. }
55. };
56.
57. int main()
58. {
59. Stack stack;
60.
61. // Try to pop from an empty stack
62. int poppedValue = stack.pop();
63. if (poppedValue != -1)
64. {
65. cout << "Popped: " << poppedValue << endl;
66. }
67.
68. stack.push(10);
69. stack.push(20);
70. stack.push(30);
71. stack.push(40);
72. stack.push(60);
73. stack.push(70);
74.
75. while (!stack.isEmpty())
76. {
77. int value = stack.pop();
78. cout << "Popped: " << value << endl;
79. }
80.
81. return 0;
82. }
83.
Output:-

You might also like