CS 112
Spring 2024

Problem Set 1

due by 11:59 p.m. Eastern time on Tuesday, January 30, 2024

Preliminaries

In your work on this assignment, make sure to abide by the collaboration policies of the course.

If you have questions while working on this assignment, please come to office hours, post them on Piazza, or email cs112-staff@cs.bu.edu.

Make sure to follow the instructions outlined at the end of Part I and Part II when submitting your assignment.

Part I

40 points total

This part of the assignment consists of a series of short-answer questions. You will be able to check your answers to at least some of these questions by executing the code, but we strongly encourage you to answer them on your own and to convince yourself of the correctness of your answers before you try to test them. These questions are similar to ones that could appear on the midterms and final exam, so it’s important to be able to answer them without the use of a computer.

Creating the necessary folder

  1. If you haven’t already created a folder named cs112 for your work in this course, follow these instructions to do so.

  2. Then create a subfolder called ps1 within your cs112 folder, and put all of the files for this assignment in that folder.

Creating the necessary file

The problems from Part I will all be completed in a single PDF file. To create it, you should do the following:

  1. Access the template that we have created by clicking on this link and signing into your Google account as needed.

  2. When asked, click on the Make a copy button, which will save a copy of the template file to your Google Drive.

  3. Select File->Rename, and change the name of the file to ps1_partI.

  4. Add your work for the problems from Part I to this file.

  5. Once you have completed all of these problems, choose File->Download->PDF document, and save the PDF file in your ps1 folder. The resulting PDF file (ps1_partI.pdf) is the one that you will submit. See the submission guidelines at the end of Part I.

Problem 1: Java programming basics

10 points total; 5 points each part; individual-only

  1. The following program has many syntax errors:

    import java.util.*;
    class Problem1 {
       static void main(String[] args) {
          console = Scanner(System.in)
          System.print('Enter an integer n: ')
          int n = Scanner.nextInt()
          int sum = calculateSum(n);
          System.out.println("The sum of the numbers is: " + sum);
       };
       /*
        * This static method should take an integer n and return
        * the sum of all integers from 1 up to n, inclusive.
        */
        private static int calculateSum(n) {
           int sum = 0;
           for (int i = 0; i < n;) {
              sum+= 1 and i = i+1
           }
           return sum
        };
    };
    

    Identify and correct all the problems with this program so that it will compile and run as follows:

    • Prompt the user to enter an integer and store the user’s input in the variable n.

    • Call the method calculateSum with n as its input, and print the value returned by that method. calculateSum should have the functionality specified in the comment that precedes it.

    Here’s what a run of the program should look like if the user enters 5:

    Enter an integer n: 5
    The sum of the numbers is: 15
    

    And here’s what it should look like if the user enters 10:

    Enter an integer x: 10
    The sume of the numbers is: 55
    

    Debugging in VS Code
    We encourage you to use VS Code to help you to debug this program. Here are the steps:

    1. If you haven’t already done so, create a folder named ps1 for your work on this assignment.

    2. Download the following file: Problem1.java

      Make sure to put the file in your ps1 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.

    3. 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 for this assignment. (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 Problem1.java file that you downloaded above.

    4. Click on the name Problem1.java, which will open an editor window for that file.

    5. Make whatever edits are needed to allow you to compile and run the program. You can try to run the program by using the F5 key, or by right-clicking the name of the program in the Explorer pane and choosing Run or Run Java.

    Once you are confident that you have fixed all of the problems in the code, put the revised program in your ps1_partI file as your answer to this question. (See the guidelines at the start of Part I for how to create this file.)

  2. Assume that the following variable declarations have already been executed:

    int a = 1;
    double b = 2;
    double c = 3.0;
    String d = "4";
    String e = "five";
    boolean f = true;
    

    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.

    1.       (double)(a) / 2
    2.       (int)(c)
    3.       (int)(a / b)
    4.       a / c
    5.       "cs"+a+a+b
    6.       b==2*a
    7.       (double)(a / 2)
    8.       a + b + c
    9.       b + c + d
    10.       d + e + f

Problem 2: Conditional execution

10 points total; individual-only

Consider the following code fragment:

import java.util.Scanner;

public class BigBang {
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.print("Enter three numbers: ");
       int a = scan.nextInt();
       int b = scan.nextInt();
       int c = scan.nextInt();

       if (a < b) {
           if (b < c) {
               if (a < c) {
                   System.out.println("You won!");
               }
           } else if (a < c) {
               System.out.println("rock!");
           }
           System.out.println("scissors!");
       } else if (a < b && a < c) {
           System.out.println("rock!");
       } else if (!(b < c)) {
           System.out.println("paper!");
       }
       System.out.println("lizard!");
       if (!(a < b)) {
           System.out.println("spock");
       } else if (b < c) {
           System.out.println("You lost!");
           if (a == b || b == c || a == c) {
               System.out.println("You lost again!");
           } else {
              System.out.println("You won!");
           }
       }
       System.out.println("done");
   }
}
  1. (6 points) In section 2-1 of ps1_partI (see above), state the output that would result from each of the following sets of inputs. (In each case, the first number will be assigned to the variable a, the second number will be assigned to b, and the third number will be assigned to c.)

    1.     1 2 3
    2.     1 3 2
    3.     2 1 3
    4.     2 3 1
    5.     3 2 1
    6.     3 1 2
  2. (4 points) At least one of the println statements in the above code fragment will not be executed for any set of inputs. Identify the statement(s) and explain why it/they will never be executed.

Problem 3: Static methods

10 points total; individual-only

  1. (5 points) Consider the following Java program, which includes two static methods:

    public class TracingMethodCalls {
       public static int compute(int x, int y) {
          System.out.println(x + " " + y);
          if (x*y > 0)
             if (y%2==0)
                return -y/2+1;
             else
                return -x/y;
          else if (x>0 && y>0)
             return -2*x;
          else
             return -y;
       }
    
       public static void main(String[] args) {
          int x = 8;
          int y = -6;
          System.out.println(x + " " + y);
          y = compute(x, y)/2;
          System.out.println(x + " " + y);
          x = 2*compute(y, x);
          System.out.println(x + " " + y);
          y = compute(x, x);
          System.out.println(x + " " + y);
       }
    }
    

    In section 3-1 of ps1_partI (see above), we have given you tables that you should complete to illustrate the execution of the program.

    We have started the first and third tables for you. You should:

    • complete the first and second tables so that they illustrate how the values of the variables change over time
    • complete the last table so that it shows the output of the program (i.e., the values that are printed).

    You may not need all of the rows provided in the tables.

  2. (5 points) Fill in the blanks below to create a static method that takes as parameters two integer arguments a and b and returns a String of the relational operator >, > or =, which indicates the appropriate relation of the arguments a and b.

    public _____________ relationalOperator(______________________) {
        if (__________________)
           return __________________;
        else
           /*
            * Fill the rest of the code.
            * You might need more lines 
            * of code to finish this function
            */
    }
    

    Example:

    relationalOperator(3, 6) should return "<"
    relationalOperator(7, 5) should return ">"
    

Problem 4: Loops

10 points total; individual-only

  1. (3 points) Consider the following partial code fragment:

    public static void oddProduct(int n) {
       int product = ____________;
       for (____________; ____________; ____________) { 
          if (____________)
              ____________;
       }
       System.out.println(product);
    }
    

    Fill in the blanks to create a loop that computes the product of all positive odd numbers smaller than n.

  2. (3 points) Consider the following method:

    public static void increaseBy(int n, int f, int t) {
       for (int r = n; r < (n+f*t); r+=f) {
          System.out.println(r);
       }
    }
    

    Assuming that the inputs n, f and t are positive integers, this loop runs t times and increments n by a factor f for each iteration of the loop. For example:

    5
    9
    13
    

    We have included the original method in ps1_partI. Rewrite this loop so that it uses a while loop instead of a for loop.

  3. (4 points) Consider the following code fragment:

    public static void diamond(int n) {
       for (int i = 0; i < n; i++) {
          if (i < n / 2) {
             for (int j = 0; j < n % i; j++) {
                System.out.print(j);
             }
          } else {
             for (int j = 0; j < i; j++) {
                System.out.print(j);
             }
          }
          System.out.println();
       }
    }
    

    Modify this fragment to make it produce the following output when diamond(int 10) is called:

    1
    22
    333
    4444
    55555
    4444
    333
    22
    1
    

    We have included the original code fragment in ps1_partI. Make whatever changes are needed to obtain the correct output.

Submitting your work for Part I

Note: There are separate instructions at the end of Part II that you should use when submitting your work for that part of the assignment.

Submit your ps1_partI.pdf file using these steps:

  1. If you still need to create a PDF file, open your ps1_partI file on Google Drive, choose File->Download->PDF document, and save the PDF file in your ps1 folder.

  2. Login to Gradescope by clicking the link in the left-hand navigation bar. When logging in, make sure that you use the School Credentials option and select Boston University.

  3. Once you are logged in, click on the box for CS 112. (If you don’t see that box, you should email cs112-staff@cs.bu.edu so that we can add you to the course’s Gradescope site.)

  4. Click on the name of the assignment (PS 1: Part I) 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.)

  5. 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.

  6. You should see a question outline along with thumbnails of the pages from your uploaded PDF. For each question in the outline:

    • Click the title of the question.
    • Click the page(s) on which your work for that question can be found.

    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.

  7. Once you have assigned pages to all of the questions 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 cs112-staff@cs.bu.edu


Part II

30 points total

Important guidelines

The following guidelines apply to the programming problems (i.e., problems in which you submit a .java file) in this and all subsequent assignments.

  • You should not use any built-in Java classes or methods that we have not covered in the lecture notes, unless we explicitly instruct you to do so.

  • Use 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.

  • At a minimum we expect that your submitted code will compile and run. If your code does not compile during our tests, you will not receive any credit for that specific problem. 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.

Problem 5: Computing an insulin dosage

15 points total; pair-optional

This is the only problem of the assignment that you may complete with a partner. See the rules for working with a partner on pair-optional problems for details about how this type of collaboration must be structured.

Important

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 standards 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

  1. If you haven’t already done so, create a folder named ps1 for your work on this assignment. You can find instructions for doing so here.

  2. Download the following file: InsulinDosage.java

    Make sure to put the file in your ps1 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.

  3. 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.

  4. Click on the name InsulinDosage.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

  1. Start by reading over the starter code that we’ve given you. Make sure that you understand it.

  2. Complete the assignment statements in the main method for the variables currentSugar, targetSugar, carbEquiv, carbConsume and exercise. At the moment, each of these assignment statements assigns the number 0. For example, here is the first of the three assignments:

    int currentSugar = 0;
    

    You should replace the 0 in each of the assignment statements with a call to a Scanner method that reads an integer entered by the user from the keyboard.

    Important: You must use the Scanner object created at the start of the main method, and you may not create an additional Scanner object.

    You may assume that all of the values entered by the user are valid values, and thus you do not need to perform any checking for problematic values.

  3. Complete the main method so that it uses the values of the variables to compute the correct dosage of insulin, using the following formula:

     :::text
                currentSugar - targetSugar     carbConsume
     dosage  =  --------------------------  +  -----------  -  exercise
                            55                  carbEquiv
    

    For example, assume that a person enters the following values:

    • current blood sugar: 210
    • target blood sugar: 100
    • carbohydrate equivalency: 10
    • carbohydrates to consume: 60
    • amount of exercise: 2

    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
    

    Notes:

    • The formula that we have given you uses standard mathematical notation. You will need to use the appropriate Java operators and appropriate numeric literals in your code.

    • You may find it helpful to compute the cost in stages by first computing some of the components of the formula – storing their values in one or more variables that you declare – and then combining those components to compute the final result.

    • In the example above, the dosage happens to be an integer, but that won’t always be the case, and you should make your computation as precise as possible. This means that you will need to be careful with the type that you select for your dosage variable (and any other variables that you may use for intermediate results) and in the expressions that you construct for your computations.

  4. Display the appropriate message, which depends on the value of the computed dosage as follows:

    • If the computed dosage is exactly 1.0, the program should print the following message:

      recommended dosage: 1 unit
      

      Note that the dosage is printed without a decimal, and that the final word printed is unit, not units.

    • If the computed dosage is greater than 0.0 and is a whole number other than 1.0, the program should still print the dosage without a decimal, but the final word should be units with an s at the end. For example, if the computed dosage is 6.0, the program should print:

      recommended dosage: 6 units
      
    • If the computed dosage is greater than 0.0 and is not a whole number (i.e., it has a fractional part), the program should print the full computed value, including all of the digits after the decimal point. For example, if the computed dosage is 7.125, the program should print:

      recommended dosage: 7.125 units
      
    • If the dosage is less than or equal to 0.0, the program should print the following message:

      recommended dosage: 0 units
      

    Notes:

    • There is more than one way to test if the computed dosage is a whole number. You may want to consider using a type cast in some way.

    • Make sure that the format of your results matches the examples that we have shown above.

  5. Test your program on a variety of inputs to make sure that you don’t have any logic errors in your code.

    Remember that you can run the program by using the F5 key, or by right-clicking the name of the program in the Explorer pane and choosing Run or Run Java.

    Note: When your run the program, you may need to click on the Terminal area of VS Code in order to input the five numbers.

Problem 6: Computing area from diameter

15 points; individual-only

This problem involves writing a program that computes the area of a circular piece of land, based on its diameter.

Getting started

  1. As needed, open your ps1 folder using the File->Open Folder or File->Open menu option in VS Code.

  2. Select File->New File, which will open up an empty editor window.

  3. Select File->Save, and give the new file the name Circular.java.

Writing the program

  1. Add comments at the top of the new file that include:

    • a brief desciption of what the program is supposed to do.
    • your name and email address

    See the comments that we provided in the starter code for previous problem for an example of what they should look like.

  2. Below the comments – and before any class header – add an import statement for the java.util package, as we did in the starter code for the previous problem. Including this import statement will allow you to create a Scanner object in your program.

  3. Create a class named Circular that will serve as a container for your program.

  4. Inside the Circular class, add a main method with the usual header.

  5. Start the main method by creating a Scanner object for getting user inputs from the keyboard and assigning it to an appropriate variable.

  6. Next, add code to obtain an integer representing the diameter of the piece of land (specified to the nearest foot) and store it in an appropriate variable.

    Use a print statement with an appropriate prompt, and then use the Scanner that you created at the start of main to get the diameter from the user.

    Important: You must use the Scanner object created at the start of the main method, and you may not create an additional Scanner object.

  7. Use the value entered for the circle’s diameter to compute its area in square feet as a real number, and store the result in an appropriate variable. Make the computation as precise as possible.

    Recall that:

    • The radius of a circle is half of its diameter.

    • The area of a circle is π times the radius squared (i.e., π * radius * radius). Use the value of π available in Java’s built-in Math class, which you can obtain by writing Math.PI

    For example, if the diameter is 10 feet, the radius is 5 feet, and thus the area is Math.PI times 5 squared or 78.53981633974483 square feet.

  8. Display the approximate area of the circle in two forms:

    • in square feet rounded to the nearest integer; to perform the necessary rounding, make a call to the built-in Math.round method.

      Note: Math.round returns a value of type long, which is the data type that Java provides for large integers. As a result, in order to store the return value in a variable of type int, you will need to perform a type cast.

    • as a whole number of square yards, with the remaining area expressed as an integral number of square feet. 1 square yard is 3 square feet, so you can convert from square feet to square yards by dividing by 9.

    For example, if the user enters a diameter of 10, the output should look like this:

    The area of the circle is approximately:
    79 square feet
    8 square yards plus 7 square feet
    

    Note that the final line of results stems from the fact that 79 divided by 9 is 8 with a remainder of 7.

    Make sure that the format of your results matches the example that we have shown above.

  9. Close the Scanner object’s connection to the keyboard by calling the object’s close() method. See the starter code for the previous problem for an example of how to do this.

  10. Test your program on a variety of inputs to make sure that you don’t have any logic errors in your code.

Submitting your work for Part II

Note: There are separate instructions at the end of Part I that you should use when submitting your work for that part of the assignment.

Submission checklist for Part II

  • You have read the Java coding standards and followed all guidelines regarding format, layout, spaces, blank lines, and comments.

  • You have verified that your code satisfies all of the tests that we have provided, and you have conducted whatever other tests are needed to ensure that your code works correctly.

Pair-optional problem

If you chose to work on Problem 5 with a partner, both you and your partner should submit your own copy of your joint work, along with your individual work on the other problem. Don’t forget to include your partner’s name and email in the comments at the top of the file.

You should submit only the following files:

Make sure that you do not try to submit a .class file or a file with a ~ character at the end of its name.

Here are the steps:

  1. Login to Gradescope by clicking the link in the left-hand navigation bar, and then click on the box for CS 112. When logging in, make sure that you use the School Credentials option and select Boston University.

  2. Click on the name of the assignment (PS 1: Part II) 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.)

  3. Add your files to the box labeled DRAG & DROP. You can either drag and drop the files from their folder into the box, or you can click on the box itself and browse for the files.

  4. Click the Upload button.

  5. You should see a box saying that your submission was successful. Click the (x) button to close that box.

  6. The Autograder will perform some tests on your files. 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 for at least some of the problems 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.

  7. 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.

  8. 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 the files contain 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 cs112-staff@cs.bu.edu