I’m almost done with a dice rolling program and my only issue is that I’m unable to input more than 5000 rolls, due to the size of the array I’ve specified. While I suppose I could simply increase the size of the array to some ridiculous number, I’d prefer not to and instead use a dynamically sized array based on the input remainingRolls. Can anyone help?
NOTE: This is the edited and final code that works.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int roller(){ // loop to simulate dice roll
int die1, die2;
int total;
die1 = rand()%6+1;
die2 = rand()%6+1;
total=die1+die2;
return total;
}
int main(){
int numberOfRolls;
int remainingRolls;
int eights=0; // declare counter array to hold frequencies of dice results
int i;
int value;
float percentage;
int currentRoll; // declare array for dice values
currentRoll= 0;
cout << "How many times will the dice be rolled?" << endl;
cin >> remainingRolls;// user input # of dice rolls
numberOfRolls = remainingRolls;// variable to hold number of rolls (for output)
for (i=0; remainingRolls >0; remainingRolls--){// loop to count frequency of each value
currentRoll = roller();// activate diceRoll function
if (currentRoll == 8){
eights++;
}
}
percentage = (eights*100/numberOfRolls);
cout << "The dice were rolled " << numberOfRolls << " times." << endl;
cout << "The value 8 came up " << eights << " times or " << percentage << "% of the time." << endl;
getch();
return 0;
}
You can simply eliminate the array. You never access the values in the array outside of the loop, so you can replace it with a local variable.
Create a variable
int currentRollat the start and replace all occurances ofdiceValues[i]with currentRoll.