Docsity

Notes for Introduction to Computer Programming - Lab 17 | CPS 196, Lab Reports of Computer Science

Partial preview of the text

Download Notes for Introduction to Computer Programming - Lab 17 | CPS 196 and more Lab Reports Computer Science in PDF only on Docsity!

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 :

  • so that r is an int but not an array (we will repeatedly assign r a random value from 1 to 6 (using roll))
  • set up an array count[7]. Initialize it to all 0's with a loop.
  • Write a loop so 1000 random numbers are generated whose value is from 1 to 6. For each random number r, add one to count[r] to count how many times r is rolled. Since we cannot roll a 0, count[0] should remain 0.
  • Print the count array at the end of the program.

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?