Solution

advertisement
CmSc150 Fundamentals of Computing I
Homework 02 Solution
1. Write down the algorithm for computing the square of the distance between two
points (X1,Y1) and (X2, Y2)
a. using pseudocode
b. using flowchart
Input of the algorithm: The coordinates of the points are entered by the user into
memory locations X1, Y1, X2, Y2.
Output of the algorithm: print the contents of memory location D, containing the
squared distance between the points.
Use the operations read, print,  (assignment), and the arithmetic operations
subtraction, addition and multiplication
Pseudocode
1. read X1
2. read Y2
3. read X2
4. read Y2
5. D  (X1 – X2)*(X1 – X2) + (Y1-Y2)*(Y1-Y2)
6. print D
Flowchart: on next page
1
START
Read X1
Read Y1
Read X2
Read Y2
D  (X1 – X2)*(X1 – X2) + (Y1-Y2)*(Y1-Y2)
Print D
END
2. Write down an algorithm to determine whether two points (X1,Y1) and (X2,Y2)
lie on the same side of the x-axis.
a. using pseudocode
b. using flowchart
2
If at least one of the points lies on the x-axis, you may consider them to be on the
same side.
Input of the algorithm: memory locations X1, Y1, X2, Y2 containing the coordinates
of the points.
Output of the algorithm: an appropriate message.
Pseudocode
1. If Y1 > 0
1.1. if Y2  0 print “Points lie on the same side”
1.2. otherwise print “Points lie on different sides”
2. otherwise
2.1. If Y1 < 0
2.1.1. if Y2  0 print “Points lie on the same side”
2.1.2. otherwise print “Points lie on the different sides”
2.2. otherwise print “Points lie on the same side”
Flowchart: see next page
3
START
NO
YES
Y1 > 0
NO
NO
Y1< 0
Y2  0
YES
YES
YES
Y2 0
1
NO
1
Print “same
side
Print
“different
side
END
Second solution:
1. if Y1 * Y2  0 print “same side”
2. otherwise print “different sides”
4
Multiple choice:
1. A Java program is best classified as
a. hardware
b. software
c.
d.
e.
storage
processor
input
2. When executing a program, the processor reads each program instruction from
a. secondary memory (storage)
b. the Internet
c. registers stored in the processor
d. main memory
e.
could be any of these
3. Binary numbers are composed entirely of
a. 0s
b. 1s
c. 0s and 1s
d.
e.
0s, 1s and 2s
any digits between 0 and 9
4. Java is an example of a(n)
a. machine language
b. assembly language
c. high-level language
d.
all of the above
5
Download