part I due by 10 p.m. on Monday, June 29, 2026
part II due by 10 p.m. on Tuesday, June 30, 2026
In your work on this assignment, make sure to abide by the policies on academic conduct.
If you have questions while working on this assignment, please come to
office hours, post them on Ed Discussion, or email
cscis111-staff@lists.fas.harvard.edu
45 points total
If you haven’t already created a folder named s111 for your
work in this course, follow these
instructions to do so.
Then create a subfolder called ps2 within your s111 folder,
and put all of the files for this assignment in that folder.
The problems from Part I will all be completed in a single PDF file. To create it, you should do the following:
Access the template that we have created by clicking on this link and signing into your Google account as needed.
When asked, click on the Make a copy button, which will save a copy of the template file to your Google Drive.
Select File->Rename, and change the name of the file to
ps2_partI.
Add your work for the problems from Part I to this file.
Once you have completed all of these problems, choose
File->Download->PDF document, and save the PDF file on your
machine. The resulting PDF file (ps2_partI.pdf) is the one that
you will submit. See the submission guidelines at the end of Part I.
6 points total; 0.75 points each part; individual-only
Assume that the following variable declarations have already been executed:
int x = 21; int y = 4; double z = 4; double n = 14.0;
Given the statements above, determine the value of each of the following expressions. Make sure that your answers clearly indicate the type of each value. In particular, floating-point values should have a decimal and strings should be surrounded by double quotes.
x / y x / zx + y "x" + "y"(int)(n / y * y) (int)n / y * y11 + 1 + " CS "" CS " + 11 + 17 points total; individual-only
Assume that num and val are variables of type int that have
already been declared and assigned initial values.
In this problem, you will write assignment statements using num
and val. These statements must use the standard assignment
operator (=). They should not use shortcut assignment operators
like +=.
(1 point) Write a single assignment statement that assigns to
num the value that is 10 more than the value of val.
(1 point) Write a single assignment statement that triples the
value of val.
(1 point) Assume that num is a three-digit number (i.e., a
number between 100 and 999). Write a single assignment statement
that assigns to val the 100’s digit of the value of num. For
example, if num has a value of 711, your assignment statement
should end up assigning a value of 7 to val. Your statement
must use a single arithmetic operator, and it should work for an
arbitrary, three-digit value of num.
(2 points) If num may have more than three digits, we have to
use a different approach when determining its 100’s digit. Write
a single assignment statement that assigns to val the 100’s
digit of the value of num for any value of num, regardless
of how many digits it has. For example, if num has a value of
12345, your assignment statement should end up assigning a value
of 3 to val; if num has a value of 15, your statement should
end up assigning a value of 0. (Hint: the right-hand side of
the assignment statement should be an expression that uses two
mathematical operators.)
(2 points) What are the values of num and val after the
following assignment statements have been executed?
num = 10; val = 3; num = num - 5; val = val + num; num = num % 2;
6 points total; 3 points each part; individual-only
Convert each of the following binary numbers into its equivalent decimal number. Show your work.
Convert each of the following decimal numbers into its equivalent binary number. Show your work.
6 points total; 3 points each part; individual-only
In ps2_partI, we have included the following partial code
fragment:
for (____________; ____________; ____________) { System.out.println("Go Crimson!"); }
Fill in the blanks to create a loop that repeats the message “Go Crimson!” 5 times. Use one of of the two templates for simple repetition that we discussed in lecture.
Consider the following code fragment:
for (int i = 5; i < 0; i++) {
System.out.println(i);
}
This code is supposed to print the integers from 5 down to 1 on a single line, as follows (there is a space after every number, including the last one):
5 4 3 2 1
However, it currently fails to do so.
We have included the original code fragment in ps2_partI. Make
whatever changes are needed to obtain the correct output. The
corrected version should still consist of a three-line for
loop — i.e., you should not add any lines.
for loops6 points total; 3 points each part; individual-only
Consider the following code fragment:
for (int i = 2; i <= 6; i += 2) {
for (int j = 2; j < i; j++) {
System.out.println(i + j);
}
}
In section 5-1 of ps2_partI, we have provided a table that you
should use to trace through the execution of these loops. We have
given you the first two rows; complete the table with your trace
of the remaining iterations of the loops. You may not need all of
the rows.
Consider the following code fragment:
for (int i = 1; i <= 4; i++) { System.out.println("** " + i + " **"); for (int j = 3; j >= 0; j++) { System.out.println(i + " " + j); } }
Modify this fragment to make it produce the following output:
** 1 ** 1 3 1 2 1 1 ** 2 ** 2 3 2 2 ** 3 ** 3 3
We have included the original code fragment in ps2_partI.
Make whatever changes are needed to obtain the correct output. The
corrected version should still consist of six lines, with one
three-line for loop nested in another for loop.
for loops to produce a pattern8 points total; individual-only
Consider the following pattern:
::::::::::= :::::::=== ::::===== :=======
(2 points) To deduce the formulas needed for this pattern, begin
by completing the table provided in ps2_partI. We have given you
the first row. Complete the remaining rows using the same approach
that we took in the DrawTorch case study in the lecture notes.
(3 points) Use the table to determine formulas for:
line in your formula.line in your formula.(3 points) Write a Java code fragment that uses nested for
loops to produce the pattern. For full credit, each
print/println statement should print at most one character.
You do not need to create a program for this problem. Simply
include the code fragment in your text file.
6 points total; 1 pt. each part; individual-only
Consider the following program, which includes a number of incomplete println statements:
public class ScopePuzzle { public static void myMethod() { int i; for (i = 0; i < 10; i++) { System.out.println(________); // first println int a = 5; for (int j = 0; j < 3; j++) { int b = 0; System.out.println(________); // second println } System.out.println(________); // third println } int y = 3; System.out.println(________); // fourth println } public static void main(String[] args) { int c = 0; System.out.println(________); // fifth println int d = 1; myMethod(); System.out.println(________); // sixth println } }
The program includes a number of int variables: a,b,c,d,
i, j, and y. Given the rules that we have learned about
variable scope:
Submit your ps2_partI.pdf file by taking the following steps:
Login to Gradescope by clicking the link in the left-hand navigation bar.
Click on the box for CSCI S-111.
If you still need to create a PDF file, open your file on Google Drive, choose File->Download->PDF document, and save the PDF file on your machine.
Click on the name of the assignment in the list of assignments on Gradescope. You should see a pop-up window labeled Submit Assignment. (If you don’t see it, click the Submit or Resubmit button at the bottom of the page.)
Choose the Submit PDF option, and then click the Select PDF button and find the PDF file that you created. Then click the Upload PDF button.
You should see a question outline along with thumbnails of the pages from your uploaded PDF. For each question in the outline:
As you do so, click on the magnifying glass icon for each page and doublecheck that the pages that you see contain the work that you want us to grade.
Once you have assigned pages to all of the problems in the question outline, click the Submit button in the lower-right corner of the window. You should see a box saying that your submission was successful.
Important
It is your responsibility to ensure that the correct version of every file is on Gradescope before the final deadline. We will not accept any file after the submission window for a given assignment has closed, so please check your submissions carefully using the steps outlined above.
If you are unable to access Gradescope and there is enough
time to do so, wait an hour or two and then try again. If you
are unable to submit and it is close to the deadline, email
your homework before the deadline to
cscis111-staff@lists.fas.harvard.edu
55-65 points total
12 points; pair-optional
Important
Remember that some of the points for Part II will be based on your use of good programming style. Use appropriate indentation, select descriptive variable names, insert blank lines between logical parts of your program, and add comments as necessary to explain what your code does. See the coding conventions for more detail.
Imagine that you have been asked to write a program that computes the cost of a trip taken in an automobile.
Getting started
If you haven’t already done so, create a folder named ps2
for your work on this assignment. You can find instructions for
doing so here.
Download the following file: TripCalculator.java
Make sure to put the file in your ps2 folder. If your browser
doesn’t allow you to specify where the file should be saved, try
right-clicking on the link above and choosing Save as... or Save
link as..., which should produce a dialog box that allows you to
choose the correct folder for the file.
In VSCodium, select the File->Open Folder or File->Open menu option, and use the resulting dialog box to find and open the folder that you created in step 1. (Note: You must open the folder; it is not sufficient to simply open the file.)
The name of the folder should appear in the Explorer pane on
the left-hand side of the VSCodium window, along with the name of the
TripCalculator.java file that you downloaded in step 2.
Click on the name TripCalculator.java, which will open an editor
window for that file. You will see that we’ve given you the
beginnings of the program. Make sure to complete the comments at the
top of that file.
Completing the program
Start by reading over the starter code that we’ve given you. Make sure that you understand it. You will see that it does the following:
gasPriceepaRatingdistance.You do not need to understand how the program obtains the values
of these variables. You simply need to complete the program so that
it uses the values of the variables gasPrice, epaRating, and
distance to compute the cost of the trip in dollars using the
following formula:
gasPrice distance
cost = -------- * ---------
100 epaRating
For example, if gas costs 300 cents per gallon, the car’s EPA rating is 25 miles per gallon, and the trip is 200 miles, the program should begin by performing the computation
300 200
--- * --- = 24
100 25
Format of the result
Based on the value of the cost, your program will need to decide at
runtime which format to use when printing the result.
If the cost is an integer (i.e., a whole number of dollars, with no additional cents), then the cost should be printed without a decimal. For example, given the values in the above example, the program should print the following:
The cost of the trip is: $24
If the cost is not a whole number of dollars, then the cost
should be printed in the form $d.cc, where d is the number of
dollars, and cc is the number of cents rounded to two places
after the decimal. For example, if gas costs 300 cents, the
car’s EPA rating is 20 miles per gallon, and the trip is 210
miles, the program should print the following:
The cost of the trip is: $31.50
To print the cost with two places after the decimal, we
encourage you to use the System.out.printf command
mentioned near the end of the notes on primitive data. Here is a sample
printf statement that you can adapt:
System.out.printf("The price is: $%.2f\n", p);
Note that the string portion of this printf command
includes some preliminary text ("The price is: $"),
followed by a format string ("%.2f") that specifies that we
want to print a floating-point value to 2 place after the
decimal, followed by a newline character ("\n") so that
Java will go down to the next line after printing. You should
be able to make minor changes to this command so that it uses
the correct preliminary text and the correct variable name
for your program.
Use an if-else statement to determine which format to use for the
cost. See our
ChangeAdder4.java
program for an example of using this type of construct. There is
more than one way to test if the computed cost is a whole number.
You may want to consider using a type cast in some way.
Implementation guidelines:
main
method, putting it below the code that we have given you.You should not perform any mathematical operations in the context of a println statement. Instead, you should assign the result of a mathematical computation to a variable and then use the variable in the println statement.
For example, let’s say that you wanted to print the product of
the values in the int variables d and e. Instead of doing
this:
System.out.println("The product is: " + (d * e)); // not allowed in this assignment
you would instead do something like this:
int product = d * e; System.out.println("The product is: " + product);
Taking this approach will give you practice with declaring your own variables. Using variables in this way can also make your code more readable, provided that you use descriptive names for the variables.
We recommend that you test your code frequently, rather than waiting until after the entire program is written. After you add each new piece of functionality, check for compiler errors, perform other testing, and debug as needed before proceeding with the rest of the program.
//) at the start of the each of the problematic
lines. If you are unsure about how to get your program to
compile, feel free to ask us for help.Compiling and running your code
Begin by opening VSCodium’s built-in Terminal pane. You can do this by pressing the Control key and the backtick key, or by selecting Terminal->New Terminal from the menu.
The Terminal should open at the bottom of the VSCodium window. If
you created and opened the ps2 folder using the instructions at
the start of Part II, the Terminal should already be in the ps2
folder.
To compile your program:
Save any changes that you made to the file by using Ctrl-S or selecting File->Save.
Type the following command in the Terminal and then press Enter:
javac TripCalculator.java
Doing so word will produce a list of any syntax errors in your code.
Edit the code as needed and recompile. Important: Make sure to save any changes that you make before you try to recompile!
Repeat the steps above until javac does not report any
errors. (Note: Pressing the Up Arrow key in the Terminal
should bring you back through your recent commands, so
you shouldn’t need to retype them!)
To run your program:
Once all of the syntax errors have been fixed, enter the following command from the Terminal:
java TripCalculator
Make sure that the program produces the expected results, and edit your code as needed.
13 points; pair-optional
You need to use a ladder to reach a certain point on the outside of your house. To avoid adjusting the ladder once it’s in the air, you want to precompute the required length of the ladder.
Getting started
Download the following file: LadderHelper.java
Make sure to put the file in your ps2 folder. If your browser
doesn’t allow you to specify where the file should be saved, try
right-clicking on the link above and choosing Save as... or Save
link as..., which should produce a dialog box that allows you to
choose the correct folder for the file.
As needed, open your ps2 folder using the File->Open Folder
or File->Open menu option in VSCodium.
The name of the folder should appear in the Explorer pane on the left-hand side of the VSCodium window, along with the name of the file that you downloaded in step 1.
Click on the name LadderHelper.java, which will open an editor
window for that file. You will see that we’ve given you the
beginnings of the program.
Completing the program
Start by reading over the starter code that we’ve given you. Make sure that you understand it. You will see that it does the following:
heightangle.Given these values, the required length of the ladder can be computed as follows:
height
length = ---------------
Math.sin(angle)
Important: Java’s Math.sin function expects the angle to be
given in radians. Therefore, you will need to take the angle that
the user inputs and convert it from degrees to radians by dividing
by 180 and multiplying by π. (In Java, you can use the expression
Math.PI for π.)
You should add the code needed to compute and report the length of the ladder in three forms:
For example, if the height is 20 feet and the angle is 60, the output would look something like this:
The required length is:
23.094010767585033 feet
7.698003589195011 yards
7 yards and 2.094010767585033 feet
The implementation guidelines from the previous problem also apply to this one.
30 points; individual-only
This problem is based closely on a similar problem by Stuart Reges and Marty Stepp.
Your task is to write two programs that print the following drawing of a tower from Boston’s Zakim Bridge:
/|\ //|\\ |:|:| |:|:| ----- |:|:| |:|:| ----- |:|:| |:|:| /-----\ /{{{|}}}\ /{{{{|}}}}\ /{{{{{|}}}}}\ /{{{/ \}}}\ /{{{/ \}}}\ /{{{/\ /\}}}\ /{{{/ \ / \}}}\ /{{{/ \ / \}}}\ /{{{/ \ / \}}}\ /{{{/ | \}}}\ /{{{/ | \}}}\ /{{{/ | \}}}\ /{{{/ | \}}}\ ==== = ====
(The Y shape in the middle of the triangular opening represents cables that run down to the median strip between the two directions of traffic, as shown here. You’re also welcome to think of the figure as something else, like the Eiffel Tower!)
First version
The first version of your program should reproduce the drawing
shown above without using a class constant for a scale factor.
This initial version of your program will be similar to the initial
DrawTorch program from lecture.
Your program should use for loops (including nested loops where
appropriate) to print the drawing. Break the drawing into
components – groups of lines that follow the same pattern – and
write a separate method for each component. Use pseudocode and
tables to figure out the patterns in the output. Test each method
before moving on to the next one. The case study from lecture
(notes,
examples)
is a good example of this approach to drawing a complex
figure.
In addition, you should follow these guidelines:
BridgeDrawing.
After opening your ps2 folder in VSCodium, select File->New Text
File, which will open up an empty editor window. Then select
File->Save, and give the new file the name BridgeDrawing.java'\\' only
counts as a single character.printChars method from the
lecture notes on methods with
parameters, although doing
so is not required. If you choose to use it, you should copy the
method into your class and call it from your other methods.
However, to ensure that you get at least some explicit practice
with nested loops, at least one of the components of your figure must
be printed without using the printChars method. (For
example, if we were applying this guideline to our DrawTorch
case study, we might use explicit nested loops for the flame,
and calls to printChars for the other components of the
figure.)Second version
To create the second version of your program, you should modify
your first version so that it uses a scale factor, just as we
modified DrawTorch to
create DrawTorch2.
To begin, make sure that the first version of your program is fully
saved. Then use the File->Save As menu option in VSCodium to save a
copy of your first version so that you can use it as a starting
point for your second version. Give the new file the name
BridgeDrawing2.java, and change the name of the class in this file to
BridgeDrawing2.
Once you have created the file for your second version, you should add a class constant to represent the scale factor – the integer value that is used to determine the dimensions of the various components of the figure. The figure below shows how a scale factor value of 2 can be used to determine the dimensions of some of the components of the drawing at its original size.

Make whatever changes are needed to fully incorporate the scale factor into your program. On any given execution, your program will produce just one version of the drawing. However, you should refer to the class constant throughout your code, so that by simply changing your constant’s value and recompiling, your program will produce a proportional drawing of a different size. Your program should work for any value of the constant greater than or equal to 1. Here are some examples of what the figure should look like for different values of the constant:
To determine how the scale factor should be incorporated into your
existing code, it can be helpful to compare two or more sizes of the
figure and to use tables to determine how the various numbers in the
for loops depend on the value of the scale factor. See the case
study from lecture for
examples of this process.
Note
The figure includes components that always have a height or width of 1, regardless of the value of the constant. For example, there is a vertical line of width 1 that goes through the center of the figure. The example outputs given above should help you to determine where the rest of these fixed-dimension components are found.
Guidelines 2-6 from the first version also apply to the second version.
10 points; individual-only; required of grad-credit students; may be completed by other students for partial extra credit
Java’s Math library includes a method for
calculating the square root of a number. If this method weren’t
available, how would we compute a square root?
One option is to use the algorithm devised by Newton, which computes a series of estimates that get closer and closer to the actual square root. Newton’s algorithm begins with some initial estimate of the square root, and it repeatedly generates a closer estimate by performing a simple computation. If x is the number whose square root we are calculating and estimate is the current estimate of the square root, Newton’s algorithm uses

as its next estimate. It repeats this computation multiple times, and each time it gets a more accurate estimate of the square root.
Your task is to write a program that uses Newton’s algorithm to estimate the square root of a positive integer.
Getting started
Download the following file: RootCompute.java
Make sure to put the file in your ps2 folder. If your browser
doesn’t allow you to specify where the file should be saved, try
right-clicking on the link above and choosing Save as... or Save
link as..., which should produce a dialog box that allows you to
choose the correct folder for the file.
As needed, open your ps2 folder using the File->Open Folder
or File->Open menu option in VSCodium.
The name of the folder should appear in the Explorer pane on the left-hand side of the VSCodium window, along with the name of the file that you downloaded in step 1.
Click on the name RootCompute.java, which will open an editor
window for that file. You will see that we’ve given you the
beginnings of the program.
Completing the program
The starter code that we have given you obtains two values from the user:
Here again, you do not need to understand how the program obtains the values of these variables. You simply need to complete the program so that it uses these variables to estimate the square root.
Your code should use x/2 as the original estimate, and it should
improve the estimate n times by repeatedly applying the formula
above. The program should output all of the estimates that it
computes, including the original estimate. Use a for loop to
perform the necessary repetitions.
Here is a sample run of the program, with user inputs of 20 and 5:
input a positive integer: 20 number of times to improve the estimate: 5 estimates of the square root of 20: 10.0 6.0 4.666666666666667 4.476190476190476 4.472137791286727 4.472135954999956
Note that we end up with six estimates: the original one (x/2), and the five improvements that the user requested.
The implementation guidelines from problem 8 also apply to this one.
You should submit the following files:
TripCalculator.javaLadderHelper.javaBridgeDrawing.javaBridgeDrawing2.javaRootCompute.java (if completed)Here are the steps:
Login to Gradescope by clicking the link in the left-hand navigation bar.
Click on the box for CSCI S-111.
Click on the name of the assignment in the list of assignments. You should see a pop-up window with a box labeled DRAG & DROP. (If you don’t see it, click the Submit or Resubmit button at the bottom of the page.)
Add your file to the box labeled DRAG & DROP. You can either drag and drop the file from its folder into the box, or you can click on the box itself and browse for the file.
Click the Upload button.
You should see a box saying that your submission was successful.
Click the (x) button to close that box.
The Autograder will perform some tests on your file. Once it is done, check the results to ensure that the tests were passed. If one or more of the tests did not pass, the name of that test will be in red, and there should be a message describing the failure. Based on those messages, make any necessary changes. Feel free to ask a staff member for help.
Note: You will not see a complete Autograder score when you submit. That is because additional tests will be run later, after the final deadline for the submission has passed. For such problems, it is important to realize that passing all of the initial tests does not necessarily mean that you will ultimately get full credit on the problem. You should always run your own tests to convince yourself that the logic of your solutions is correct.
If needed, use the Resubmit button at the bottom of the page to resubmit your work. Important: Every time that you make a submission, you should submit all of the files for that Gradescope assignment, even if some of them have not changed since your last submission.
Near the top of the page, click on the box labeled Code. Then click on the name of each file to view its contents. Check to make sure that you see the code that you want us to grade.
Important
It is your responsibility to ensure that the correct version of every file is on Gradescope before the final deadline. We will not accept any file after the submission window for a given assignment has closed, so please check your submissions carefully using the steps outlined above.
If you are unable to access Gradescope and there is enough
time to do so, wait an hour or two and then try again. If you
are unable to submit and it is close to the deadline, email
your homework before the deadline to
cscis111-staff@lists.fas.harvard.edu
Last updated on June 29, 2026.