Hi I'm new here and I'm also a beginner programmer.
In school I was given a assignment to create a program implementing a stack using an array... I understand the concept of the stack because it was taught in class, but I'm having trouble with the code. I am also a bit rusty on arrays. Any ideas? (C++ is what I'm using, of course)
A stack needs the following:
- a push function
- a pop function
- a way to tell when the stack is full (so you don't push)
- a way to tell when the stack is empty (so you don't pop)
- a pointer to the top of the stack so you know where to push to or pop from
Because you mentioned arrays, I assume you will be using an standard, fixed-size array to implement your stack. You will need an index counter or a pointer into the array to indicate where the top of the stack is. From that you can determine full and empty. I will leave pushing and popping for you to try implementing for the time being.
As far as being rusty with arrays:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// number of elements in the array
#define ARRAYSIZE (3)
// declare an array of ints, indexed from 0 to (STACKSIZE - 1)
int array[ARRAYSIZE];
// access the first int in the array
int first = array[0];
// access the last int in the array
int last = array[ARRAYSIZE - 1];
// loop through all of the ints in the array
for (int i = 0; i < ARRAYSIZE; ++i)
{
int current = array[i];
}
Why don't you start writing a Stack class and show us what you have. We can better help you with difficulties at that point.