Easy Programming

C++ Stacks:

In my last tutorial, I introduced stacks to you and what I would be doing to teach you stacks. In this tutorial, I use what I taught you in my last tutorial to code a program from scratch. I do this the long way without using the Stack library.

There are other ways to do stacks, this is just the way I am teaching you, using structs, arrays, while loops, and functions. This method of teaching shows you exactly what goes on within a Stack. If you are interested in knowing the stack library, I may make a tutorial for that in the future.

If you have any questions about the program or anything in general relating to beginner C++ Programming, feel free to ask.

Click here to go back

//Programmer:	Nazmus
//Program:		Stacks Tutorial
//Website:		EasyProgramming.net

#include<iostream>

#include<string>
using namespace std;

const int maxstack = 7;

struct stacktype
{
	string name[maxstack];
	int top;
};

void createstack(stacktype &stack);
void destroystack(stacktype &stack);

bool fullstack(stacktype stack);
void push(stacktype &stack, string &newelement);

bool emptystack(stacktype stack);
void pop(stacktype &stack, string &poppedelement);

int main()
{
	stacktype stack; 
	string newelement, poppedelement;
	char quest;

	createstack(stack);

	cout << "Do you want to enter data (y/n)? ";
	cin >> quest;

	while((quest == 'y' || quest == 'Y') && !(fullstack(stack)))
	{	
		cout << "Please enter name: ";

		cin >> newelement;
		
		push(stack, newelement);

	cout << "Do you want to enter data (y/n)? ";
	cin >> quest;

	}

	cout << endl << endl;

	while(!emptystack(stack))
	{
		pop(stack, poppedelement);

		cout << poppedelement << endl;
		
	}
	destroystack(stack);
	system("pause");
}

void createstack(stacktype &stack)
{
	stack.top = -1;
}

void destroystack(stacktype &stack)
{
	stack.top = -1;
}

bool fullstack(stacktype stack)
{
	if(stack.top == maxstack -1) return 1;

	else return 0;
}

void push(stacktype &stack, string &newelement)
{

	stack.top++;
	stack.name[stack.top] = newelement;
}

bool emptystack(stacktype stack)
{
	if(stack.top == -1) return 1;

	else return 0;
}

void pop(stacktype &stack, string &poppedelement)
{

	poppedelement = stack.name[stack.top];
	stack.top--;
}