Stack using arrays - c++

If suppose i want to implement a stack in c++ using arrrays is it better to do it via making a structure or class for storing the location of head and stuff like that or should you implement in more of a hard code style like this -
#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}
Im just trying to know what is a more accepted method.

The approach you've taken here using global variables is fine for a simple implementation, but it has a major drawback in most real-world applications: it's not reusable.
What if you need two stacks in your program? That would require creating a second set of global variables and a second set of functions to act on them.
That is the problem that using a class solves. If you wrap all of your stack's state in a class then you can create a single set of functions that can operate on any object of that class. Then creating a second stack is very simple.
Of course, for most real world applications you shouldn't implement your own stack anyway. Just use std::stack unless you have a very compelling reason not to. But that still supports the same conclusion. Because std::stack is a self-contained, reusable class any program can use it without having to re-implement their own stack logic (possibly multiple times).

Related

i can't get an output from this

#include<iostream>
using namespace std;
class stack
{
int size=10;
int stack[size]={0}, value=0, top;
top=size;
public:
void push(int v)
{
if(top==0)
cout<<"\nstack is full\n";
else
{--top;
stack[top]=v;}
}
void pop()
{
if(top==size)
cout<<"\nstack is empty\n";
else
{top++;
stack[top];
stack[top-1]=0;
}
}
void display()
{
if(top==size)
cout<<"\nstack empty\n";
else
{
for(int i=top;i<size-1;i++)
{
cout<<stack[i];
}
}
}
};
int main()
{
stack s;
char t;
int value,ch;
do
{
cout<<"\n1.push\n";
cout<<"\n2.pop\n";
cout<<"\n3.display\n";
cout<<"enter choice:\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nenter the value to be pushed\n";
cin>>value;
s.push(value);
break;
case 2:s.pop();
break;
case 3:s.display();
break;
default:
cout<<"\nwrong choice\n";
}
cout<<"\ndo u want to retry\n";
cin>>t;
}while(t=='y' || t=='Y');
return 0;
}
Simplest fix to errors occurring is changing int size=10; to static const int size=10;.
After this, apart from occurring warning with stack[top]; being empty statement, there is logical error in display loop in for(int i=top;i<size-1;i++) where it should be either for(int i=top;i<size;i++) or for(int i=top;i<=size-1;i++).
As answered by Tomáš Zahradníček, you need to fix a few things to have your code compile (using -std=c++11).
I used for(int i=top; i<size; ++i) in the display method. I also add that your pop method could simply do top++; without overwriting the stack.
Anyways, regarding your problem of nothing being printed on cout : you obviously tried with 1 item pushed in the stack, but not with 2, which would have pointed to faulty line (the for loop).

segmentation fault while using two different stack of same class in a program

i just started c++ and coded a program to push and pop in 2 stacks simultaneously inn a program....i coded it corectly but while i run the program and try to access the first stack i.e s1 it shows segmentation fault but i am able access my second stack s2 very perfectly.....help me
#include<iostream>
using namespace std;
#define max 10
class stack
{
private:
int arr[max],top;
public:
void init()
{
int top=0;
}
void push(int a)
{
arr[top++]=a;
}
int pop()
{
return arr[--top];
}
int isempty()
{
if(top==0)
return 1;
else
return 0;
}
int isfull()
{
if(top==max)
return 1;
else
return 0;
}
};
int main()
{
int a,z,cas;
stack s1;
stack s2;
s1.init();
s2.init();
while(1)
{
cout<<"Enter your choice i.e. :\n";
cout<<"1.Pushing in stack s1.\n";
cout<<"2.Pushing in stack s2.\n";
cout<<"3.Poping from stack s1.\n";
cout<<"4.Poping from stack s2.\n";
cout<<"5.To STOP.\n";
cin>>cas;
switch(cas)
{
case 1:
cout<<"Enter the number to push in stack s1:\n";
cin>>a;
if(s1.isfull()==0)
s1.push(a);
else
cout<<"The Stack is full.\n";
break;
case 2:
cout<<"Enter the number to push in stack s2:\n";
cin>>a;
if(s2.isfull()==0)
s2.push(a);
else
cout<<"The Stack is full.\n";
break;
case 3:
if(s1.isempty()==0)
cout<<"The number poped out is :\n"<<s1.pop()<<endl;
else
cout<<"The stack is empty.\n";
break;
case 4:
if(s2.isempty()==0)
cout<<"The number poped out is :\n"<<s2.pop()<<endl;
else
cout<<"The stack is empty.\n";
break;
case 5:
cout<<"The elements in stack s1 are :\n";
while(!s1.isempty())
cout<<s1.pop()<<" ";
cout<<endl;
cout<<"The elements in stack s2 are :\n";
while(!s2.isempty())
cout<<s2.pop()<<" ";
cout<<endl;
exit(1);
}
}
return 0;
}
Much more useful than a debugger is the art of reading carefully:
void init()
{
int top=0;
}
declares a local variable top.
The member variable is left uninitialised, leading to Undefined Behaviour.
That one of the stacks appears to work is just bad luck.
Making it a proper assignment:
void init()
{
top=0;
}
would do it, but this is C++, so you should use a constructor:
class stack
{
public:
stack();
// ...
};
stack::stack()
: top(0)
{
}
and then
stack s1;
stack s2;
while(1)
{
// ...

how to use gets function in c++ code?

In the main function of this code in the case 2 of switch case after entering the string program terminates! What is the problem with the code?
/*this code is a implementation of bubble sort algorithm*/
#include <iostream>
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<dos.h>
using namespace std;
int counter;
template <class T>//template created
class program//class which holds all the sorting functions
{
public:
T *v,x;
int j,k,l,siz,flag;
time_t t1,t2;
char c;
public:
void sortlist()//fn to sort characters and numbers
{
cout<<endl<<"------->>INTERMEDIATE STEPS<<-------";
for(k=1;k<=siz-1;k++)//sorting using a bubble sort
{ flag=0;
cout<<endl<<"PASS : "<<k<<endl;
j=0;
while(j<=siz-1-k)
{
if(v[j]>v[j+1])//comparing two consecutive elements
{
x=v[j+1];
v[j+1]=v[j];
v[j]=x;
flag++;
}
for(l=0;l<siz;l++)
{
cout<<v[l]<<" ";
}
cout<<endl;
j++;
}
cout<<"COMPARISONS:"<<(siz-k)<<endl;
if(flag==0)
{
cout<<endl<<"----->NO need to carry out more passes"<<endl<<"List is already sorted"<<endl;
break;
}
}
}
void stringsort()//fn to sort the strings
{
T a[90][20],b[1][20];
cout<<"enter the size of list:";
cin>>siz;
cout<<"enter the list:";
cin.ignore();
for(j=0;j<siz;j++)
{
gets(a[j]);
}
cout<<endl<<"------->>INTERMEDIATE STEPS<<-------";
for(k=1;k<=siz-1;k++)//sorting using bubble sort
{
flag=0;
cout<<endl<<"PASS : "<<k<<endl;
j=0;
while(j<siz-k)
{
x=strcmp(a[j],a[j+1]);//comparing two consecutive string
if(x>0)
{
strcpy(b[1],a[j+1]);
strcpy(a[j+1],a[j]);
strcpy(a[j],b[1]);
flag++;
}
for(l=0;l<siz;l++)
{
cout<<a[l]<<" ";
}
cout<<endl;
j++;
}
cout<<endl<<"COMPARISON:"<<(siz-k)<<endl;
if(flag==0)
{
cout<<endl<<"No need to carry out more passes"<<endl<<"List is already Sorted"<<endl;
break;
}
}
cout<<"SORTED LIST:"<<endl;
for(j=0;j<siz;j++)
{
cout<<endl<<a[j]<<endl;
}
}
};
int main()//main fn
{
int x;
char c;
do
{
program <char> p1;
program <int> p2;
cout<<endl<<"To sort a list of NUMBERS enter -> 1"<<endl<<endl<<"To sort string of CHARACTERS enter -> 2"<<endl<<endl<<"To sort a list OF STRINGS and DOUBLE_STRINGS enter -> 3";
cout<<endl<<endl<<"Enter either 1 OR 2 OR 3:";
cin>>x;
switch(x)
{
case 1://to sort list of numbers
{
cout<<endl<<"enter the size of list: ";
cin>>p2.siz;
cout<<"enter the list: "<<endl;
p2.v=new int[p2.siz];
for(p2.l=0;p2.l<=p2.siz-1;p2.l++)
{
cin>>p2.v[p2.l];
}
p2.sortlist();//sort and search in numbers
cout<<endl<<"SORTED LIST:"<<endl;//sorted list after the bubble sort
for(x=0;x<=(p2.siz)-1;x++)
{
cout<<p2.v[x]<<endl;
}
}
break;
case 2://to sort string of character
{
cout<<"enter the string of characters:";
cin.ignore()
gets(p1.v);
p1.siz=strlen(p1.v);
p1.sortlist();//sort in characters
cout<<endl<<"SORTED STRING:"<<p1.v;
}
break;
case 3://to sort list of strings
{
p1.stringsort();//sort list of string
}
break;
default:
cout<<"INVALID_CHOICE"<<endl<<endl;
}
cout<<endl<<"do u want to enter another list?y/n";
cin>>c;
}
while(c=='y');
return 0;
}
gets requires that you pass a pointer to enough storage space to hold the string that gets read. Your program passes an uninitialized pointer.
You're not really allowed to do anything with uninitialized values, so in theory your program can crash before it even enters the gets function.
Since the user can pass any amount of data to gets and your program would be responsible for storing it, the function is deprecated. It doesn't even exist any more in the C++ standard library as std::gets since 2011, although ::gets will probably always be available in POSIX. The short answer is, "don't."
You might consider std::string and std::getline instead.

menue driven program to perform the following queue operation using array en-queue, de-queue, count the number of elements and display in c++?

i need to make a C++ program for
menu driven program to perform the following queue operation using array en-queue, de-queue, count the number of elements and display in c++?
how to make this one ?
im very weak in c++ can anyone guide me or help me or link me to a complete program to study it and understand it?!!!
i tried but i coudnt do it so i really need help
is this right or not ?
#include<iostream.h>
#include<conio.h>
void push(int st[],int data,int &top); //declaring a push class
void disp(int st[],int &top); //declaring display class
int pop(int st[],int &top); //declaring a pop class
int flg=0;
int top=-1,tos=-1;
int st[50];
void push(int st[],int data,int &top) //push
{
if(top==50-1)
flg=0;
else
{
flg=1;
top++;
st[top]=data;
}
}
int pop(int st[],int &top) //pop
{
int pe;
if(top==-1)
{
pe=0;
flg=0;
}
else
{
flg=1;
pe=st[top];
top--;
}
return(pe);
}
void disp(int st[],int &top) //display
{
int i;
if(top==-1)
{
cout<<"\nStack is Empty";
}
else
{
for(i=top;i>=0;i--)
cout<<"\t"<<st[i];
}
}
void main()
{
int dt,opt; // declare varible
int q=0;
clrscr();
cout<<"\t\t\tStack operations";
cout<<"\n\n\tMain Menu.........";
cout<<"\n\n1.Push";
cout<<"\n\n2.Pop";
cout<<"\n\n3.Exit";
cout<<"\n\n4.display";
do // useing do while for to make choice and select any options
{
cout<<"\n\n\tEnter Your Choice 1-4:"; //entering your choice
cin>>opt;
switch(opt)
{
case 1:
cout<<"\nEnter the Element to be Push:";
cin>>dt;
push(st,dt,tos);
if(flg==1)
{
cout<<"the push is done";
if(tos==50-1)
cout<<"\nStack is Now Full";
}
else
cout<<"\nStack Overflow Insertion Not Possible";
break;
case 2:
dt=pop(st,tos);
if(flg==1)
{
cout<<"\n\tData Deleted From the Stack is:"<<dt;
cout<<"\n \t pop is done";
}
else
cout<<"\nStack Empty,Deletio Not Possible:";
break;
case 3:
q=1;
break;
default:
cout<<"\nWrong Choice Enter 1-3 Only";
case 4:
disp(st,tos);
break;
}
} while(q!=1);
}
There is a queue collection in the STL library which provides all of the functionality required above for you, if for some reason you are not allowed to use this then I suggest the following logic might be helpful
when an item is popped from the front of the queue all other items must be copied down 1 element, use a for loop for this
E.g
for (int index = 1; index < arraySize; index++)
{
if (item[index] == -1)
{
item[index-1] = -1;
break;
}
item[index - 1] = item[index];
}
when an element is deleted, all items that follow that item in the queue must be moved down 1 space, find the index of the element being deleted and use a for loop
E.g
for (int index = deletedItemIndex; index < arraySize; index++)
{
if (item[index] == -1)
break;
item[index] = item[index + 1];
}
when an item is added to the queue it is simply placed at the end of the queue, but not necessarily the end of the array (perhaps initialise all the array elements with -1 to start, that way you can easily test if you are at the end of the queue)

Error in a Link List

I wrote the following code for a Link list to create a Book its serial no. and search it. I am using linked list in it.
When I add my first entry , it is added successfully, but when I add second entry it shows segmentation fault. I am not able to figure out why. Please help.Thanks in advance.Code:
#include<iostream>
#include<string>
#include<fstream>
#include<cstdlib>
using namespace std;
struct book
{
int accno;
string name;
book* next;
};
int main()
{
bool flag=false;
int x,m;
string s;
book* front=NULL;
book* n;
do
{
cout<<"\nPlease select the following:\n1.Create and append\n2.Search\n3.Exit";
cin>>m;
switch(m)
{
case 1:
n=new book();
cout<<"\nEnter the book name: ";
cin>>s;
cout<<"\nEnter the acc no.: ";
cin>>x;
if(front==NULL)
{
front=n;
}
else
{ n=front;
while(n->next!=NULL)
{
n=n->next;
}
n=n->next;
}
n->accno=x;
n->name=s;
break;
case 2:
cout<<"Enter the roll no.";
int y;
cin>>y;
if(front==NULL){cout<<"Doesnot exist\n"; break;
}
else
{
n=front;
while(n->accno!=y && n->next!=NULL)
{
n->next=n;
}
cout<<"Book name is:"<<n->name;
cout<<"\nAccno is: "<<n->accno;
}
break;
case 3: flag=true;
break;
}
}
while(flag==false);
return 0;
}
Here
while(n->next!=NULL)
{
n=n->next;
}
n=n->next;
you iterate through the linked list to find the last element, then step past it. After this, n will be null.
What you are missing is creating a new element and appending it to the end of the list.
And here
n->accno=x;
n->name=s;
you must also assign n->next = null, otherwise your list won't be properly terminated.
Also, when searching for a book, here
while(n->accno!=y && n->next!=NULL)
{
n->next=n;
}
cout<<"Book name is:"<<n->name;
cout<<"\nAccno is: "<<n->accno;
after exiting the loop, either you found the book or n is null. You must check which is the case before trying to dereference n, otherwise you will again get a segfault if the book you are looking for is not in the list.
Learn to write a linked list (so if this is a homework targeted at learning them, it's valid, but it is not tagged as such), but never ever do it in practice. There is a standard library and there is boost and they have all data structures you'll need unless you do something really special.
You have C++, so don't write C-style code. book should have a constructor that should initialize it's members. The list head should probably be encapsulated in the class too and manipulated using it's methods.
You never set n->next, so don't be surprised it never contains anything meaningful.
You re-use n in the loop forgetting the object you constructed (memory leak).
Than you get the NULL at the end of the list instead of the object you constructed.
here lies your problem:
....
else
{
n=front;
while(n->next!=NULL) //access to next will cause seg fault!!!
{
n=n->next;
}
n=n->next; // step once more, now we have NULL on second add...
}
also, where is n->next being assigned? I don't see it anywhere?
What are you doing here?
case 1:
n=new book();
cout<<"\nEnter the book name: ";
cin>>s;
cout<<"\nEnter the acc no.: ";
cin>>x;
if(front==NULL)
{
front=n;
}
else
{
n=front;
}
while(n->next!=NULL)
{
n=n->next;
}
n=n->next;
}
n->accno=x;
n->name=s;
break;
You have created new book and assigned it to n, in first case its ok becasue your are directly assigning it to front. But in other case you should iterate list using someother variable (temp), when your write n = front, your have already lost your new book object pointer. Hope you got your answer.
This is a buggy code:
You need null the "next" field when you add a new node:
case 1:
new book();
n->next = NULL;
...
You have the memory leakage