NerdPC
NerdPC

Reputation: 1

C++ stacks and 2D array

I have been working on a Project that is suppose to simulate link list by using 2D array for stacks. I have the code but I can not figure out how to make the Random numbers work. I have looked online but online doesn't explain how to make the random function work with the simulation. Here is my code below:

`#include <iostream>

#include <stdlib.h>
using namespace std;

int myTop = -1;
int index = -1;
int next = -1;
int tt[25][2]; 
void construct()
{
    tt[25][2];
}

void empty()
{
    if (myTop == -1)
        cout << "Empty Stack";
    else
        cout << "Full Stack";
}

void push(int x)
{
    if (myTop < 24)
    {   
        myTop++;
        tt[myTop] = x;  
    }
    else
        cout << "The stack is full.";       
}

void top()
{
    if (myTop != -1)
        cout << "Top Value is: " << tt[myTop];
    else
        cout << "Empty Stack";

}

int pop()
{
    int x;
         if(myTop<=0)
         {
                cout<<"stack is empty"<<endl;
                return 0;
         }
         else
         {
                x=tt[myTop];
                myTop--;
          }
          return(x);

}

void display()
{
    for (int row=0; row<25; row++)
    {
        for (int column=0; column<3; column++)
        {
            cout << tt[row][column] << "\t";
            if (column == 2)
                cout << endl;
        }
    }
    cout << endl;
}

int main()
{
    push(rand() % 25);
    display();
    push(rand() % 25);
    display();
    push(rand() % 25);
    display();
    push(rand() % 25);
    display();
    top();
    pop();
    display();
    top();
    pop();
    display();
    top();
    pop();
    display();
    }

Upvotes: 0

Views: 3054

Answers (3)

Topo
Topo

Reputation: 5002

Here is how to use random numbers in C++

#include <cstdlib>
#include <ctime>

int main ()
{
  srand(time(NULL));
  number = rand() % 10 + 1; # Random number between 1 and 10
}

Upvotes: 0

Jesse Good
Jesse Good

Reputation: 52365

You haven`t initialized the random number generator (this is called "seeding").

Add the following to your code.

#include <time.h>

srand (time(0));

And on another note, I prefer using ctime and cstdlib as those are c++ headers (although this can be debated). Also, look into the random header if you have access to an up-to-date compiler.

Upvotes: 4

Related Questions