Skip to content

Instantly share code, notes, and snippets.

@mycodeschool
Created October 8, 2013 02:44
Show Gist options
  • Star 69 You must be signed in to star a gist
  • Fork 33 You must be signed in to fork a gist
  • Save mycodeschool/6878628 to your computer and use it in GitHub Desktop.
Save mycodeschool/6878628 to your computer and use it in GitHub Desktop.
An object oriented implementation of stack using arrays in C++.
// Stack - Object oriented implementation using arrays
#include <iostream>
using namespace std;
#define MAX_SIZE 101
class Stack
{
private:
int A[MAX_SIZE]; // array to store the stack
int top; // variable to mark the top index of stack.
public:
// constructor
Stack()
{
top = -1; // for empty array, set top = -1
}
// Push operation to insert an element on top of stack.
void Push(int x)
{
if(top == MAX_SIZE -1) { // overflow case.
printf("Error: stack overflow\n");
return;
}
A[++top] = x;
}
// Pop operation to remove an element from top of stack.
void Pop()
{
if(top == -1) { // If stack is empty, pop should throw error.
printf("Error: No element to pop\n");
return;
}
top--;
}
// Top operation to return element at top of stack.
int Top()
{
return A[top];
}
// This function will return 1 (true) if stack is empty, 0 (false) otherwise
int IsEmpty()
{
if(top == -1) return 1;
return 0;
}
// ONLY FOR TESTING - NOT A VALID OPERATION WITH STACK
// This function is just to test the implementation of stack.
// This will print all the elements in the stack at any stage.
void Print() {
int i;
printf("Stack: ");
for(i = 0;i<=top;i++)
printf("%d ",A[i]);
printf("\n");
}
};
int main()
{
// Code to test the implementation.
// calling Print() after each push or pop to see the state of stack.
Stack S;
S.Push(2);S.Print();
S.Push(5);S.Print();
S.Push(10);S.Print();
S.Pop();S.Print();
S.Push(12);S.Print();
}
@jayeshcp
Copy link

Pop() function is incorrect. It should return the top value and decrement top.

void Pop() 
{
    if(IsEmpty()) { // If stack is empty, pop should throw error. 
        printf("Error: No element to pop\n");
        return;
    }
    return A[top--];
}

@samanvay17
Copy link

"Incorrect" is a strong word to use. He has already declared another function top() which returns the top element, so its actually needless to include it in Pop(). His Pop() does exactly what is should i.e. pop elements. Its all about coding styles

@sitansusubudhi
Copy link

how come you are returning A[top--] by giving void as a return type?

@marie-user667
Copy link

jayeshcp - better you be away from programming, LOL 😀

@tuhin75tk
Copy link

printf() function is used here...so "stdio.h" this header file must be included..!

Copy link

ghost commented Aug 14, 2016

line 22: instead of printf cout should be used

@akritithakur
Copy link

stdio needs to be included.

@amanuel1995
Copy link

I'm sorry, but may I ask what "#define MAX_SIZE 101" means and what it does?

@mayankgupta804
Copy link

"#define MAX_SIZE 101" sets the maximum size of the array to be equal to 101 and not more than that,ever.

@ayitikshome7614
Copy link

Since it is a C++ code , you must use cout instead of printf. Please change it !!

@anujgupta99
Copy link

One ridiculous question I know...Why wouldn't you define top in private instead of constructor in public?
Please answer it!

@ankitch6
Copy link

top is defined in private ....it is only initialized in the constructor.

@Dipk05
Copy link

Dipk05 commented Sep 17, 2017

Helpful..Thank You Sir.

@sayujaya
Copy link

sayujaya commented Jul 8, 2018

In Pop() method instead of the if condition checking if top == -1, can we call the IsEmpty() method inside the if condition to check if the stack is empty? If we can do we have to create a stack object first inside the Pop() method so we can call the IsEmpty() method?

@Nimeshka
Copy link

@sayujaya Yes, you can, and I think it's better to call IsEmpty() rather than duplicating the logic again in pop method. You don't create a new instance, just call it using this keyword. i.e. if (this->IsEmpty()) { // If stack is empty, pop should throw error. }

@singh-bhagirath
Copy link

line 22: instead of printf cout should be used

not necessary to use cout ,you can use printf as well as cout.

@abhicse113
Copy link

C++ is super set of C , so we can use both printf and cout.

Copy link

ghost commented Mar 6, 2020

please do you have a cpp file for stack implementation using linked list.

@humpty-dumpty-419
Copy link

Pop() function is incorrect. It should return the top value and decrement top.

void Pop() 
{
    if(IsEmpty()) { // If stack is empty, pop should throw error. 
        printf("Error: No element to pop\n");
        return;
    }
    return A[top--];
}

here in his above code "top" is used as a global variable so if he is calling pop() fn it means he is reducing the value of "top" and hence "top is global variable so no need to return as it was updated globally for all functions out there in above code.
pop() function is used to remove an element from the top of the stack(newest element in the stack). The element is removed to the stack container and the size of the stack is decreased by 1.

Syntax :
Parameters :
No parameters are passed.
Result :
Removes the newest element in the stack
or the top element.✌

@Reeshik
Copy link

Reeshik commented Jun 17, 2020

Pop() function is incorrect. It should return the top value and decrement top.

void Pop() 
{
    if(IsEmpty()) { // If stack is empty, pop should throw error. 
        printf("Error: No element to pop\n");
        return;
    }
    return A[top--];
}

here in his above code "top" is used as a global variable so if he is calling pop() fn it means he is reducing the value of "top" and hence "top is global variable so no need to return as it was updated globally for all functions out there in above code.
pop() function is used to remove an element from the top of the stack(newest element in the stack). The element is removed to the stack container and the size of the stack is decreased by 1.

Syntax :
Parameters :
No parameters are passed.
Result :
Removes the newest element in the stack
or the top element.✌

here u r using void pop() nd ur returning A [top--]....

@prateek753
Copy link

Can anyone tell me why we declared top and MAX_SIZE in private and not in public and then initializing top in constructor ?

@agargcode001
Copy link

Pop() function is incorrect. It should return the top value and decrement top.

void Pop() 
{
    if(IsEmpty()) { // If stack is empty, pop should throw error. 
        printf("Error: No element to pop\n");
        return;
    }
    return A[top--];
}

How can a void function return a value?

@untilhamza
Copy link

printf() function is used here...so "stdio.h" this header file must be included..!

very true

@DivyanshRathi
Copy link

I am sorry but I have a little doubt,....we defined a function in public as Stack which sets the value of top as -1. But we never called it in the main function, then why the stack is initialized with top = -1.

@Ahbar1999
Copy link

@DivyanshRathi a constructor is called automatically when a class' object is instantiated

@csgeeek
Copy link

csgeeek commented May 25, 2021

stdio needs to be included.

No, It isn't necessary.
It will work fine even if we don't put #include<stdio.h> in C/C++.

@csgeeek
Copy link

csgeeek commented May 25, 2021

I am sorry but I have a little doubt,....we defined a function in public as Stack which sets the value of top as -1. But we never called it in the main function, then why the stack is initialized with top = -1.

Stack is a constructor.
It will be called automatically when an object is created in int main()

@itsakashp
Copy link

itsakashp commented Jun 14, 2021

But if i am not wrong, the basic functionality of pop() function in stack is to delete the recent value and also return the deleted Value to the Calling Function
.int pop(){ if (isEmpty()) { cout<<"ERROR! No Element to POP\t"; } return A[top--]; };

@Abhinav12082003
Copy link

stdio needs to be included.

actually iostream is enough in cpp language

@JoNieRv
Copy link

JoNieRv commented Jan 2, 2023

stdio needs to be included.

actually iostream is enough in cpp language

he said that because printf is used in code instead of cout.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment