/* * SelfTest2.txt * Chapter 9 * By John Stile */ 1. Write a program that generates a random number between 10 and 30 inclusively using modulus operator. ANSWER: see SelfTest2.question1.c 2. Rewrite the following code fragment using the if...else structure. ORIGINIAL: NEW USING IF...ELSE int main(void) int main(void) { { int n; int n; do if ( (n=getnum()) >10 ) { { n=getnum(); again(); } } while (n>10 ? again(): ok() ); else { return 0; ok(); } } return 0; } 3. Explain how the following code fragment works: CODE FRAGMENT: EXPLAIN: sran(time(NULL)); // call time function, // which returns curren seconds since epoc // as an int, and call srand using int as the seed num = rand() % MAX; // call srand which returns a psudo random number // as an int. divide number by MAX and return the // remainder. // assign the remainder to num. // Effectvely generates a number between 0 and MAX 4. How many time will the following loop? for(aa=0; aa<=30; aa+=4) // initialize aa to zero // if aa <= 30, do block // increment aa, // if aa<= 30, do block ANSWER: 30/4=8. 8 times. 0 4 8 12 16 20 24 28 5. Explain how the following works: CODE FRAGMENT: EXPLAIN: if (((aa<=100) || (bb>=300)) && (year==12)) // quest for truth // outer most () are for the if // second set are &&, if first fails, second not checked // thrid set are ||, if first succed, second not checked // if aa<=100, third set = TRUTH // if not, if bb>=300, thrid set = TRUTH // if thrid set = TRUTH, if year==12, second set = TRUTH // if third set = TRUTH, if not year==12, second set = FALSE // if thrid set = FALSE, second set = FALSE // if second set = FALSE, first set = FALSE // if second set = TRUTH, first set = TRUTH 6. Write a program named whatnum.c that reads a positive igetger from the keyboard and then determines if it is a prime number. Have the program also print out the number of factors. Use a for loop and modulus operator. The input and output should have the following format: Enter a positive integer: 12 12 has 5 factors including 1. Enter a positive integer: 13 13 is a prime number. ANSWER: see SelfTest2.question6.c