I wrote a small dice rolling program that will print out the results of however many dice rolls that are entered. I want to count how much each number occurs so I thought I would put the output from the rand() function into an array and then search the array for the different values. I don't know how to put numbers into an array that are not entered in manually.
#include <stdio.H>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int count;
int roll;
srand(time(NULL));
printf("How many dice are being rolled?\n");
scanf("%d", &count);
printf("\nDice Rolls\n");
for (roll = 0; roll < count; roll++)
{
printf("%d\n", rand() % 6 + 1);
}
return 0;
}
3 Answers 3
#include <stdio.H>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int count;
int roll;
int* history;
srand(time(NULL));
printf("How many dice are being rolled?\n");
scanf("%d", &count);
history = malloc( sizeof(int) * count );
if( !history )
{
printf( "cannot handle that many dice!\n" );
exit( -1 );
}
printf("\nDice Rolls\n");
for (roll = 0; roll < count; roll++)
{
history[roll] = rand() % 6 + 1;
printf("%d\n", history[roll]);
}
// do something interesting with the history here
free( history );
return 0;
}
2 Comments
scanf too.just put it into the array
for (roll = 0; roll < count; roll++)
{
myArray[roll] = rand() % 6 + 1;
printf("%d\n", myArray[roll] );
}
1 Comment
If you want to track the number of occurences of each result, you don't even need to save every dice roll.
int result[6] = {} ; // Initialize array of 6 int elements
int current = 0; // holds current random number
for (roll = 0; roll < count
{
current = rand() % 6;
result[current]++; // adds one to result[n] of the current random number
printf("%d\n", current+1);
}
After which you will have an array 0-5 (result), with each element containing the number of each occurence (you will need to add the element number + 1 to get the actual roll). ie. result[0] is the number of occurences of '1'.
<stdio.H>. I think you meant<stdio.h>. Which book are you reading?