90 likes | 104 Vues
Learn how to generate random numbers and convert between decimal and binary representations in C programming. This lecture covers the use of rand() function, setting the seed for random number generation, and the decimal and binary number systems. Practice exercises included.
E N D
Lecture-5 Miscellaneous
Random Numbers • Can use ‘rand()’ function declared in the stdlib.h header file • The seed for random number generation can be set using srand() • A good seed can be the ‘time()’ function defined in time.h header file Follow this link to test_ran.c
In-class Exercise 6-1 • Write a program to guess a number • Generate a random number from 1 to 10 using: 1 + rand() % 10 • Prompt the user to enter a number(from 1 to 10), find out of the number is equal to, less than, or greater than the random number • Keep prompting user till he enters a negative value.
Decimal Number System • Numbers with the base value of 10 • Digits used: {0, 1, 2,…, 9} • 1362: 1*103 + 3*102 + 6*101 + 2*100 • In general, any number with ‘n’ number of digits can be represented as: dn.10n+dn-1.10n-1+….d0.100
Binary Numbers • Numbers represented with base value of 2 • Only two digits used: {0, 1} • Binary digits are frequently called “bits”, and can be visualized as an “on-off” operation for a electronic switch • 1011: 1.23 + 0.22 + 1.21 + 1.20 1011: 8 + 0 + 2 + 1 = 11(decimal)
Bit Operations • C has bit operators with operate on integers as bit patterns • Each bit from each integer is acted upon separately • The answer is presented in integer format Follow this link to bit_opr.c
Operator table Complement Operator(!): Inverts value Thus: !1 = 0, and !0 = 1
Shift operators • Shift operators can shift bits of a variable either left or right • Shifting bits to left is equivalent to multiplying by 2 • Shifting bits to right is equivalent to dividing by 2 Follow this link to bit_shift.c
In-class Exercise 6-2 • Write a program to print out the multiplication table of 2 • Use bit-shift operators for each number to multiply the number by two, and then display it. • Use the range of number from 1 to 10