Infinite Loop problem. Help me!

I am trying to write a code which will have an array of 2 elements. A user enters initial values for array elements, N (Initial values are same) and enters probability value p.

p - probability that someone will choose an array element rolls[0] and subtracts one.
1-p is a probability that someone will choose an array element rolls[1] and subtracts one.

The program should compare probability p with random number from 0 to 1.

It should repeat until one of the array element equal to zero, and my program should record a none zero array element number.

My code is not working properly because of my while loop I guess. Can any one help me to figure out how to correct my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  double rand_uniform();

int main ()
{
  srand(time(0));                // different seeds 
  const int num_sims = 1000000;  // number of trials for our simulation

  int N;                // initial number of squares on each roll
  int Avg; 

  double p;             // probability of a big-chooser
  double r;             // randomly generated number from 0 to 1

  int total_squares;    // for each trial we'll keeping a running sum
                        // of the squares left on the non-empty roll

  cout << "Please enter N ";
  cin >> N;
  cout << "Please enter p ";
  cin >> p;
  cout << endl << "Entered N: " << N << ", " << "Entered P: " << p << endl;
  
  int rolls [2] = {N,N};
  cout << "Array Element no 1: " << rolls[0] << endl;
  cout << "Array Element no 2: " << rolls[1] - 1 << endl;
  
  int i = 0; int j = 0;
  while (rolls[0] != 0 || rolls[1] != 0)
  {
     r = rand_uniform();
     cout << "Random number: " << r << endl;
     if (r <= p)
     {
       rolls[0] = rolls[0] - 1;
       i++;
       cout << "Number of i: " << i << "Array 1: " << rolls[0] <<endl;
     }
     else 
     {
       rolls[1] = rolls[1] - 1;
       j++;
       cout << "Number of j: " << i << "Array 2: " << rolls[1] <<endl;
     }
  }
   return 0;
}

 double rand_uniform()
{
  double r = rand() * 1.0/RAND_MAX; //Random number between 0 and 1
  return r;
} 
Line 28. OR. Loop continues if either is not 0. In other words, the loop can end only if both are 0. Quite unlikely.

Furthermore, the values should not go to negative, so you could test like 0<a && 0<b


Non-fatal:
Why does line 25 show a value-1?

What are i and j?

Line 42 says "j" but shows i.

There is a shorthand for rolls[0] = rolls[0] - 1; -- the decrement operator: --rolls[0];

Code has unused variables.
Thank you very much!
I'll polish my code:)
Topic archived. No new replies allowed.