



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




CPS 196 Lab 17 Fall 2007
I. Let's look at the computer's random number generator. a) Write a new program that calls the random number generator 100 times:
/introtorand.c/ #include <stdio.h> #include <stdlib.h> /for rand/
int main() { int i; /* Generate 100 random integers*/ for (i=0; i<100; i++) printf("%i ",rand());
return 0; }
Record the first 5 numbers:
b) We would like to be able to keep the numbers created, to use in various ways. For this reason, we will store them in an array. Modify the program to look like this:
/introtorand.c/ #include <stdio.h> #include <stdlib.h> /for rand/ #define size 100
int main() { int r[size],i; /* Generate 100 random integers and store in array. */ for (i=0; i<size; i++) r[i]=rand();
/* Print the results */ for (i=0; i<size; i++) { if (i%5==0) printf("\n"); printf("%7i",r[i]); } printf("\n"); return 0; }
Run the program.
What is the purpose of the lines if (i%5==0) printf("\n");
Are there any negative numbers?
Does 0 ever appear?
Record the first 5 numbers: r[0] r[1] r[2] r[3] r[4]
e) I want to simulate the roll of a die (getting the numbers 1 through 6 with equal frequency). Modify the line you changed above so it will produce numbers in the range from 1 to 6.
r[i]= Run the program with this change.
f) Write a function int roll(); to simulate the roll of a die, returning a random value from 1 to 6. Modify main to call this function and assign the returned value to r[i] for each i.
II. Counting the outcomes. a) Now we want to count how many times each number (1 through 6) appears in our rolls of the die. We don't need to keep all the rolls in an array, just count the outcomes as they are produced. We will use an array, count, to count how many times each number is produced. Modify main :
Record your results : count[0] count[1] count[2] count[3] count[4] count[5] count[6]
Are all six values (not counting the 0) about the same?