By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,847 Members | 2,296 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,847 IT Pros & Developers. It's quick & easy.

stack using C++

P: 16
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.
Jan 10 '07 #1
Share this Question
Share on Google+
2 Replies


Rryk
P: 1
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:

Expand|Select|Wrap|Line Numbers
  1. include <stdio>;
  2. include <stdlib.h>;
  3.  
  4. // redefine this to set up a maximum numbers could be hold in stack
  5. #define MAX_SIZE 100
  6. // define from which interval we will get random numbers
  7. #define MIN_RAND 0
  8. #define MAX_RAND 1000
  9.  
  10. int * stackArray = new int[MAX_SIZE];
  11. int stackSize = 0;
  12.  
  13. // to get lasy number from the top and delete it from stack
  14. int pop()
  15. {
  16.    return stackArray[--stackSize];
  17. }
  18.  
  19. // to get last number from the top without delete it from stack
  20. int pick()
  21. {
  22.    return stackArray[stackSize-1];
  23. }
  24.  
  25. // put a number into a stack
  26. void put(int i)
  27. {
  28.    stackArray[stackSize++] = i;
  29. }
  30.  
  31. void main()
  32. {
  33.    int i;
  34.    // to initiate randomizer
  35.    srand();
  36.  
  37.    // generate 20 random number and put them into a stack
  38.    for (i = 0; i < 20; i++)
  39.    {
  40.       int number = (int)((rand()/RAND_MAX)*(MAX_RAND-MIN_RAND)+MIN_RAND);
  41.       put(number);
  42.    }
  43.  
  44.    // get numbers from stack and print them out
  45.    while (stackSize > 0)
  46.    {
  47.       cout << pop();
  48.    }
  49. }
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;
Jan 10 '07 #2

Banfa
Expert Mod 5K+
P: 8,916
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.
Jan 10 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.