Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Objective: To gain insight into the performance differences when a series of if-

ID: 3576698 • Letter: O

Question

Objective: To gain insight into the performance differences when a series of if-then-else tests are converted into a switch - case configuration. The specific assignment is to compare the execution times of two routines that perform the same task, but implement the decision processes differently. Assignment: Write a main program which generates a source array which is populated with random numbers in the range of 0 to 999. Write your program so that the size of the array can be changed easily or specified on the command line. Specific requirements are: Use rand() to generate a sequence of random integers. Use the modulus function to limit the original numbers to a range of 0 to 999. Count the number of values which fall in the range of 0 - 199, 200 - 399, 400 - 599, 600 - 799, 800 - 999 using both a switch statement and a sequence of if-then-else statements. Measure how much time it takes to generate a count for all of the numbers with both approaches, and compare the two approaches' execution times. For the case statement, I suggest that you convert the number to an integer form that lends itself to the switch statement. You may use something like: int index = number/200. This will work because the number is an integer and the fractional part of the result is discarded - this is good practice to see the effects of different ways that numbers are represented.

Explanation / Answer

#include /* printf, scanf, puts, NULL */ #include /* srand, rand */ #include /* time */ int main () { int iSecret, iGuess; /* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ iSecret = rand() % 10 + 1; do { printf ("Guess the number (1 to 10): "); scanf ("%d",&iGuess); if (iSecretiGuess) puts ("The secret number is higher"); } while (iSecret!=iGuess); puts ("Congratulations!"); return 0; }