## CS 1401, Exam #2

Date: Friday, October 6, 2006, 11:30 am
Name (please type legibly, ideally in block letters): ______________________________________________________________________

1. Use if-statements to write down a code that, given three numbers n1, n2, and n3, finds the smallest of these three numbers, and assigns this value to the variable whose name is smallest.

Hint: you do not need to read anything from the keyboard or from a file, you do not need to print anything to the screen or place it into a file, just compute and assign. Assume that n1, n2, and n3 have been assigned some values already, which are the numbers that you are comparing.

```

```
2. Write down a code that, given two strings s1 and s2, sorts them in inverse alphabetic order: i.e., if s1 precedes s2 in alphabetic order, your code should swap the strings. You can assume that both s1 and s2 only contain small letters.

Example: if s1 is "air" and s2 is "water", then after your code, s1 should contain "water" and s2 should contain "air". Trace your code, step by step, on this example: draw all the boxes and show how their values change after each operation.

For extra credit: make the code work also if some of the letters are capital letters.

```

```
3. Draw the truth tables for "and", "or", and "not" operations. Use these truth tables to find the truth value of the statement 3 < 5 || 2 < 4 && 4 < 2. Explain precedence of different logical operations, and how this precedence is related to precedence of different arithmetic operations.

For extra credit: what is the difference between || and |? What is the advantage of each of these operations? Give an example when they lead to different results.

```

```
4. Use the while loop to write a piece of code that, given an integer n, finds the smallest square k^2 for which k^2 >= n. In other words, your code should find the smallest square which is larger than a given integer n. For example, for n = 7, we should return 9, because 3^2 = 9 > 7, and 9 is the smallest such square: 2^2 = 4 < 7.

Idea: start with k = 0, and while the condition k^2 >= n is not satisfied, keep increasing k by 1. Trace your code step-by-step for n = 7.

For extra credit: what is the advantage of using k++ instead of k = k+1?

```

```
5. To convert a decimal integer n to binary form, you repeatedly divide n by 2 and keep the remainder until you get 0. Reading the remainders from bottom to top provides the desired binary number. Use this algorithm to convert 19 to binary code. Check the result by converting the binary number back into the decimal code.

Reminder: 137 in decimal code means 1 * 10^2 + 3 * 10^1 + 7 * 10^0. Similarly, 101 in binary code means 1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 1*4 + 0*2 + 1*1 = 4 + 1 = 5.