22
CS 1050 Common Final Exam Sample Questions

CS 1050 Common Final Exam Sample Questionsrowdysites.msudenver.edu/~gordona/cs1050/cs1050SampleFinalW17.pdfTest Case Number Description Input ... Sample Question 1.2: Trace execution

Embed Size (px)

Citation preview

CS 1050 Common Final Exam

Sample Questions

Topic # Topics Mapping to Student Learning Objective

1 TestingA) Error types (syntax errors, logical errors, run time errors)B) Detection of errorsC) Developing test casesD) DebuggingE) Handling run time errors using try/catch blocks

1. Write and run a computer program that correctly solves a problem in the range from simple to medium difficulty.

11. Utilize the top-down problem solving technique and stepwise refinement.

Sample Question 1.1: Given the following method:

public int someMethod (int input){ int result; if (input > 0) result = input; else if (input < 0) result = -1 * input; else result = 0;

return result;}

Write three test cases that can be used to test the method.Test CaseNumber

Description Input ExpectedOutput

CS 1050 Common Final Exam Page 2 of 22

Sample Question 1.2: Trace execution of this class, beginning with main, showing output in the space provided (we will include Java API document for parseInt method in Integer class):

public class ExceptionTest{ public static void main( String[] args) { int number; String str;

try { str = " xyz"; number = Integer. parseInt( str); System.out.println("A"); } catch( NumberFormatException e) { System. out. println("B"); } catch( IllegalArgumentException e) { System. out. println("C"); } }}

CS 1050 Common Final Exam Page 3 of 22

2 Data Types, Variables, and IdentifiersA) Different primitive data types (integers, real, characters, boolean)B) Objects (String)C) Naming rules and conventionsD) Scope, visibility, and lifetimeE) Constants

7. Use appropriate data types including integers, real numbers, characters, Booleans, arrays, and strings.

10. Determine the scope and visibility of an identifier.

Sample Question 2.1: Trace execution of this class, beginning with main, showing contents of memory for each method call, and showing output in the space provided:

public class Cat1c { public static void main(String[] args) { int x = 37; int y = 12; x = fiddle(y, x); System.out.println("x = " + x + " y = " + y); }

public static int fiddle(int x, int a) { int y; y = x + a; x++; a--; System.out.println("x = " + x + " y = " + y + " a = " + a); return y; }}

Methods Calls (Memory) Display

main

fiddle

CS 1050 Common Final Exam Page 4 of 22

Sample Question 2.2: Trace execution of this code fragment, showing contents of memory and output in the space provided:

String s = "hello";String t = "goodbye";System.out.println(s + t);System.out.println(s + " " + t);t = s;System.out.println(s + t);

Memory Display

CS 1050 Common Final Exam Page 5 of 22

3 ComputationA) OperatorsB) ExpressionC) Operator precedence

6. Utilize expressions, assignment, decision structures, and looping.

Sample Problem 3.1: Trace execution of this code fragment, showing contents of memory and output in the space provided:

int x = 17;int y = 14;int z = 3;y /= z;x %= 3;z = x + 2 * y;System.out.println("x = " + x + " y = " + y + " z = " + z); x += y;y++;y *= 2;System.out.println("x = " + x + " y = " + y + " z = " + z);

Memory Display

CS 1050 Common Final Exam Page 6 of 22

4 Input/OutputA) Interactive programsB) Reading and writing text filesC) Recognizing end of file

8. Write interactive programs and programs that use text files for input and output.

Sample Question 4.1: Suppose that a data file named test3 has these contents: 37 cat 5.2ape 4 eleven42

Trace execution of the program listed below, beginning with main, showing contents of memory, output to the console, and the contents of the file out3:

import java.io.File; import java.util.Scanner; import java.io.PrintWriter;

public class Cat1f { public static void main(String[] args) { try { Scanner input = new Scanner(new File("test3")); PrintWriter output = new PrintWriter("out3"); do { String s = ""; try { s = input.next(); int x = Integer.parseInt(s); output.println(x); } catch(Exception e) { System.out.println(s); } } while(input.hasNext()); input.close(); output.close(); } catch(Exception e2) { System.out.println("File not found"); } }}

CS 1050 Common Final Exam Page 7 of 22

Sample Problem 4.2: Complete the following code fragment for the main method:

public static void main (String[] args){ //Declare a scanner object

//Ask user for the reatil price of an item

//Ask user for the sales tax rate

//Calculate sales tax amount and display it

//Calculate total amount (retail price + sales tax amount) //and display the result

}

CS 1050 Common Final Exam Page 8 of 22

5 ClassesA) Difference between class and objectB) Defining classC) Declaration of fieldsD) Different types of fields – mutable vs non-mutableE) Constructors – default constructor, no argument constructor, constructor with argumentsF) Different types of methods – accessor vs mutatorG) Method header vs method signatureH) Method arguments – formal arguments vs actual argumentsI) Return value

4. Declare and define classes, methods, and variables.

5. Declare and utilize parameters and return values.

CS 1050 Common Final Exam Page 9 of 22

Sample Question (Test for conceptual knowledge) 5.1: Categorize each identifier in the class listed below as an Instance Variable (IV), Class Variable (CV), Parameter (P), Local Variable (LV), Constructor (C), Instance Method (IM), or Class Method (CM).

public class Segment{ private static int current = 10; private int id; private double x1, y1, x2, y2; public Segment( double a, double b ){ current++; id = current; double temp = a+b; x1=a; y1=b; x2=temp; y2=3; }

public void moveEnd( double c, double d ){ x2=c; y2=d; } public double flop(){ return x1+y2; }

public void smoosh( Segment other ){ x1=other.y2; other.x1=y1; y1 = other.x2; }

public String toString(){ return "[("+x1+","+y1+")("+x2+","+y2+")"+id+"]"; }

public static void main(String[] args){ Segment r = new Segment( 2, 5 ); Segment s = new Segment( 4, 1 ); System.out.println( r + " " + s ); r.moveEnd( 8, 4 ); s.moveEnd( 0, 0 ); System.out.println( r + " " + s );

CS 1050 Common Final Exam Page 10 of 22

System.out.println( r.flop() ); s.smoosh(r); System.out.println( r + " " + s ); }}

Identifier IV CV C IM CM P LV

current

id

x1

y1

x2

y2

Segment

a

b

temp

moveEnd

c

d

flop

smoosh

other

toString

main

args

r

s

CS 1050 Common Final Exam Page 11 of 22

Sample Question 5.2: Consider the following objects and their properties:

Car: fuel capacity, serial number, passenger capacity, net weight, license plateBoat: fuel capacity, serial number, passenger capacity, net weight, draft

We want to use inheritance to implement the above given objects. Define a third class which can be the superclass. Provide a list of fields that will be included in each of the classes.

CS 1050 Common Final Exam Page 12 of 22

Sample Question 5.3: Trace execution of this program, beginning with main, showing contents of memory and output in the space provided:

public class Box { private int x, y, w, h; private static int maxWidth = 6; public Box(int xIn, int yIn) { if ( xIn > maxWidth ) { x = maxWidth; } else { x = xIn; } y=yIn; w=0; h=3; }

public void grow(int a) { w += a; h += a; }

public void fight( Box other ) { x =other.y+5; other.x = 7; }

public int cross(){ return x * y; }

public String toString(){ return "[(" + x + "," + y + ") " + w + " " + h + "]"; }

public static void main(String[] args) { Box a = new Box(12, 5); Box b = new Box(2, 7); System.out.println("new boxes: " + a + " " + b); a.grow(3); b.grow(2); System.out.println("after grow: " + a + " " + b); b.fight(a); System.out.println("after fight: " + a + " " + b);

CS 1050 Common Final Exam Page 13 of 22

System.out.println("cross: " + a.cross() ); }}

Static Variables Display

Memory

CS 1050 Common Final Exam Page 14 of 22

6 Decision StructuresA) Relational expressionB) Logical expressions

1. Write and run a computer program that correctly solves a problem in the range from simple to medium difficulty.

6. Utilize expressions, assignment, decision structures, and looping.

Sample Question 6.1: Given the following class:

public class SalesCalculator{ private double cost; private int quantity;

}

Write the code for the following method:

public double totalAmount (){ }

It calculates the total amount. Total amount is (quantity * cost) – discount. Discount is calculated based on the following formula:

Quantity Discount

10-19 20%

20-49 30%

50-99 40%

100 or more 50%

CS 1050 Common Final Exam Page 15 of 22

7 LoopingA) while, do while, for loopsB) infinite loops

1. Write and run a computer program that correctly solves a problem in the range from simple to medium difficulty.

6. Utilize expressions, assignment, decision structures, and looping.

Sample Question 7.1: Trace execution of this code fragment, showing contents of the memory and output in the space provided:

int x=10; y=11;z=3; do { System.out.println(x + " " + y + " " + z); if (y > z) { y = y – 5; } else { y = y + 3; } x = x – 2;} while (x > 0);

System.out.println("Bye");

Memory Display

CS 1050 Common Final Exam Page 16 of 22

8 ArraysA) one and two-dimensional arraysB) processing and using arrays including partially filled arraysC) searching – linear D) sorting -- selection

1. Write and run a computer program that correctly solves a problem in the range from simple to medium difficulty.

7. Use appropriate data types including integers, real numbers, characters, Booleans, arrays, and strings.

Sample Question 8.1: Trace execution of this program, beginning with main, showing contents of memory and output in the space provided:

public class Cat1e{ public static void main(String[] args){ int[] a = { 7, 11, 4, 18, 25, 19, 30, 82 }; int[] b = new int[ a.length ]; int end = 0;

for (int j=0; j<a.length; j+=2) { b[ end ] = a[ j ]; end++; }

System.out.print("b = ["); for (int k=0; k<end; k++) { System.out.print(b[k] + " "); } System.out.println(" ]"); }}

Memory Display

CS 1050 Common Final Exam Page 17 of 22

Sample Question 8.2: Suppose that the Puppy class has a method with signature: public int cuteness()

that returns the cuteness of a puppy.

Your job on this question is to write the body of the method documented below.

// return the total cuteness of// all the puppies in the given listpublic int getTotalCuteness( ArrayList<Puppy> list ){

}

CS 1050 Common Final Exam Page 18 of 22

Sample Question 8.3: Write the body of the method given below, following the documentation:

// Copy every item stored in the given array three positions // toward the beginning, but don’t copy any items that// would cause an exception// For example, if the method is called with// array = [ "a", "b", "c", "d", "e", "f", "g", "h" ]// then after the method executes// array = [ "d", "e", "f", "g", "h", "f", "g", "h" ] public static void shiftLeft3(String[] arrray) {

}

CS 1050 Common Final Exam Page 19 of 22

Sample Question 8.4: Write the body of the method given below, following the documentation:

// add up the items in array in the sub-rectangle// with rows between firstRows and lastRow, inclusive,// and columns between firstCol and lastCol, inclusive,// and return that total// Assume that the four given integers are valid for the array public static int totalRegion(int[][] array, int firstRow, int lastRow, int firstCol, int lastCol){}

CS 1050 Common Final Exam Page 20 of 22

9 Development processA) Problem definitionB) Algorithm designC) ModularityD) Top-down design, step-wise refinementE) Object oriented designF) Software documentation

1. Write and run a computerprogram that correctly solves a problem in the range from simple to medium difficulty.

2. Appropriately document a computer program.

3. Use modularity when writing programs.

9. Utilize the top-down problem solving technique and stepwise refinement.

Sample Question 9.1: Create a complete Java application in a class named StrangeCalc that behaves as a strange calculator as follows. This calculator maintains a “current value” which is an integer. The user repeatedly enters commands. Each command performs some operation on the currentvalue, typically changing it, and then the new current value is displayed. The current value starts at 0.

Here are the commands: Command Operation

twice Replace current value by twice the current value

hop Replace the current value by three times the current value plus one

shrink Replace the current value by half the current value (using integer division)

quit Halt the application

Here is a screen image showing a sample run of the program: value: 0 ? hop value: 1 ? hop value: 4? twice value: 8? hopvalue: 25? shrinkvalue: 12? quit

CS 1050 Common Final Exam Page 21 of 22

Sample Question 9.2: Suppose you are starting work on a program to be used for a restaurant. As part of this work, you realize you need to have a class Order to store and work with the items a table of customers orders.

The restaurant only sells burgers, fries, and drinks. An order has instance variables storing how many burgers, how many sacks of fries, and how many drinks the table has ordered, along with the name of the staff person who took the order.

The restaurant encourages people to order “meals,” where a meal consists of one burger, one sack of fries, and one drink. So, if a table orders 5 meals, their order will have 5 burgers, 5 sacks of fries, and 5 drinks.

But, after ordering their meals, they can also adjust the number of each item they want (only adjustingburgers is asked for—similar methods for fries and drinks would be needed).

Each burger costs $3.50, each sack of fries costs $2.75, and each drink costs $2.25.

Write the bodies for all the constructors and instance methods, following the documentation for each method and using the given instance variables.

public class Order { private String name; // the server who took the order private int burgers; // the number of burgers in the order private int fries; // the number of sacks of fries in the order private int drinks; // the number of drinks in the order // given a server’s name and a number of meals, // construct this order public Order(String server, int numMeals) { }

// add the given number of burgers to the order // (n can be negative to remove burgers) // Don’t let the number of burgers go below 0 public void addBurgers(int n) { } // compute and return the cost of this order public double figureCost() { }

// return whether this order and the given other order // have the same server public boolean haveSameServer(Order other) { }}

CS 1050 Common Final Exam Page 22 of 22