Title: C Programming Language: Practice 10
1C Programming Language Practice 10
2Overview
- Random Numbers Generator
- rand()
- srand()
- dice
- Array initialization and class exercise
3Rand()
int rand() - returns a pseudo-random integer
between 0 and RAND_MAX (32767).
- include ltstdio.hgt
- include ltstdlib.hgtint main() int
i for (i 0 i lt 5 i)
printf("d\n",rand()) return
0
4Seed Definition
- Observation The results of several runs are
identical. - Explanation The initial seed used by rand() is
identical each time. - The Seed
- Used for the generation of the random numbers.
- Explicitly specified using the srand function.
5srand()
- void srand (unsigned int seed)
- Sets seed as the seed for a new sequence of
pseudo-random integers to be returned by rand(). - The sequences can be repeatable by calling
srand() with the same seed value. - The system time is a good choice as an argument
for srand. It will be different each time the
program is run. Thus, results will also be
different.
6Rand() and Srand()
- unsigned long int next 1
- int rand(void)
- next next1103515245 12345
- return (unsigned int) (next/65536) 32768
-
- void srand (unsigned int seed)
- next seed
Sets the seed for the rand() function
7srand()
- include ltstdio.hgt
- include ltstdlib.hgt
- include lttime.hgtint main() int i
- / Set the seed / srand( time( NULL )
) for (i 0 i lt 5 i) printf("
d\n",rand() return 0
srand(time(NULL)) is the same as int seed seed
time(NULL) srand(seed)
8- include ltstdio.hgt
- include ltstdlib.hgt
- int main ()
- int i
- int d1, d2
- int a13 / uses 2..12 /
- for (i 2 i lt 12 i) /
initialize / - ai 0
-
- for (i 0 i lt 1000 i) / Compute /
- d1 rand() 6 1
- d2 rand() 6 1
- ad1 d2 ad1 d2 1 / Count the
occurrences / -
- for (i 2 i lt 12 i) / Print /
- printf ("2d 3d\n", i, ai)
- return 0
ai counts how many times a pair of dice rolled
i.
rand() 6 produces random numbers in the range 0
to 5, rand() 6 1 produces random numbers in
the range 1 to 6.
9Output of dice with rand() and srand()
dice (with rand)
sdice(with srand)
10- int main()
- double numbers 5 3.1, 4.1, 5.9, 2.6,
5.3 - int arr 100 0
- int a_1 5, 4, 3, 2
- int a_2 4 5, 4, 3, 2
- char str_1 "abcdef"
- char str_2 7 'a', 'b', 'c', 'd', 'e',
'f', 0 - char str_3 7 97, 98, 99, 100, 101,
102, 0 - int array2d 3 2 1, 2 ,
- 3, 4 ,
- 5, 6
- int array3d 3 2 1 0
- return 0
Identical arrays a_1 and a_2
Identical arrays str_1, str_2 and str_3
11Class Exercise
- Write a program that creates a matrix with the
multiplication table and then prints it. - Define a matrix
- int mult_table 10 10
- Fill it with the values of the multiplication
table. - Print each entry in the table.
12Required Output
13Basic Conversions
- Conversion from basis B to basis 10 and vice
versa
- Number of digits
- Digit d of number x in base B
-