stack using C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • selam
    New Member
    • Nov 2006
    • 16

    #1

    stack using C++

    I have a problem in C++.My problem is how to push random number to a stack.
    It is to generate 20 random numbers and push it to the stack and pop it from the stack when it's needed.
  • Rryk
    New Member
    • Jan 2007
    • 1

    #2
    What do u mean by 'stack'? Is it a command stack or simply array (and several stack functions) or do u want to use any class from standart libraries (like MFC)?

    If u simply need a stack in your program u may use this code:

    Code:
    include <stdio>;
    include <stdlib.h>;
    
    // redefine this to set up a maximum numbers could be hold in stack
    #define MAX_SIZE 100
    // define from which interval we will get random numbers
    #define MIN_RAND 0
    #define MAX_RAND 1000
    
    int * stackArray = new int[MAX_SIZE];
    int stackSize = 0;
    
    // to get lasy number from the top and delete it from stack
    int pop()
    {
       return stackArray[--stackSize];
    }
    
    // to get last number from the top without delete it from stack
    int pick()
    {
       return stackArray[stackSize-1];
    }
    
    // put a number into a stack
    void put(int i)
    {
       stackArray[stackSize++] = i;
    }
    
    void main()
    {
       int i;
       // to initiate randomizer
       srand();
    
       // generate 20 random number and put them into a stack
       for (i = 0; i < 20; i++)
       {
          int number = (int)((rand()/RAND_MAX)*(MAX_RAND-MIN_RAND)+MIN_RAND);
          put(number);
       }
       
       // get numbers from stack and print them out
       while (stackSize > 0)
       {
          cout << pop();
       }
    }
    Sorry - hadn't time to test code. It should work, but there may be some syntax errors. And while using functions pop() and put() check maximum size of stack and if stack is empty, as i didn't wrote any error checking - wrong use will cause runtime error;

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      When you say the stack, I think you mean a stack.

      You will need to create a stack (of integers) to use. In such a simple case it could just be an array with a couple of index variables.

      Alternitively since it is C++ it would be rather easy to implement using a list or deque from the STL.

      Comment

      Working...