part I due by 10 p.m. on Monday, June 30, 2025
part II due by 10 p.m. on Tuesday, July 1, 2025
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 f = 15; int g = 2; double h = 2.0; double i = 2; double j = 10.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.
f + g
f + "g" + 1
f + 1 + "g"
f / g
f / h
f / i
(int)j / f * f
(int)(j / f) * f
7 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
val
a value that is 5 less than the value of num
.
(1 point) Write a single assignment statement that cuts the
value of num
in half.
(1 point) Assume that val
is a two-digit number (i.e., a number
between 10 and 99). Write a single assignment statement that
assigns to num
the 10’s digit of the value of val
. For
example, if val
has a value of 71, your assignment statement
should end up assigning a value of 7 to num
. Your statement must
use a single arithmetic operator, and it must work for an
an arbitrary value of val
between 10 and 99.
(2 points) If the value of val
can have an arbitrary number of
digits, we need to use a different approach when determining its
10’s digit. Write a single assignment statement that assigns
to num
the 10’s digit of the value of val
, regardless of how many
digits the value has. For example, if val
has a value of 12345, your
assignment statement should end up assigning a value of 4 to num
;
if val
has a value of 5, your statement should end up assigning a
value of 0.
Hint: the right-hand side of the assignment statement should be expressed using two mathematical operators.
(2 points) What are the values of num
and val
after the
following assignment statements have been executed?
val = 9; val = val * 2; num = val - 4; val = 11;
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("I feel loopy!"); }
Fill in the blanks to create a loop that repeats the message “I feel loopy!” 12 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 > 30; i++) { System.out.println(i); }
This code is supposed to print the multiples of 5 from 5 to 30 on separate lines, as follows:
5 10 15 20 25 30
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 <= 4; i++) { for (int j = 1; j < 4; 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 = 0; i < 3; i++) { for (int j = 2; j >= 0; j--) { System.out.println(i + " " + j); } System.out.println("--"); }
Modify this fragment to make it produce the following output:
0 0 -- 1 1 1 0 -- 2 2 2 1 2 0 -- 3 3 3 2 3 1 3 0 --
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
We will cover the material needed for this problem on Friday, 6/24.
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 ps2_partI
file.
6 points total; 1 pt. each part; individual-only
Consider the following program, which includes a number of incomplete println statements:
public class ScopeThisOut { public static void doSomething() { int a = 5; System.out.println(________); // first println int b = 2; for (int i = 1; i <= 5; i++) { System.out.println(________); // second println int c = 2; for (int j = 0; j < 3; j++) { System.out.println(________); // third println int d = 4; } } System.out.println(________); // fourth println } public static void main(String[] args) { int x = 5; System.out.println(________); // fifth println int y = 2; doSomething(); System.out.println(________); // sixth println } }
The program includes a number of int
variables: a
,b
,c
,d
,
i
, j
, x
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.
Some people with type I diabetes inject insulin before each meal in order to stabilize their blood-sugar level. The amount of insulin that is required depends on several factors. This problem asks you to complete a simple program that allows the user to compute the amount of insulin that they should inject.
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: Insulin.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 VS Code, 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 VS Code window, along with the name of the
Insulin.java
file that you downloaded in step 2.
Click on the name Insulin.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:
currentSugar
targetSugar
carbEquiv
carbConsume
exercise
.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 to compute the correct dosage of insulin, using the following formula:
currentSugar - targetSugar carbConsume dosage = -------------------------- + ----------- - exercise 55 carbEquiv
For example, assume that a person enters the following values:
For this person, the program should perform the following computation:
(210 - 100) 60 dosage = --------- + -- - 2 55 10 = 110 --- + 6 - 2 55 = 2 + 6 - 2 = 6
If the dosage is greater than 0, the program should output the result using a message like the following:
You should consume 6.0 units of insulin before the meal.
If the dosage ends up being less than or equal to 0, the program should print the following message instead:
You do not need to consume any insulin before the meal.
Use conditional execution to determine which message to print. See our ChangeAdder4.java program for an example of using this type of construct.
Important
For this example, the dosage happens to be an integer. However, this will not always be the case. See guideline 4 below for more detail. Also, you do not need to round the dosage; rather, you should print the full value that you obtain, including all of the digits after the decimal point.
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.
Make sure that the program that you submit compiles, even if
it isn’t complete. If it doesn’t compile, we can’t test it,
and you will end up losing most if not all of the available
points. If there are lines in your program that prevent it from
compiling, remove them or turn them into comments by putting two
slashes (//
) 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.
Test your program on a variety of inputs to make sure that you don’t have any logic errors in your code.
13 points; pair-optional
This problem asks you to complete a simple program that allows the user to compute some information about a right triangle.
Getting started
Download the following file: RightTriangle.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 VS Code.
The name of the folder should appear in the Explorer pane on the left-hand side of the VS Code window, along with the name of the file that you downloaded in step 1.
Click on the name RightTriangle.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 reads from the user
the lengths of the two two legs of a right triangle – measured to the
nearest inch – and stores these lengths in the variables a
and b
.
You should add the code needed to compute and report the following values:
the length of the hypotenuse as a real number. By the Pythagorean
theorem, the hypotenuse c
is the square root of the sum of the
squares of the legs a
and b
. When computing the hypotenuse,
you should use the built-in Math.sqrt
method. For example, to
compute the square root of the value in the variable foo
, you
would write Math.sqrt(foo)
the area of the triangle in square inches as a real number. The area
of a right triangle is half of the product of the legs (i.e., the
product of a
and b
divided by 2).
the area of the triangle in square feet as a real number. Note that
square feet = square inches / 144
the area of the triangle as an integral number of square feet, with the remaining area expressed in square inches as a real number.
For example, here is a sample run of the program, with user inputs of 20 and 17:
Enter the first leg to the nearest inch: 20 Enter the second leg to the nearest inch: 17 The hypotenuse is: 26.248809496813376 inches The area is: 170.0 sq in 1.1805555555555556 sq ft 1 sq ft and 26.0 sq in
Note: The first two lines above are from the portion of the program that we provided to read values from the user. You should not echo/re-print the user’s inputs.
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 an arched opening:
======================== //\\//\\//\\//\\//\\//\\ //\\//\\//\\//\\//\\//\\ ======================== :::::::::::::::::::::::: :::::::::::::::::::::::: //\\::::::_/\_:::::://\\ //\\::::_/ \_:::://\\ //\\::_/ \_:://\\ //\\_/ \_//\\ |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| ==== ==== |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| |||| ======================== ////////::::::::\\\\\\\\ ///////::::::::::\\\\\\\ ======================== //\\//\\//\\//\\//\\//\\ //\\//\\//\\//\\//\\//\\ ========================
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:
Put this version of your program in a class called DrawArch
.
After opening your ps2
folder in VS Code, select File->New Text
File, which will open up an empty editor window. Then select
File->Save, and give the new file the name DrawArch.java
Each print/println statement should print at most two
characters. Note that an escape sequence like '\\'
only counts
as a single character.
Make sure that your program exactly reproduces the output shown above. This includes having identical characters and spacing. There should be no blank lines before or after the drawing, and no extra spaces to the left or right of a given line.
When comparing your output to the expected output, you may find it helpful to consult the text file available here; additional text files for other sizes of the figure are available below. In addition, when you submit your code on Gradescope, one of the preliminary tests will tell you if your code produces the correct output for the default size of the figure.
You may find it helpful to use the 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.)
Use procedural decomposition – employing static methods to capture the structure of your solution and to eliminate code duplication – as you did in Problem Set 1. Make sure that no substantial groups of repeated statements appear in your code.
Employ 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. In particular, you should have comments at the start of the file and before each method, as you did in Problem Set 1. See the coding conventions for more detail.
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 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
DrawArch2.java
, and change the name of the class in this file to
DrawArch2
.
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 diagram includes several horizontal lines that always have a height of 1, regardless of the value of the constant. The example outputs given above should help you to determine where these fixed-height horizontal lines are found. (Note that the widths of these horizontal components do depend on the value of the constant.)
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 VS Code.
The name of the folder should appear in the Explorer pane on the left-hand side of the VS Code 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:
Insulin.java
RightTriangle.java
DrawArch.java
DrawArch2.java
RootCompute.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 27, 2025.