CMPS 12A - Winter 2002 Final Exam A March 16, Name: ID:

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

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

CMPS 12A - Winter 2002 Midterm 2 March 5, Name: ID:

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

University of Palestine. Mid Exam Total Grade: 100

AP CS Unit 3: Control Structures Notes

CS101 Part 2: Practice Questions Algorithms on Arrays, Classes and Objects, String Class, Stack Class

Computer Programming, I. Laboratory Manual. Final Exam Solution

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Spring 2013 COMP Midterm Exam Solutions March 07, 2013

1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 4, 2005

Java Identifiers, Data Types & Variables

Solutions to the 2005 exam

Introduction to Programming Using Java (98-388)

Loops. CSE 114, Computer Science 1 Stony Brook University

CS111: PROGRAMMING LANGUAGE II

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013

COS 126 General Computer Science Spring Written Exam 1

PROGRAMMING FUNDAMENTALS

Programming with Java

NATIONAL UNIVERSITY OF SINGAPORE

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Loops and Expression Types

CompSci 125 Lecture 11

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Spring University of New Mexico CS152 Midterm Exam. Print Your Name

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

ESC101 : Fundamental of Computing

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

About this exam review

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

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

CS 101 Fall 2006 Midterm 3 Name: ID:

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

COMP-202 Unit 4: Programming with Iterations

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015

CS 211: Methods, Memory, Equality

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012

Complexity, General. Standard approach: count the number of primitive operations executed.

CMSC 331 Second Midterm Exam

McGill University School of Computer Science COMP-202A Introduction to Computing 1

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

Chapters 1-4 Summary. Syntax - Java or C? Syntax - Java or C?

Object-Oriented Programming

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Introduction to the Java Basics: Control Flow Statements

Selected Questions from by Nageshwara Rao

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

COE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CSCE 145 Exam 1 Review Answers. This exam totals to 100 points. Follow the instructions. Good luck!

RECURSION (CONTINUED)

AP COMPUTER SCIENCE A

Computational Expression

COS 126 Midterm 1 Written Exam, Fall 2009

Unit 10: Sorting/Searching/Recursion

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

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

1 If you want to store a letter grade (like a course grade) which variable type would you use? a. int b. String c. char d. boolean

H212 Introduction to Software Systems Honors

Introduction to Java & Fundamental Data Types

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

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Multiple Choice Questions (20 questions * 6 points per question = 120 points)

Problem Grade Total

Building Java Programs Chapter 2

Getting started with Java

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

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Reduction & Recursion Overview

CSE 1223: Exam II Autumn 2016

(c) ((!(a && b)) == (!a!b)) TRUE / FALSE. (f) ((!(a b)) == (!a &&!b)) TRUE / FALSE. (g) (!(!a) && (c-d > 0) && (b!b))

Computer Science 1 Ah

Course Outline. Introduction to java

CS 101 Fall 2005 Midterm 2 Name: ID:

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Unit 1 Lesson 4. Introduction to Control Statements

CS 112 Introduction to Programming

CPSC 219 Extra review and solutions

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

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Lecture #6-7 Methods

Lec 3. Compilers, Debugging, Hello World, and Variables

COMPUTER APPLICATIONS

Operators in java Operator operands.

CIS Fall Data Structures Midterm exam 10/16/2012

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

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

YOU ARE ALLOWED TO HAVE ONLY THE FOLLOWING ON YOUR DESK OR WORKTABLE:

Transcription:

CMPS 12A - Winter 2002 Final Exam A March 16, 2002 Name: ID: This is a closed note, closed book exam. Any place where you are asked to write code, you must declare all variables that you use. However, I just want code fragments, you must not write extra code such as a class specification or extraneous print statements. Section I: 20 multiple choice questions [5 points each] For each of the following questions, write the letter of the best answer to the right of the question including, where appropriate, All for All of the above or None for None of the above. 1. The purpose of testing is to make sure your program: All a. Does what it is supposed to do b. Doesn't do what it is not supposed to do c. Does what it used to do 2. Which are all Java keywords: a. int, double, for, array, and break b. continue, break, main, switch, and float c. char, boolean, final, static, and this 3. Which are all valid identifiers: a. Change, 7eleven, m77, foo_bar b. float, a, silly, data? c. main, seven11, a$, test_case, java 4. Which are valid literals a. 5L, 3.7, '\n', "(&(#@" b. 23, 4.5, -0.01, 'abc', "12897a*&)U" c. 5, 4-5, 0.0000004, ';', "Hello" 5. The type of a variable specifies: a. its value b. its name c. the operations that are permitted on it 6. char a = 'a'; a++; a is equal to: a. 'b' b. b c. error A C - array and main are not keywords C - 7eleven and data? are not valid identifiers A - abc and 4-5 are not valid literals, but 5L is C 1

1. 7. Which of the following results in a = = 0 a. int a = 3/4; b. int a = 3.0/4.0; c. double a = 3/4; 2. 8. If a = 1 and b = 23, what does this expression print out if(!( (1+2*a == 3) && (b-23+a!= 1) )) System.out.println("false"); else System.out.println("true"); a. true b. false c. nothing 3. 9. Which list of operators is listed in order of precedence a. +, *, /, = b. ++, *, +, = B c. &&, *, +, % 4. 10. What is the value of the expression (3+4*5-4*5+3) a. 0 b. 12 c. 3 5. 11. Given a = 5 and b = 7, what does this code print out if (b < a) System.out.println("1"); else if (a + 2 == b) System.out.println("2"); else if (a < b) System.out.println("3"); a. 1 b. 2 c. 3 d. both 2 and 3 e. nothing 6. 12. What does this code print out: int a = 'b'; switch(a) { case 'a': System.out.println('1'); case 'b': System.out.println('2'); case 'c': System.out.println('3'); a. 1 b. 2 c. 3 d. both 2 and 3 e. nothing All None - the value is 6=(3 + 20-20 + 3) B - the second if statement is true, and it never gets to the third D - case b is true, but there is no break, so it prints both 2 and 3 B - the expression is true, so it prints out false 2

13. What does this (ugly) code print out: class Foo { Public static void main(string[] args) { int[] foo = {3, 5, 7; if (foo[0] > foo[1]) swap(foo, 0, 1); if (foo[2] < foo[1]) swap(foo, 1, 2); if (foo[0] > foo[1]) swap(foo, 0, 1); System.out.println(foo[0] + " " + foo[1] + " " + foo[2]); void swap(int[] a, int b, int c) { int temp = a[b]; a[b] = a[c]; a[c] = temp; a. 3 5 7 b. 7 5 3 c. 15 A - the tests are false, so nothing happens to the array 14. In for loops: a. The initialization expression is executed zero or more times b. The boolean expression is executed zero or more times C c. The update expression is executed zero or more times 15. What does this print out: for(int i = 2; i < 100-i; i = i*i - i/2) System.out.print(i + " "); a. 2 4 8 16 32 b. 2 3 7.5 56.25 None c. 2 3 7 42 16. Which is true? a. return(a,b); can be used to return two values None b. primitive types are call-by-reference c. the scope of an object is the class that defines its type 17. What does this method compute? public int foo(int n) { if(n <= 1) return 1; else return 5 + foo(n-1); a. foo(n) = the nth fibonacci number b. foo(n) = 5*n c. foo(n) = n 5 d. foo(n) = 5 n None - it computes 5n-4 18. Method overloading is when you write a method a. That has too much code in it b. That has the same name and parameters as another method in the class c. That has the same name but different parameters than another method in the classl C 3

19. Arrays: a. Once you have created an array, you can change its size b. The last element of an array of size n is at index n c. 2D arrays are twice as big as 1D arrays None 20. Public vs. Private: a. Public methods can only access public data elements b. Private data elements are accessible by methods in the same package c. By default, all data elements are private None Section II: 9 questions 1. [10 points] Write code fragments to do the following: a) Given ints x, y, and z, add x and y and store the result in z. z = x + y; b) Given a float called celsius_temp, print out "Within range" or "Out of range" depending on whether or not celsius_temp is greater than or equal to 0 and less than 100. if(celsius_temp >= 0 && celsius_temp < 100) System.out.print( Within range ); else System.out.print( Out of range ); c) Given an char c, print out "A", "B.", or "C." depending on the value of c ( a, b, or c ). Use a switch statement for your solution. switch(c) { case a : System.out.print( A ); break; case b : System.out.print( B ); break; case c : System.out.print( C ); break; 4

2. [10 points] Write a main() method that reads in four integers and prints out yes if the numbers were entered in increasing order and prints out no otherwise. public static void main(string[ ] args) { int[ ] foo = new int[4]; for(int i = 0; i < foo.length; i++) { foo[i] = Console.in.readInt(); if(foo[0] < foo[1] && foo[1] < foo[2] && foo[2] < foo[3]) System.out.print( yes ); else System.out.print( no ); 3. [10 points] Write a method that tests whether the formula a 2 + b 2 = c 2 is true for three integers passed as parameters and returns the result of this test. Such a triple is a Pythagorean triple and forms a right-angle triangle with these numbers as the lengths of its sides. public static boolean testpythagorean(int a, int b, int c) { return c*c == a*a + b*b; 5

4. [10 points] Write a method called divisors() that takes as a parameter an int n, and uses a for loop to find and print out the integer divisors of n (i.e. all integers that evenly divide into n). Do not use any other methods - compute the divisors yourself. divisors() should return the number of integer divisors of n. public int divisors(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) { System.out.println(i); count++; return count; 5. [10 points] One way to calculate square root of a number n is to guess that the root is some number x between 0 and n, and then repeatedly refine your guess x by setting x equal to the average of x and n / x, until the difference between your x 2 and n is very small. Show how you could implement square_root() using this method to return the square root to within.0001 of a number passed as a parameter. public double square_root(double n) { double x = n/2; while(math.abs(n - x*x )> 0.0001) { x = (n/x + x) / 2; return x; 6

6. [10 points] Write a method called paircount() that takes as a parameter an array of characters and returns a count of the number of pairs of characters (consecutive elements of the array with the same value). public int paircount(char[ ] a) { int count = 0; for(int i = 0; i < (a.length-1); i++) { if(a[i] == a[i+1]) count++; return count; 7. [10 points] Show how you would implement the recursive method rec(), defined as follows: rec(0) = 37 rec(1) = 73 rec(n) = n /(rec(n-1) + rec(n-2)) public static int rec(int n) { if(n == 0) return 37; if(n == 1) return 73; return n / (rec(n-1) + rec(n-2)); 7

8. [20 points] Implement a class called Coordinate that allows the user to store an (x, y) coordinate. Provide: a) A constructor that sets both variables to values passed as parameters. b) An instance method called add() that adds two Coordinates and returns a new coordinate containing the sum of the other two. c) A static method called distance() that returns the distance between two Coordinates. Recall that the distance between two coordinates (x 1, y 1 ) and (x 2, y 2 ) is ( x 2 x 1 ) 2 + ( y 2 y 1 ) 2. You may use the method Math.sqrt() to calculate the square root. d) Some test code that declares two Coordinates A and B and adds them and stores the result in C. class Coordinate { private double x; private double y; Coordinate(double xval, double yval) { x = xval; y = yval; public Coordinate add(coordinate c) { return new Coordinate(x+c.x, y+c.y); public static double distance(coordinate c1, Coordinate c2) { return Math.sqrt((c2.x-c1.x)*(c2.x-c1.x) + (c2.y-c1.y)*(c2.y-c1.y)); Test code: Coordinate A = (1,1); Coordinate B = (2,2); Coordinate C = A.add(B); 8

9. [10 points] A stack is an abstract data structure that holds data objects of a given type. Stacks support two operations: push(), which takes a data element and puts it on the stack, and pop(), which takes a data element off of the stack and returns it. Stacks function as though the data elements are stacked in a pile. When a new element is pushed onto the stack, it goes on top of the pile. When an elements is popped from the stack, it is taken from the top of the pile. One simple way to implement a stack is to use an array to hold the data elements. A counter can keep track of how many elements are in the stack, and to find the top of the stack to add or remove data elements. When a data element is pushed onto the stack, it is put in the right spot in the array and the counter is incrememented. When a data element is popped from the stack, the counter is decremented and the appropriate item in the array is returned. a) Write the data definitions for the Stack class, assuming that the data elements are characters. b) Write a constructor for the Stack class c) Write the push() method d) Write the pop() method class Stack { private char[ ] pile; private int count; Stack() { pile = new char[100]; count = 0; public boolean push(char c) { if(count < pile.length) { pile[count++] = c; return true; return false; public char pop() { if(c > 0) return pile[--count]; return -1; 9

CMPS 12A - Winter 2002 Final Exam A March 16, 2002 Name: ID: This is a closed note, closed book exam. Any place where you are asked to write code, you must declare all variables that you use. However, I just want code fragments, you must not write extra code such as a class specification or extraneous print statements. Section I: 20 multiple choice questions [5 points each] For each of the following questions, write the letter of the best answer to the right of the question including, where appropriate, All for All of the above or None for None of the above. 1. The purpose of testing is to make sure your program: All a. Does what it is supposed to do b. Doesn't do what it is not supposed to do c. Does what it used to do 2. Which are all Java keywords: a. int, double, for, array, and break b. continue, break, main, switch, and float c. char, boolean, final, static, and this 3. Which are all valid identifiers: a. Change, 7eleven, m77, foo_bar b. float, a, silly, data? c. main, seven11, a$, test_case, java 4. Which are valid literals a. 5L, 3.7, '\n', "(&(#@" b. 23, 4.5, -0.01, 'abc', "12897a*&)U" c. 5, 4-5, 0.0000004, ';', "Hello" 5. The type of a variable specifies: a. its value b. its name c. the operations that are permitted on it 6. char a = 'a'; a++; a is equal to: a. 'b' b. b c. error A C - array and main are not keywords C - 7eleven and data? are not valid identifiers A - abc and 4-5 are not valid literals, but 5L is C 1

1. 7. Which of the following results in a = = 0 a. int a = 3/4; b. int a = 3.0/4.0; c. double a = 3/4; 2. 8. If a = 1 and b = 23, what does this expression print out if(!( (1+2*a == 3) && (b-23+a!= 1) )) System.out.println("false"); else System.out.println("true"); a. true b. false c. nothing 3. 9. Which list of operators is listed in order of precedence a. +, *, /, = b. ++, *, +, = B c. &&, *, +, % 4. 10. What is the value of the expression (3+4*5-4*5+3) a. 0 b. 12 c. 3 5. 11. Given a = 5 and b = 7, what does this code print out if (b < a) System.out.println("1"); else if (a + 2 == b) System.out.println("2"); else if (a < b) System.out.println("3"); a. 1 b. 2 c. 3 d. both 2 and 3 e. nothing 6. 12. What does this code print out: int a = 'b'; switch(a) { case 'a': System.out.println('1'); case 'b': System.out.println('2'); case 'c': System.out.println('3'); a. 1 b. 2 c. 3 d. both 2 and 3 e. nothing All None - the value is 6=(3 + 20-20 + 3) B - the second if statement is true, and it never gets to the third D - case b is true, but there is no break, so it prints both 2 and 3 B - the expression is true, so it prints out false 2

13. What does this (ugly) code print out: class Foo { Public static void main(string[] args) { int[] foo = {3, 5, 7; if (foo[0] > foo[1]) swap(foo, 0, 1); if (foo[2] < foo[1]) swap(foo, 1, 2); if (foo[0] > foo[1]) swap(foo, 0, 1); System.out.println(foo[0] + " " + foo[1] + " " + foo[2]); void swap(int[] a, int b, int c) { int temp = a[b]; a[b] = a[c]; a[c] = temp; a. 3 5 7 b. 7 5 3 c. 15 A - the tests are false, so nothing happens to the array 14. In for loops: a. The initialization expression is executed zero or more times b. The boolean expression is executed zero or more times C c. The update expression is executed zero or more times 15. What does this print out: for(int i = 2; i < 100-i; i = i*i - i/2) System.out.print(i + " "); a. 2 4 8 16 32 b. 2 3 7.5 56.25 None c. 2 3 7 42 16. Which is true? a. return(a,b); can be used to return two values None b. primitive types are call-by-reference c. the scope of an object is the class that defines its type 17. What does this method compute? public int foo(int n) { if(n <= 1) return 1; else return 5 + foo(n-1); a. foo(n) = the nth fibonacci number b. foo(n) = 5*n c. foo(n) = n 5 d. foo(n) = 5 n None - it computes 5n-4 18. Method overloading is when you write a method a. That has too much code in it b. That has the same name and parameters as another method in the class c. That has the same name but different parameters than another method in the classl C 3

19. Arrays: a. Once you have created an array, you can change its size b. The last element of an array of size n is at index n c. 2D arrays are twice as big as 1D arrays None 20. Public vs. Private: a. Public methods can only access public data elements b. Private data elements are accessible by methods in the same package c. By default, all data elements are private None Section II: 9 questions 1. [10 points] Write code fragments to do the following: a) Given ints x, y, and z, add x and y and store the result in z. z = x + y; b) Given a float called celsius_temp, print out "Within range" or "Out of range" depending on whether or not celsius_temp is greater than or equal to 0 and less than 100. if(celsius_temp >= 0 && celsius_temp < 100) System.out.print( Within range ); else System.out.print( Out of range ); c) Given an char c, print out "A", "B.", or "C." depending on the value of c ( a, b, or c ). Use a switch statement for your solution. switch(c) { case a : System.out.print( A ); break; case b : System.out.print( B ); break; case c : System.out.print( C ); break; 4

2. [10 points] Write a main() method that reads in four integers and prints out yes if the numbers were entered in increasing order and prints out no otherwise. public static void main(string[ ] args) { int[ ] foo = new int[4]; for(int i = 0; i < foo.length; i++) { foo[i] = Console.in.readInt(); if(foo[0] < foo[1] && foo[1] < foo[2] && foo[2] < foo[3]) System.out.print( yes ); else System.out.print( no ); 3. [10 points] Write a method that tests whether the formula a 2 + b 2 = c 2 is true for three integers passed as parameters and returns the result of this test. Such a triple is a Pythagorean triple and forms a right-angle triangle with these numbers as the lengths of its sides. public static boolean testpythagorean(int a, int b, int c) { return c*c == a*a + b*b; 5

4. [10 points] Write a method called divisors() that takes as a parameter an int n, and uses a for loop to find and print out the integer divisors of n (i.e. all integers that evenly divide into n). Do not use any other methods - compute the divisors yourself. divisors() should return the number of integer divisors of n. public int divisors(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) { System.out.println(i); count++; return count; 5. [10 points] One way to calculate square root of a number n is to guess that the root is some number x between 0 and n, and then repeatedly refine your guess x by setting x equal to the average of x and n / x, until the difference between your x 2 and n is very small. Show how you could implement square_root() using this method to return the square root to within.0001 of a number passed as a parameter. public double square_root(double n) { double x = n/2; while(math.abs(n - x*x )> 0.0001) { x = (n/x + x) / 2; return x; 6

6. [10 points] Write a method called paircount() that takes as a parameter an array of characters and returns a count of the number of pairs of characters (consecutive elements of the array with the same value). public int paircount(char[ ] a) { int count = 0; for(int i = 0; i < (a.length-1); i++) { if(a[i] == a[i+1]) count++; return count; 7. [10 points] Show how you would implement the recursive method rec(), defined as follows: rec(0) = 37 rec(1) = 73 rec(n) = n /(rec(n-1) + rec(n-2)) public static int rec(int n) { if(n == 0) return 37; if(n == 1) return 73; return n / (rec(n-1) + rec(n-2)); 7

8. [20 points] Implement a class called Coordinate that allows the user to store an (x, y) coordinate. Provide: a) A constructor that sets both variables to values passed as parameters. b) An instance method called add() that adds two Coordinates and returns a new coordinate containing the sum of the other two. c) A static method called distance() that returns the distance between two Coordinates. Recall that the distance between two coordinates (x 1, y 1 ) and (x 2, y 2 ) is ( x 2 x 1 ) 2 + ( y 2 y 1 ) 2. You may use the method Math.sqrt() to calculate the square root. d) Some test code that declares two Coordinates A and B and adds them and stores the result in C. class Coordinate { private double x; private double y; Coordinate(double xval, double yval) { x = xval; y = yval; public Coordinate add(coordinate c) { return new Coordinate(x+c.x, y+c.y); public static double distance(coordinate c1, Coordinate c2) { return Math.sqrt((c2.x-c1.x)*(c2.x-c1.x) + (c2.y-c1.y)*(c2.y-c1.y)); Test code: Coordinate A = (1,1); Coordinate B = (2,2); Coordinate C = A.add(B); 8

9. [10 points] A stack is an abstract data structure that holds data objects of a given type. Stacks support two operations: push(), which takes a data element and puts it on the stack, and pop(), which takes a data element off of the stack and returns it. Stacks function as though the data elements are stacked in a pile. When a new element is pushed onto the stack, it goes on top of the pile. When an elements is popped from the stack, it is taken from the top of the pile. One simple way to implement a stack is to use an array to hold the data elements. A counter can keep track of how many elements are in the stack, and to find the top of the stack to add or remove data elements. When a data element is pushed onto the stack, it is put in the right spot in the array and the counter is incrememented. When a data element is popped from the stack, the counter is decremented and the appropriate item in the array is returned. a) Write the data definitions for the Stack class, assuming that the data elements are characters. b) Write a constructor for the Stack class c) Write the push() method d) Write the pop() method class Stack { private char[ ] pile; private int count; Stack() { pile = new char[100]; count = 0; public boolean push(char c) { if(count < pile.length) { pile[count++] = c; return true; return false; public char pop() { if(c > 0) return pile[--count]; return -1; 9

CMPS 12A - Winter 2002 Final Exam A March 16, 2002 Name: ID: This is a closed note, closed book exam. Any place where you are asked to write code, you must declare all variables that you use. However, I just want code fragments, you must not write extra code such as a class specification or extraneous print statements. Section I: 20 multiple choice questions [5 points each] For each of the following questions, write the letter of the best answer to the right of the question including, where appropriate, All for All of the above or None for None of the above. 1. The purpose of testing is to make sure your program: All a. Does what it is supposed to do b. Doesn't do what it is not supposed to do c. Does what it used to do 2. Which are all Java keywords: a. int, double, for, array, and break b. continue, break, main, switch, and float c. char, boolean, final, static, and this 3. Which are all valid identifiers: a. Change, 7eleven, m77, foo_bar b. float, a, silly, data? c. main, seven11, a$, test_case, java 4. Which are valid literals a. 5L, 3.7, '\n', "(&(#@" b. 23, 4.5, -0.01, 'abc', "12897a*&)U" c. 5, 4-5, 0.0000004, ';', "Hello" 5. The type of a variable specifies: a. its value b. its name c. the operations that are permitted on it 6. char a = 'a'; a++; a is equal to: a. 'b' b. b c. error A C - array and main are not keywords C - 7eleven and data? are not valid identifiers A - abc and 4-5 are not valid literals, but 5L is C 1

1. 7. Which of the following results in a = = 0 a. int a = 3/4; b. int a = 3.0/4.0; c. double a = 3/4; 2. 8. If a = 1 and b = 23, what does this expression print out if(!( (1+2*a == 3) && (b-23+a!= 1) )) System.out.println("false"); else System.out.println("true"); a. true b. false c. nothing 3. 9. Which list of operators is listed in order of precedence a. +, *, /, = b. ++, *, +, = B c. &&, *, +, % 4. 10. What is the value of the expression (3+4*5-4*5+3) a. 0 b. 12 c. 3 5. 11. Given a = 5 and b = 7, what does this code print out if (b < a) System.out.println("1"); else if (a + 2 == b) System.out.println("2"); else if (a < b) System.out.println("3"); a. 1 b. 2 c. 3 d. both 2 and 3 e. nothing 6. 12. What does this code print out: int a = 'b'; switch(a) { case 'a': System.out.println('1'); case 'b': System.out.println('2'); case 'c': System.out.println('3'); a. 1 b. 2 c. 3 d. both 2 and 3 e. nothing All None - the value is 6=(3 + 20-20 + 3) B - the second if statement is true, and it never gets to the third D - case b is true, but there is no break, so it prints both 2 and 3 B - the expression is true, so it prints out false 2

13. What does this (ugly) code print out: class Foo { Public static void main(string[] args) { int[] foo = {3, 5, 7; if (foo[0] > foo[1]) swap(foo, 0, 1); if (foo[2] < foo[1]) swap(foo, 1, 2); if (foo[0] > foo[1]) swap(foo, 0, 1); System.out.println(foo[0] + " " + foo[1] + " " + foo[2]); void swap(int[] a, int b, int c) { int temp = a[b]; a[b] = a[c]; a[c] = temp; a. 3 5 7 b. 7 5 3 c. 15 A - the tests are false, so nothing happens to the array 14. In for loops: a. The initialization expression is executed zero or more times b. The boolean expression is executed zero or more times C c. The update expression is executed zero or more times 15. What does this print out: for(int i = 2; i < 100-i; i = i*i - i/2) System.out.print(i + " "); a. 2 4 8 16 32 b. 2 3 7.5 56.25 None c. 2 3 7 42 16. Which is true? a. return(a,b); can be used to return two values None b. primitive types are call-by-reference c. the scope of an object is the class that defines its type 17. What does this method compute? public int foo(int n) { if(n <= 1) return 1; else return 5 + foo(n-1); a. foo(n) = the nth fibonacci number b. foo(n) = 5*n c. foo(n) = n 5 d. foo(n) = 5 n None - it computes 5n-4 18. Method overloading is when you write a method a. That has too much code in it b. That has the same name and parameters as another method in the class c. That has the same name but different parameters than another method in the classl C 3

19. Arrays: a. Once you have created an array, you can change its size b. The last element of an array of size n is at index n c. 2D arrays are twice as big as 1D arrays None 20. Public vs. Private: a. Public methods can only access public data elements b. Private data elements are accessible by methods in the same package c. By default, all data elements are private None Section II: 9 questions 1. [10 points] Write code fragments to do the following: a) Given ints x, y, and z, add x and y and store the result in z. z = x + y; b) Given a float called celsius_temp, print out "Within range" or "Out of range" depending on whether or not celsius_temp is greater than or equal to 0 and less than 100. if(celsius_temp >= 0 && celsius_temp < 100) System.out.print( Within range ); else System.out.print( Out of range ); c) Given an char c, print out "A", "B.", or "C." depending on the value of c ( a, b, or c ). Use a switch statement for your solution. switch(c) { case a : System.out.print( A ); break; case b : System.out.print( B ); break; case c : System.out.print( C ); break; 4

2. [10 points] Write a main() method that reads in four integers and prints out yes if the numbers were entered in increasing order and prints out no otherwise. public static void main(string[ ] args) { int[ ] foo = new int[4]; for(int i = 0; i < foo.length; i++) { foo[i] = Console.in.readInt(); if(foo[0] < foo[1] && foo[1] < foo[2] && foo[2] < foo[3]) System.out.print( yes ); else System.out.print( no ); 3. [10 points] Write a method that tests whether the formula a 2 + b 2 = c 2 is true for three integers passed as parameters and returns the result of this test. Such a triple is a Pythagorean triple and forms a right-angle triangle with these numbers as the lengths of its sides. public static boolean testpythagorean(int a, int b, int c) { return c*c == a*a + b*b; 5

4. [10 points] Write a method called divisors() that takes as a parameter an int n, and uses a for loop to find and print out the integer divisors of n (i.e. all integers that evenly divide into n). Do not use any other methods - compute the divisors yourself. divisors() should return the number of integer divisors of n. public int divisors(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) { System.out.println(i); count++; return count; 5. [10 points] One way to calculate square root of a number n is to guess that the root is some number x between 0 and n, and then repeatedly refine your guess x by setting x equal to the average of x and n / x, until the difference between your x 2 and n is very small. Show how you could implement square_root() using this method to return the square root to within.0001 of a number passed as a parameter. public double square_root(double n) { double x = n/2; while(math.abs(n - x*x )> 0.0001) { x = (n/x + x) / 2; return x; 6

6. [10 points] Write a method called paircount() that takes as a parameter an array of characters and returns a count of the number of pairs of characters (consecutive elements of the array with the same value). public int paircount(char[ ] a) { int count = 0; for(int i = 0; i < (a.length-1); i++) { if(a[i] == a[i+1]) count++; return count; 7. [10 points] Show how you would implement the recursive method rec(), defined as follows: rec(0) = 37 rec(1) = 73 rec(n) = n /(rec(n-1) + rec(n-2)) public static int rec(int n) { if(n == 0) return 37; if(n == 1) return 73; return n / (rec(n-1) + rec(n-2)); 7

8. [20 points] Implement a class called Coordinate that allows the user to store an (x, y) coordinate. Provide: a) A constructor that sets both variables to values passed as parameters. b) An instance method called add() that adds two Coordinates and returns a new coordinate containing the sum of the other two. c) A static method called distance() that returns the distance between two Coordinates. Recall that the distance between two coordinates (x 1, y 1 ) and (x 2, y 2 ) is ( x 2 x 1 ) 2 + ( y 2 y 1 ) 2. You may use the method Math.sqrt() to calculate the square root. d) Some test code that declares two Coordinates A and B and adds them and stores the result in C. class Coordinate { private double x; private double y; Coordinate(double xval, double yval) { x = xval; y = yval; public Coordinate add(coordinate c) { return new Coordinate(x+c.x, y+c.y); public static double distance(coordinate c1, Coordinate c2) { return Math.sqrt((c2.x-c1.x)*(c2.x-c1.x) + (c2.y-c1.y)*(c2.y-c1.y)); Test code: Coordinate A = (1,1); Coordinate B = (2,2); Coordinate C = A.add(B); 8

9. [10 points] A stack is an abstract data structure that holds data objects of a given type. Stacks support two operations: push(), which takes a data element and puts it on the stack, and pop(), which takes a data element off of the stack and returns it. Stacks function as though the data elements are stacked in a pile. When a new element is pushed onto the stack, it goes on top of the pile. When an elements is popped from the stack, it is taken from the top of the pile. One simple way to implement a stack is to use an array to hold the data elements. A counter can keep track of how many elements are in the stack, and to find the top of the stack to add or remove data elements. When a data element is pushed onto the stack, it is put in the right spot in the array and the counter is incrememented. When a data element is popped from the stack, the counter is decremented and the appropriate item in the array is returned. a) Write the data definitions for the Stack class, assuming that the data elements are characters. b) Write a constructor for the Stack class c) Write the push() method d) Write the pop() method class Stack { private char[ ] pile; private int count; Stack() { pile = new char[100]; count = 0; public boolean push(char c) { if(count < pile.length) { pile[count++] = c; return true; return false; public char pop() { if(c > 0) return pile[--count]; return -1; 9