CS 1401, Exam #2, Solutions

Date: Thursday, March 1, 2007
Section (9 am or 10:30 am): ____________________________
Name (please type legibly, ideally in block letters): ______________________________________________________________________

On March 1, 1790, the first United States Census was authorized. 100 years later, in 1890, punch cards were invented to help process census data. IBM, the company that produced the first punch cards, is now one of the main computer companies.

1. To estimate the average population of a city, the organizers of the first census decided to take the average of the largest and the smallest population values. Use if-statements to write down a code that, given three numbers p1, p2, and p3 describing the population of three different cities, computes and prints the average of the largest and the smallest values.

Hint: You do not need to read anything from the keyboard or from a file, just compute and print. Assume that p1, p2, and p3 have been assigned some values already.

```
Solution:

int average;
if ((p1 <= p2 && p2 <= p3) || (p3 <= p2 && p2 <= p1))
average = (p1 + p3)/2;
else if ((p1 <= p3 && p3 <= p2) || (p2 <= p3 && p3 <= p1))
average = (p1 + p2)/2;
else
average = (p2 + p3)/2;
System.out.println(average);

```
2. To promote the census, the census organizers decided to send to each citizen a nice leaflet in which this citizen's data is listed first, and his neighbor's data is listed second. Write down a code that, given two strings s1 and s2 and the name of the citizen (stored in the string name), finds the string which contains this name and places it first. Assume that the names are always spelled in a normal way: first letter capitalized, all other letters small.

Example: if s1 is "Xiaojing Wang", s2 is "Carlos Acosta", and name is "Acosta", then after your code, s1 should contain "Carlos Acosta" and s2 should contain "Xiaojing Wang".

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 the name is spelled in all caps.

```
Solution:

if (s2.indexOf(name) >= 0)
{String temp = s1;
s1 = s2;
s2 = temp;
}

Tracing:

originally

--------    -------   -------   ---------------    ----------------
|  22    |  |   33  | |   44  | | Xiaojing Wang |  |  Carlos Acosta |
--------    -------   -------   ---------------    ----------------
s1           s2       name        22                 33

--------
| Acosta |
--------
44

after the line String temp = s1:

--------    -------   -------   ---------------    ----------------
|  22    |  |   33  | |   44  | | Xiaojing Wang |  |  Carlos Acosta |
--------    -------   -------   ---------------    ----------------
s1           s2       name        22                 33

--------    -------
| Acosta |  |  22   |
--------    -------
44         temp

after the line s1 = s2:

--------    -------   -------   ---------------    ----------------
|  33    |  |   33  | |   44  | | Xiaojing Wang |  |  Carlos Acosta |
--------    -------   -------   ---------------    ----------------
s1           s2       name        22                 33

--------    -------
| Acosta |  |  22   |
--------    -------
44         temp

after the line s2 = temp:

--------    -------   -------   ---------------    ----------------
|  33    |  |   22  | |   44  | | Xiaojing Wang |  |  Carlos Acosta |
--------    -------   -------   ---------------    ----------------
s1           s2       name        22                 33

--------    -------
| Acosta |  |  22   |
--------    -------
44         temp

Extra credit:

if (s2.toLowerCase().indexOf(name.toLowerCase()) >= 0)
{String temp = s1;
s1 = s2;
s2 = temp;
}

```
3. A person is eligible for a census either if he or she is a US citizen or if this person is not a US citizen and resides in the US. Let us assume that a Boolean variable citizen is true or false depending on whether a person is a US citizen, and a Boolean variable resides is true or false depending on whether the person resides in the US. Describe a Java expression for being eligible for a US census. Draw the truth tables for "and", "or", and "not" operations. Use these truth tables to find the truth value of your expression for X. Wang who resides in the US but who is not a US citizen. Explain precedence of different logical operations, and how this precedence is related to precedence of different arithmetic operations.

```
Solution:

citizen || (!citizen && resides)

------------------------------------
| A |  B | A and B | A or B | not A |
------------------------------------
| F |  F |    F    |   F    |   T   |
------------------------------------
| F |  T |    F    |   T    |   T   |
------------------------------------
| T |  F |    F    |   T    |   F   |
------------------------------------
| T |  T |    T    |   T    |   F   |
------------------------------------

citizen is False, resides is True, so the above expression becomes
F || (!F && T). According to the truth table, !F is T, so !F && T is
T && T, i.e., T. Thus, the formula is F || T, i.e., True.

Precedence: negation ! has the highest precedence, then &&, then ||.

Inside the computer, True is 1, False is 0, so && is actually
multiplication. Or is almost addition, and precedence for && and ||
is the same as for multiplication and addition.

```
4. Suppose that the results of the census are stored in the file census.dat. Use the while loop to find and print the line that contains your name. Trace your code on the example of a file in which the first line is "Carlos Acosta" and the second is the line about you.

Reminder: to create an object for reading from a file, you need to use the following code:

```Scanner fromFile = new Scanner(new FileReader("census.dat"));

Solution:

If your name is Julio Urenda, a solution will look like this:

Scanner fromFile = new Scanner(new FileReader("census.dat"));
Boolean found = false;
String line;
while(!found && fromFile.hasNext()){
line = fromFile.next():
if (line.indexOf("Urenda") >=0){
System.out.println(line);
found = true;
}
}

At first, "found" is false. Since !found is true and there is something
in the file (i.e., fromFile.hasNext() is true), we go into the file
and read the first line of the file into the variable "line".

The value of "line" is now the first line of the file, i.e.,
"Carlos Acosta". This string does not contain a substring "Urenda", so
line.indexOf("Urenda") is -1. The condition line.indexOf("Urenda") >=0
is not satisfied, so we do not do anything on this iteration and
continue looping.

The value of found is still false, there is still something in the file,
so we read the next line "Julio Urenda" into the variable "line". This
time, the string contains a substring "Urenda", and the value of
line.indexOf("Urenda") is 6. The condition line.indexOf("Urenda") >=0
is satisfied, so we print the string "Julio Udenda" and change the
value of the variable "found" to "true".

On the next iteration, !found is false, so the condition for continuing
is false, so we get out of the loop.

```
5. To process census data in a computer, we must convert it into the binary code. 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 28 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.

```