-
Trouble with Arrays
I'm not understanding how to count the frequency of an array element so I basically did the long version. From what I understand, I am suppose to make an array of eleven elements to mirror the 11 variables and somehow increment those? How exactly do I print out that frequency of the array elements then?
The code below is the long version that I'm trying to convert to using arrays. This is just a basic program to simulate 1000 trials of 10 flips and seeing how many times it lands on hands during the trials.
Code:
int main(void){
int zero=0, one=0, two=0, three=0, four=0, five=0, six=0, seven=0, eight=0, nine=0, ten=0;
int numheads;
int trialnum = 1000;
int flipnum = 10;
int i, j, k;
int a;
int random;
srand((unsigned)time(NULL));
for(i = 0; i < trialnum; i++){
numheads = 0;
for(j = 0; j < flipnum; j++){
if( (random = rand()) > (RAND_MAX / 2)) numheads++;
}
if(numheads == 0) zero++;
if(numheads == 1) one++;
if(numheads == 2) two++;
if(numheads == 3) three++;
if(numheads == 4) four++;
if(numheads == 5) five++;
if(numheads == 6) six++;
if(numheads == 7) seven++;
if(numheads == 8) eight++;
if(numheads == 9) nine++;
if(numheads == 10) ten++;
}
getchar();
return 0;
}
-
Code:
int array[ ARRAYSIZE ]; /* declare an array with ARRAYSIZE members */
array[ 0 ] = 1; /* set the first array member to 1. arrays start at 0 */
array[ ARRAYSIZE - 1 ] = 5; /* set the last member to 5 */
array[ ARRAYSIZE ] = ERROR; /* this member does not exist and is an error */
Edited: array in the last three lines was incorrectly listed as arraysize
Quzah.
-
Quote:
Originally Posted by
quzah
Code:
int array[ ARRAYSIZE ]; /* declare an array with ARRAYSIZE members */
arraysize[ 0 ] = 1; /* set the first array member to 1. arrays start at 0 */
arraysize[ ARRAYSIZE - 1 ] = 5; /* set the last member to 5 */
arraysize[ ARRAYSIZE ] = ERROR; /* this member does not exist and is an error */
Quzah.
Are you saying I need two arrays? The two 'arraysize' text confuses me.
-
Sorry, replace 'arraysize' in the last three lines with 'array'.
Quzah.
-
Pretty simple, just a little trick:
Code:
int tally[11] = {0,0,0,0,0,0,0,0,0,0,0};
//put in your other code here, now let's tally up
tally[numheads]++;
Say numheads == 3, and this is the first number we're tallying. Now the tally array would look like:
Code:
{0,0,0,1,0,0,0,0,0,0,0}
Remember this kind of trick, because it's used very commonly, including things like:
OneArray[AnotherArray[i]], and etc. Very powerful stuff once you get your head wrapped around the concept.