# Reverse output (Stack)

Printable View

Show 80 post(s) from this thread on one page
Page 1 of 2 12 Last
• 06-29-2004
silicon
Reverse output (Stack)
Hi everyone, I've been taking a class on cprogramming and have been successful up until classes. I am now learning about stacks but was told to apply it to the program below so that the output
1
2
3
4

will print out
4
3
2
1

I understand the concept in which the output will first be stored in an array [1,2,3,4] but am not entirely sure on how to retreive it without making the program really long. I know about pop functions but have only used this with push empty and full functions in class. I am just having problems on trying to figure out how to implement it here. Will I have to use a pop function to remove the numbers from top to bottom and then print them out that way? Can I complete this by just adding the pop function. please let me know if you have any suggestions
Any help will be greatly appreciated

Thanks

Code:

```#include * "" "" using namespace std; const string space = ""; void primefactor(int number); bool isprime(int number); int main() {   int n;   cout << "Enter a number > 1000 -> ";   cin >> n;   primefactor(n);   return 0; } void primefactor(int n) {   bool truePrime = trueprime(n);   int prime = n;   int i = 2, j;   double squareRoot = sqrt(static_cast<double>(n));         int count = 0;     cout << "The prime factorization of " << n << " is:" << endl;                 if(truePrime)       cout << space << n << " is a prime number." << endl;   else {       while((prime > 0) && (i <= n)) {         if((prime % i) == 0) {                                 count++;                                 for(j = 0; j < count; j++)                                         cout << space;             cout << i << " is a factor" << endl;             prime /= i;                         } else                        i++;       }   } } bool trueprime(int n) {   int i;     for(i = 2; i < n; i++) {       if((n % i) == 0)         return false;   }     return true; }```
• 06-29-2004
anonytmouse
Code:

```#include <iostream> #include <stack> using namespace std; int main(void) {     stack<int> s;     s.push(1);     s.push(2);     s.push(3);     cout << s.top() << endl;     s.pop();     cout << s.top() << endl;     s.pop();     cout << s.top() << endl;     s.pop();     cin.get();     return 0; }```
Now, try it out and try to incorporate the concept in your code and post back if you still have trouble.

OK, I admit it, I pretty much stole the code from sgi. Search "stack stl", it's not that hard.[/edit]
• 06-29-2004
Zagaberoo
Maybe...
If you are simply looking to have the program print the numbers backwards, simply do this

Code:

```#include <iostream> using namespace std; int main() {       int numbers[4];       numbers[0] = 1;numbers[1] = 2;numbers[2] = 3;       numbers[3] = 4;       for(int i = 3;i >= 0;i--)       {             cout << numbers[i];       }       return 0; }```
• 06-29-2004
quzah
Think of a stack like a stack of paper:
1) Take a piece of paper, write something one it, then put it on your desk.
2) Take another piece of paper, write something else on it, put it on that paper.
3) Go to step 2 as often as you like.
4) When you get bored, take the top piece of paper off the stack and look at it.
5) Repeat step 4 until it's empty. Alternately, jump to step 2 whenever you like.

That's a stack. That's as simple as it is.
A queue is the same, except for in step 4 you take from the bottom instead of the top.

The simplest implementation of a stack is to use an array. All you need is an array and a counter. The counter keeps track of the highest free space. To push, put something in the highest free space, then increment the counter. To pop, decrement the counter, and return whatever is now to where it's pointing.

I was going to provide sample code, but I can't think of a way to do it that wouldn't be giving you the whole thing, because it's such a simple concept once you read the above.

And because it's so fun...
Code:

```Stack s1, s2; while( !s1.isEmpty( ) )     s2.push( s1.pop() );```
There's how you reverse a stack. ;)
[/edit]

Quzah.
• 06-29-2004
silicon
Reverse output Stack problem
Hello all, I wanted to say thank you so much for all the help. I've written the code and tried to use other functions that I've learned in past programming. Unfortunately I am still having problems. It seems that I am making a bunch of mistakes somewhere and I am not sure if I am getting close to correctly writing the program. Can you please let me know if I should just start from scratch and rewrite the program. I want to make sure that I come away from this understanding stacks and knowing where I wen wrong. Also does anyone have any suggestions on any good c++ programming books.

Thanks in advance for any help

Code:

```#include <iostream> #include <string> #include <cmath> using namespace std; const int Stack_Size=12; //Initialization of Stack Size// const string space=""; class Stack { public:         Stack(); //constructor//         void primefactor(int number);         bool isprime(int number);         void push(int);         int pop();         bool peek();         bool empty();         bool full();         private:         int count;         int data[Stack_Size]; };                 Stack::Stack()                  {                         count=-1;                 } void primefactor(int n) {   bool isPrime = isprime(n);   int prime = n;   int i = 2, j;   double squareRoot = sqrt(static_cast<double>(n));         int count = 0;     cout << "The prime factorization of " << n << " is:" << endl;                 if(isPrime)       cout << space << n << " is a prime number." << endl;   else {       while((prime > 0) && (i <= n)) {         if((prime % i) == 0) {                                 count++;                                 for(j = 0; j < count; j++)                                         cout << space;             cout << i << " is a factor" << endl;             prime /= i;                         } else                        i++;       }   } } bool isprime(int n) {   int i;     for(i = 2; i < n; i++) {       if((n % i) == 0)         return false;   }     return true; }                 void Stack::push(int value)                 {                         count++;                         data[count]=value;                 }                 int Stack::pop()                 {                         int topvalue;                         topvalue=data[count];                         count--;                         return(topvalue);                 }                                                         bool Stack::empty()                 {                         if (count==-1)                                 return 1;                         else                                 return 0;                 }                 bool Stack::full()                  {                         if (count==Stack_Size-1)                                 return 1;                         else                                 return 0;                 }                 int main()                 {                         Stack entries;                         int number;                         char answer;                                         cout<<" Please enter that is greater than 100\n  ";                 while(1) {         cout<<"Digit:\n";         cin>>number;         if (number<100)                 break;         if (entries.full())                  {                 cout<<"The stack is full and you do not have any space left\n";                                 break;                 }                 else                   entries.push(number);                                         }                                                         if (entries.empty()) //        {                 cout<<"The stack is empty\n";                         }         else                 while (!entries.empty())         {                                         cout<<" Do you want to pop an item from the stack?  ";                         cin>>answer;                         if (answer=='y')                         cout<<entries.pop()<<endl;                         else                                 break;         }         return 0;         }```
• 06-29-2004
quzah
You should streamline your classes. Your Stack class should only be a stack, nothing more. So, at its simplest:
Code:

```class Stack {     bool full( );     bool empty();     void push(int);     int pop();     ... };```
Just write a simple test program with your Stack class, and get it working. Once the stack itself is working, then you could add other functionality (by deriving another class from it with your other functionality, or whatever).

Quzah.
• 07-01-2004
silicon
Reverse output (Stack)...almost there
Hello all, I am praying that I am now on the right track. I've read all of your postings (which have been extremely helpful) and read more into stacks over the past few days and modified my code. I wrote a simple stack and got it to work. My problem is that now I tried to combine it with my other functions but am getting errors. As long as someone can confirm that i am on the right track...then that will be good enough news for me. I will modify the main a little bit more but I am having problems on making sure that the stack takes the data from my primefactor() so that I can pop all of the factors to reverse the output.

Thanks in advance

Code:

```#include <iostream.h> const int STACK_MAX= 20; typedef int StackElement; class Stack  {   private:   StackElement StackArray[STACK_MAX];   int StackTop;  public:         bool empty();         int primefactor(int number);         bool isprime();         bool full( );           bool isprime(int number);     void push(int);     void pop();     Stack::Stack()                          //Constructor   {     StackTop=-1;   }   inline bool Stack::empty() const      //Check for emptyness   {     return(StackTop==-1);   }   Stack::primefactor(int number) {   bool isPrime = isprime();   int prime = number;   int i = 2, j;   double squareroot = sqrt(static_cast<double>(number));         int count = 0;   cout << "The prime factorization of the number " << number << " is:" << endl;         if(isPrime)       cout << space << number << " is a prime number." << endl;   else {       while((prime > 0) && (i <= number)) {         if((prime % i) == 0) {                                 count++;                                 for(j = 0; j < count; j++)                                         cout << space;             cout << i << " is a factor" << endl;             prime /= i;                         } else                        i++;       }  return true; }     bool isprime(int number) {   int i;     for(i = 2; i < number; i++) {       if((number % i) == 0)         return false;   }    void Stack::push(const StackElement & value)  //Add value to the Stack   {     if(StackTop<STACK_MAX-1)                    //If Stack is not full add element             {       ++StackTop;       StackArray[StackTop]=value;       }     else     cout<<"Stack is full. \n";   }     StackElement Stack::top()const    //function to retireve value at top of Stack     {       if(StackTop>=0)                  //If Stack is not empty perform task       return StackArray[StackTop];       else       cout<<"Stack is empty\n";       }     void Stack::pop()        //Function to discard value at top of Stack       {       if(StackTop>=0)        //If Stack is not empty perform task         StackTop--;       else       cout<<"Stack is empty\n";       }         void Stack::display()    //Function to write the entire stack     {     for(int i=StackTop;i>=0;i--)     cout<<StackArray[i]<<endl;     }               int main()  {     Stack factors;         int number;           cout << "Enter a number > 1000 ";   cin >> number;       bool isPrime = isprime();   int prime = number;   int i = 2, j;   double squareroot = sqrt(static_cast<double>(number));         int count = 0;     cout << "The prime factorization of the number " << number << " is:" << endl;                 if(isPrime) //should this be factors.isPrime()       cout << space << number << " is a prime number." << endl;   else {       while((prime > 0) && (i <= number)) {         if((prime % i) == 0) {                                 count++;                                 for(j = 0; j < count; j++)                                         cout << space;             cout << i << " is a factor" << endl;             prime /= i;                         } else                        i++;                         factors.top                         factors.pop                         factors.display           };```
• 07-01-2004
swoopy
When you make a Class, you have to make sure each member function matches its prototype. For example, you have isprime() prototyped twice, but only one isprime() implementation:

> bool isprime();
> bool isprime(int number);

I would assume the second one is right, unless you want two isprime() functions, but you've only defined one.

> void push(int);
This doesn't match the implementation. The implementation looks like this:
void push(const StackElement & value)

And you left out some function prototypes: top() and display(). They are defined, but not listed in your class declaration.

When you declare a class, you can declare functions, then worry about the definition later. But not the opposite. If you have a top() implementation, it has to be declared in the class declaration (interface).

Also, you are missing braces in several places. For example:
> inline bool Stack::empty() const //Check for emptyness
> {
> return(StackTop==-1);
> }
Here add one to end the class:
};

> return true;
>}
And here at the end of primefactor()

}//Probably goes here.
return true;
}

Line up your code so it's indented properly, and missing braces are easy to spot.

Make these changes, make sure declarations and definitions match, then recompile. Then repost your latest copy.

One final observation:
>#include <iostream.h>

Unless you have an old compiler, you should use the newer headers:
#include <iostream>
using namespace std;
• 07-02-2004
The Brain
having more than one function prototype... but with a different parameter list... seems to indicate function overloading.... :rolleyes:
• 07-02-2004
swoopy
>having the same function prototype.. but with a different parameter list... seems to indicate function overloading..

Or an oversight.
• 07-06-2004
silicon
Stack (Reverse Output)
Hello all, thanks for being patient and for all of the tips. I've rewritten most of my code and came up with what's below. I am receiving 3 errors so I am unable to troubleshoot or see if there will be errors in the output. I believe that it is definitely close now. I know that the errors are with my function calls at the end but I thought that this was the method used for calling them.

Code:

```#include <iostream> #include <string> #include <cmath> using namespace std; const string SPACE_STR = "  "; static const int MAX_CAPACITY = 1000; class Stack { public:     Stack()    { top = 0; }     void primefactor (int number);         bool is_prime(int number);         void Push(int number) ;     int Pop(int number) ;           private: int arraystack[MAX_CAPACITY]; int top; }; // Function I need help with. void Stack::primefactor(int number) {   bool isPrime = is_prime(number);   int prime = number;   int i = 2, j;   double squareRoot = sqrt(static_cast<double>(number));         int count = 0;     cout << "The prime factorization of the number " << number << " is:" << endl;                 if(isPrime)       cout << SPACE_STR << number << " is a prime number." << endl;   else {       while((prime > 0) && (i <= number)) {         if((prime % i) == 0) {                                 count++;                                 for(j = 0; j < count; j++)                                         cout << SPACE_STR;             cout << i << " is a factor" << endl;             prime /= i;                         } else                        i++;       }   } } bool Stack::is_prime (int number) {   int i;     for(i = 2; i < number; i++) {       if((number % i) == 0)         return false;   }     return true; } void Stack::Push(int number) { if (top < MAX_CAPACITY)         arraystack[top++] = number; } int Stack::Pop(int number)  { if (top > 0) return arraystack[--top]; else return 0;  } int main() {   int number;   cout << "Enter a number > 1000 -> ";   cin >> number;   Stack::primefactor();   Stack::Push();   Stack::Pop();   return 0; }```
• 07-06-2004
quzah
How about posting your errors when you get them? Otherwise we have to play psychic... It's just plain bad form to not do so. Also, it's listed in the Announcements, IIRC, that you should do so if you actually want some help.

Quzah.
• 07-06-2004
silicon
Sorry about that

--------------------Configuration: Prime12 - Win32 Debug--------------------
Compiling...
Prime12.cpp
C:\Documents and Settings\Steve\Desktop\Mat 373 Class\Prime12.cpp(81) : error C2660: 'primefactor' : function does not take 0 parameters
C:\Documents and Settings\Steve\Desktop\Mat 373 Class\Prime12.cpp(82) : error C2660: 'Push' : function does not take 0 parameters
C:\Documents and Settings\Steve\Desktop\Mat 373 Class\Prime12.cpp(83) : error C2660: 'Pop' : function does not take 0 parameters
Error executing cl.exe.

Prime12.obj - 3 error(s), 0 warning(s)
• 07-06-2004
elad
in main() declare a variable of type Stack like this:

Stack myStack;

Then call methods of the Stack like this:

myStack.primefactor(number);
myStack.Push(number);
myStack.Pop();

The error messages mean that when you call each of the Stack methods you are not putting an appropriate number of parameters in the call argument list.

Pop() functions usually don't have any parameters. They just pop either the first or the last value in a container.
• 07-06-2004
quzah
Quote:

C:\Documents and Settings\Steve\Desktop\Mat 373 Class\Prime12.cpp(81) : error C2660: 'primefactor' : function does not take 0 parameters
C:\Documents and Settings\Steve\Desktop\Mat 373 Class\Prime12.cpp(82) : error C2660: 'Push' : function does not take 0 parameters
C:\Documents and Settings\Steve\Desktop\Mat 373 Class\Prime12.cpp(83) : error C2660: 'Pop' : function does not take 0 parameters
Error executing cl.exe.
These are very simple errors if you just look at your code:
Code:

```int main() {   int number;   cout << "Enter a number > 1000 -> ";   cin >> number;   Stack::primefactor();   Stack::Push();   Stack::Pop();   return 0; }```
Code:

```class Stack { public:     Stack()    { top = 0; }     void primefactor (int number);         bool is_prime(int number);         void Push(int number) ;     int Pop(int number) ;```
See the problem now?

Quzah.
Show 80 post(s) from this thread on one page
Page 1 of 2 12 Last