Consider the following C switch statement: switch (ch) {case\'n\': new_cmd(); ca
ID: 3825023 • Letter: C
Question
Consider the following C switch statement: switch (ch) {case'n': new_cmd(); case 'o': open_cmd(); case 'c': close_cmd(); case 's': save_cmd(); case 'a': save_as_cmd(); case 'g': save_as_web_page_cmd(); case 'h': search_and(); case 'r': versions_cmd(); case 'b': web_page_preview_cmd(); case 'u': page_setup_cmd(); case 'v': print_preview_cmd(); case 'p': print_cmd(); case 'd': send_to cmd(); case 'i': properties_cmd(); (a) How many comparisons would be performed, on average, if linear search were used to implement this switch statement? (Assume that ch always matches one of the case values listed and that each value is equally likely.) A "comparison" involves testing whether the value of ch matches one of the case values. (b) Repeat part (a) using binary search instead of linear search. Assume that a single comparison can test whether ch is less than, equal to, or greater than a particular case value. (c) Would it make sense to use a jump table to implement this switch statement? Why or why not?Explanation / Answer
Answer to Part 1:
If Linear Search is to be used in order to implement Switch Statement then in this particular case there are 14 cases in total. Hence no of comparsons required would be 14. Therefore, in order to convert a switch into liner search with n test cases, n number of comparisons will be required and the complexity of the function will be O(n).
Answer to Part 2:
When we use Binary Search for the switch cases defined in the question then the number of comparisons are reduced as Binary Search does not perform full fledged comparions on all the test cases. Binary Search is applied on sorted group. Hence we will sort the elements first and then the number of comparisons would be (log n).
Binary Search would match the required result with the middle element and the decide whether to test the required result before or after the middle element. Hence, the number of comparisons are reduced to a lot.
Answer to Part 3:
A jump Table is a way that is used to transfer control to some other location. Goto, break and continue are all similar in action. A Switch Statement tells us how to write the jump tables. Hence, yes the jump statement can be used to implement switch statements
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.