Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

Similar documents
CS111: PROGRAMMING LANGUAGE II

Midterm Examination (MTA)

Introduction to Java Applications

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

CSE 1223: Exam II Autumn 2016

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Section 2.2 Your First Program in Java: Printing a Line of Text

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks?

Fundamentals of Programming Data Types & Methods

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Section 004 Spring CS 170 Exam 1. Name (print): Instructions:

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Question: Total Points: Score:

PROGRAMMING FUNDAMENTALS

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Functions. Arash Rafiey. September 26, 2017

Computer Science II (20082) Week 1: Review and Inheritance

CS110: PROGRAMMING LANGUAGE I

Example: Monte Carlo Simulation 1

Chapter 4: Control Structures I

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Chapter 3. Selections

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

AP Computer Science Unit 1. Programs

CSE Fall 2015 Section 002 Exam 2, Time: 80 mins

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Introduction to Programming Using Java (98-388)

What did we talk about last time? Examples switch statements

Object Oriented Programming. Java-Lecture 1

COS 126 Midterm 1 Written Exam Fall 2011

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key

Section 2.2 Your First Program in Java: Printing a Line of Text

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

2.8. Decision Making: Equality and Relational Operators

Programming with Java

New York University Intro to Computer Science (CSCI-UA.101) Fall 2014 Midterm #1 Test G. Instructions:

Place your name tag here

Object Oriented Programming. Java-Lecture 6 - Arrays

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Chapter 2. Elementary Programming

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Full file at

Object-Oriented Programming

Introduction to Programming (Java) 4/12

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Program Fundamentals

CS313D: ADVANCED PROGRAMMING LANGUAGE

H212 Introduction to Software Systems Honors

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

Introduction to Java & Fundamental Data Types

COMP 202 Java in one week

More Programming Constructs -- Introduction

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

Computer Components. Software{ User Programs. Operating System. Hardware

COE 212 Engineering Programming. Welcome to the Final Exam Monday May 18, 2015

Lecture Set 4: More About Methods and More About Operators

CS141 Programming Assignment #5

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Final Exam. COMP Summer I June 26, points

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter Goals. Contents LOOPS

Computer System and programming in C

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Full file at

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Introduction to Java Applications

Primitive Data Types: Intro

Simple Java Reference

AP CS Unit 3: Control Structures Notes

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Full file at

1 Shyam sir JAVA Notes

Chapter 02: Using Data

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

Course Outline. Introduction to java

CS141 Programming Assignment #6

Important Java terminology

Glossary. (Very) Simple Java Reference (draft, v0.2)

A variable is a name for a location in memory A variable must be declared

Chapter 2: Using Data

CEN 414 Java Programming

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Chapter 3: Operators, Expressions and Type Conversion

Ch. 6. User-Defined Methods

Transcription:

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points. Use the remaining question as extra credit (worth 1/2 of the points earned). Specify which question is extra credit by writing EXTRA CREDIT in caps above the question. If you do not specify extra credit, the last question (#4) will be counted as extra credit. 1. Answer the questions about the code on the left in the column on the right. (a) Assume that all of the code is within the main method of a Java program (b) Additionally, assume that a Scanner object called input is within scope (c) Show your work (where possible) for partial credit (for example, write the values of variables, add comments in the code inline, etc.) Code Question #1 char ch = '\u0045'; int i = 0b00001101; syso(ch); syso(i); What is the output of this program? Show your work for partial credit. E 13 int total = 0; for(int i = 40; i > 10; i -= 10) { syso(i); total += i; syso(total); What is the output of this program? Show your work for partial credit. 40 30 20 90 int num = input.nextint(); String medal = ""; switch(num) { case 1: medal = "gold"; case 2: medal = "silver"; case 3: medal = "bronze"; syso(medal); int x = 1, y = 1; while(x > y && x >= 0 && y >= 0) { The program is meant to display the medal corresponding the number, num... for example, 1 should result in gold, and typing in 3 should display bronze. There is a logical error in the code. Fix the error by marking-up the code on the left (cross out, add lines, draw arrows). Add break statements Convert the do while loop into a regular while loop. You can mark-up the code on the left (cross out, add lines, draw arrows) to do this. syso("please enter two numbers"); x = input.nextint(); y = input.nextint();

2. And mistakes were made. The following two parts deal with syntax and logic errors. Part 1 Syntax / Compile Time Errors Circle 4 unique syntax / compile errors in the following two method definitions (assume that both methods exist in a class) and give a short, 2 or 3 word description of the error. Draw arrows to help annotate. public static void foo(int bar) { // <---- 1. overloading int[] numbers; int x = 12 ; // <---- 2. missing semicolon numbers = {x, 2, 3; // <---- 3. array initialization w/ { on 1 line public static int foo(int bar) {// <---- 1. overloading if(bar > 1) { int baz = 0; else { int baz = 25.0; //<--------- 4. double and int return bar + baz; // <--- 5. bar and baz not in scope Part 2 Logic Errors Fix 2 logic errors in the sort method below. Use arrows, cross-outs and code to show your fixes: public static void sort(int[] numbers) { for(int i = 0; i < numbers.length - 1; i++) { int min = 0; // <---- equal to i for(int j = i + 1; j < numbers.length; j++) { if(numbers[j] < numbers[min]) { min = j; if(min!= i) { // \/\/\/\/ incorrect swap numbers[min] = numbers[i]; numbers[i] = numbers[min];

3. Part 1 True or False (a) T (!Character.isUpperCase('a')) (b) T (false && true 5!= 2) (c) T.java files contain source code and.class files contain bytecode (d) F the class name in a Java program does not have to match the name of the file that it's defined in (e) T a variable declared in a for loop is available (in scope) until the end of the for loop block (f) F the break statement skips the remainder of the body of a loop and goes to the next iteration of the loop Part 2 What's the Output? Write the output of the following code in the space provided. char ch = 'c'; syso(ch--); syso(ch); c b int x = 10; syso(++x); syso(x); 11 11 Part 3 What's the Output? Draw the output of the code on the left in the grid on the right. If you need to write a space character, just leave a box blank. You do not have to use all of the squares. (3 points) int size = 4; for (int i = size; i > 0; i--) { for (int j = i ; j < size; j++) { System.out.printf("x"); for (int j = 1; j <= i; j++) { System.out.printf("%s", j); 1 2 3 4 x 1 2 3 x x 1 2 x x x 1 System.out.println(); // print newline

4. Short answer questions. (a) What is the output of the following code? Error or no output are possible. int i = 3; double d = i; syso(d); 3.0 (b) What is the output of the following code? Error or no output are possible. double num1 = 7; long num2 = num1;m //<--- ERROR - narrowing syso(num2); (c) What is type casting? Converting from one type to another (d) When is an explicit type cast required? Narrowing conversions (e) In the context of type casting, what is meant by widening a type and narrowing a type? Narrowing going from a type with a greater range of values to smaller range of values Widening going from a type with a smaller range of values to a greater range of values (f) Whys does floating point arithmetic yield results that look slightly inaccurate? Some floating point numbers can't be represented in a finite way in binary (g) Describe one way to mitigate floating point arithmetic issues. Use type with larger range of values, use BigDecimal class, add from smallest to largest (h) Name the two broad categories of types... and give an example of a type in each category. reference an Array, int[][] foo primitive a double, 5.0 (i) Why must you be careful when passing an Array as an argument to a method? What is actually being passed? The value passed is a reference to the Array in memory, so changes made on the Array in the method are seen outside of the method. That is, you can change the incoming Array in place.

Choose 4 of the last 5 questions (#'s 5 through 9) to complete. Specify which question you are skipping by writing DO NOT GRADE in caps above the question. If you do not, I will count the last question as the question you are skipping. 5. Write a complete program, including the class definition,the main method definition, and any necessary imports. The program should output the average of all of the digits in a String provided by the user. (a) ask the user for a String (b) add all of the numbers that are contained in the String; ignore everything else (c) treat each character as a single digit (for example, 12 is a 1 and 2, not a single 12) (d) output the average of all numbers entered with 2 decimal places (e) hint: you can do this with or without unicode code points (f) hint: similar to the BinHexDec.java homework, you can use Character.getNumericValue to get the int value that a single character represents example usage of the method is as follows: Character.getNumericValue('5') // returns 5 (g) hint: alternatively, you can use Integer.parseInt, but you'll have to figure out how to extract a single string from the user input (h) sample user interaction below: Please enter a string: > 12hello3 The average of the digits in the string is 2.00 +1 imports +1 class name +1 main +2 scanner and syso +1 input +2 loop over string (for loop, length of string) +1 use charat +2 check if it's a digit (if statement, correct condition) +1 if it's a digit get numeric value +2 keep track of total and count +2 print out average w/ 2 decimal places import java.util.scanner; public class JustYourAverageQuestion { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.println("Please enter a string:"); String s = input.next(); char ch; int total = 0, count = 0; for(int i = 0; i < s.length(); i++) { ch = s.charat(i); if(character.isdigit(ch)) { total += Character.getNumericValue(ch); count += 1; // watch out for divide by 0! Also, divide by double... if(count > 0) { System.out.printf( "The avg of the digits in the string is %.2f", total / count / 1.0 );

6. Write a method that moves every instance of the character, ch, in an Array of chars to the end of the Array. You do not have to specify the class that this method is in, and you do not have to write a a main method (assume both already exist). public static void movetoend(char[] characters, char ch) (a) move every character that's the same as the second parameter, ch, to the end of the Array (b) maintain the relative order of all of the other characters (c) do this in place; that is... when you create your method, don't return anything, just change the incoming Array (d) the original Array of chars, characters, should remain unchanged if ch is not in it (e) for example, with exclamation point (!) as the second argument: somecharacters = ['!', 'h', 'e', '!', '!', 'y']; // call with exclamation point movetoend(somecharacters, '!'); // prints out ['h', 'e', 'y', '!', '!', '!'] syso(somecharacters); +1 method header (given!) +3 outer loop to repeat process: (1) loop, (3) either loop over all k elements or count swaps / boolean +3 inner loop to go through every position:(1) loop (2) skip last +3 check if char matches: (1) if statement, (2) check if character +3 swap: (1) temp var, (2) swap +2 changes original +1 no return! public static void movetoend1(char[] arr, char ch) { boolean keepsorting = true; while(keepsorting) { keepsorting = false; for(int i = 0; i < arr.length - 1; i++) { if(arr[i] == ch && arr[i + 1]!= ch) { arr[i] = arr[i + 1]; arr[i + 1] = ch; // or //char tmp = arr[i]; //arr[i] = arr[i + 1]; //arr[i + 1] = tmp; keepsorting = true; public static void movetoend2(char[] arr, char ch) { for(int i = arr.length - 1; i >= 0; i--) { if(arr[i] == ch) { for(int j = i; j < arr.length - 1; j++) { // System.out.printf("%s, %s, %s\n", i, j, Arrays.toString(arr)); char temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // System.out.println(Arrays.toString(arr));

public static void movetoend3(char[] arr, char ch) { for(int i = 0; i < arr.length - 1; i++) { int min = i; for(int j = i + 1; j < arr.length; j++) { if(arr[j]!= ch && arr[i] == ch) { min = j; break; if(min!= i) { char temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; 7. Write a method called lastindexof. It will give back the index of the last occurrence of a String in an Array of Strings that comes before the index specified by endindex. Do not use the string method, lastindexof. You do not have to specify the class that this method is in, and you do not have to write a a main method (assume both already exist). public static int lastindexof(string[] haystack, String needle, int endindex) (a) haystack is the String Array to search, needle is the String to search for (b) give back the index of the last occurrence of needle in haystack (String in Array) that appears before endindex (c) give back -1 if needle is not in haystack (String is not found in String Array) or if needle appears at or after endindex (d) assume endindex is a positive integer; method should still work if endindex > length of Array (e) example usage below: String[] words = {"hello", "hi", "what's up?", "hi", "yo"; int a = lastindexof(words, "hi", 4); // a is 3 int b = lastindexof(words, "hi", 3); // b is 1 (before index 3!) int c = lastindexof(words, "hello, 10"); // c is 0 int d = lastindexof(words, "bye", 4); // d is -1 +1 method header +2 handle 0 for end index +2 handle end index larger than length +6 loop backwards, starting at end 1, (2) -- (2) start at end (2) >= 0 or (-3 return 1 st rather than last) +1 set index +1 default to -1 +2 break +1 return public static int lastindexof1(string[] haystack, String needle, int end) { int index = -1; if(end <= 0) { return -1; if(end > haystack.length) { end = haystack.length; for(int i = end - 1; i >= 0; i--) { if(haystack[i].equals(needle)) { index = i; break; return index;

public static int lastindexof2(string[] haystack, String needle, int end) { int index = -1; if(end <= 0) { return -1; if(end > haystack.length) { end = haystack.length; for(int i = 0; i < end; i++) { if(haystack[i].equals(needle)) { index = i; return index; 8. Write a complete program, including the class definition,the main method definition, and any necessary imports. The program should: (a) continually ask the user for a number (b) stop when the number is 0 (c) output the largest number and the smallest number (d) do not count 0 as one of the numbers to consider for largest and smallest (e) negative numbers are allowed (f) do not use an array to do this (g) example interaction (characters after the greater than sign, >, is user input): Give me a number > 7 Give me a number > -3 Give me a number > 12 Give me a number > 0 The largest number is 12 The smallest number is -3 import java.util.scanner; public class MaxMin { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.println("Please enter a number\n> "); int num = input.nextint(); if(num!= 0) { int max = num; int min = num; while(num!= 0) { System.out.println("Please enter a number\n> "); num = input.nextint(); if(num == 0) { break; if(num > max) { max = num; if(num < min) { min = num; System.out.printf("The max is %s, the min is %s", max, min);

9. Write a method called shift, which will give back a new Array by shifting all of the elements in the original Array to the right. You do not have to specify the class that this method is in, and you do not have to write a a main method (assume both already exist). (a) it should have two parameters, an Array of ints, and an int representing an offset (b) it should return a new Array (c) assume that the Array passed in is not empty (d) assume that that the Array will have at least 2 elements, and the offset is at least 0 (e) shift every element to the right for that many positions (f) if an element is shifted out of the Array, move it to the beginning or the end of the Array (g) example output below Array and offset are on the left, Array returned is on the right after --> [1, 2, 3, 4, 5], 1 --> [5, 1, 2, 3, 4] // shift all elements 1 to the right [1, 2, 3, 4, 5], 2 --> [4, 5, 1, 2, 3] // shift all elements 2 to the right [1, 2, 3, 4, 5], 8 --> [3, 4, 5, 1, 2] // shift all elements 8 to the right public static int[] shift(int[] arr, int offset) { int[] shifted = new int[arr.length]; int newindex; // handles shift greater than array length offset = offset % arr.length; for(int i = 0; i < arr.length; i++) { newindex = i - offset; if(newindex < 0) { // handle negative index newindex = arr.length + newindex; shifted[i] = arr[newindex]; return shifted; public static int[] shift2(int[] arr, int offset) { int[] shifted = new int[arr.length]; // handles shift greater than array length offset = offset % arr.length; for(int i = 0; i < shifted.length; i++) { if(i < offset) { shifted[i] = arr[shifted.length - offset]; else { shifted[i] = arr[i - offset]; return shifted; public static int[] shift3(int[] arr, int offset) { int[] shifted = new int[arr.length]; for(int i = 0; i < arr.length; i++) { shifted[(i + offset) % arr.length] = arr[i]; return shifted;