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

Similar documents
COE 211/COE 212 Computer/Engineering Programming. Welcome to Exam II Thursday December 20, 2012

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

COE 212 Engineering Programming. Welcome to Exam II Tuesday November 28, 2018

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

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

COE 212 Engineering Programming. Welcome to Exam II Friday November 27, 2015

COE 212 Engineering Programming. Welcome to Exam I Thursday June 21, Instructor: Dr. Wissam F. Fawaz

COE 212 Engineering Programming. Welcome to Exam II Friday April 20, Instructors: Dr. Dima El-khalil Dr. Wissam F. Fawaz

COE 212 Engineering Programming. Welcome to the Final Exam Thursday December 15, 2016

COE 212 Engineering Programming. Welcome to Exam II Wednesday November 30, 2016

COE 212 Engineering Programming. Welcome to the Final Exam Tuesday December 15, 2015

COE 211 Computer Programming. Welcome to Exam I Tuesday March 13, 2018

I. True/False: (2 points each)

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

CS 102 / CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2010

CS111: PROGRAMMING LANGUAGE II

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

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

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Programming with Java

Java Flow of Control

I. True/False: (2 points each)

COMP 202 Java in one week

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

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

Bjarne Stroustrup. creator of C++

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Spring 2010

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Problem Grade Total

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

Question: Total Points: Score:

Object Oriented Programming. Java-Lecture 1

Term 1 Unit 1 Week 1 Worksheet: Output Solution

COMP-202 Unit 4: Programming with Iterations

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

CSE 1223: Exam II Autumn 2016

COMP 202. Java in one week

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Selection Statements and operators

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) Midterm Examination

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

AP Computer Science A

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

WOSO Source Code (Java)

Selection Statements and operators

CS212 Midterm. 1. Read the following code fragments and answer the questions.

CSCI 1226 Sample Midterm Exam

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Object-Oriented Programming in Java

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Happy Cinco de Mayo!!!!

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

Course Outline. Introduction to java

1 Short Answer (10 Points Each)

COE 211/COE 212 Computer Programming/Engineering Programming. Welcome to The Comprehensive Final Exam Monday June

Question: Total Points: Score:

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

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

Chapter 3. Selections

Faculty of Science COMP-202A - Foundations of Computing (Fall 2015) - All Sections Midterm Examination

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

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

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

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

CS 231 Data Structures and Algorithms, Fall 2016

Question: Total Points: Score:

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

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

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Iterators and File Input

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

CSC 1051 Algorithms and Data Structures I. Final Examination December 17, Name:

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

CSCI 2101 Java Style Guide

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Spring 2009

6 COMPUTER PROGRAMMING

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

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

H212 Introduction to Software Systems Honors

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

Classes Basic Overview

I. True/False: (2 points each)

I. True/False: (2 points each)

AP COMPUTER SCIENCE A

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

CSci 1113 Midterm 1. Name: Student ID:

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

Control Statements: Part 1

CS Computers & Programming I Review_01 Dr. H. Assadipour

Transcription:

1 COE 212 Engineering Programming Welcome to Exam II Monday May 13, 2013 Instructors: Dr. Randa Zakhour Dr. Maurice Khabbaz Dr. George Sakr Dr. Wissam F. Fawaz Name: Solution Key Student ID: Instructions: 1. This exam is Closed Book. Please do not forget to write your name and ID on the first page. 2. You have exactly 140 minutes to complete the seven required problems. 3. Read each problem carefully. If something appears ambiguous, please write your assumptions. 4. Do not get bogged-down on any one problem, you will have to work fast to complete this exam. 5. Put your answers in the space provided only. No other spaces will be graded or even looked at. Good Luck!!

Problem 1: Multiple choice questions (15 minutes) [10 points] For each question, choose the single correct answer. 1) Consider the program segment given below. int i=0; for(i=2; i < 5; i++) System.out.println(i); How many times does the body of the for loop get executed? a. 5 b. 4 c. 3 2) Which of the following is not a Java keyword? a. break b. next c. while 3) Which of the following statements about the conditional operator (?:) is false? a. It is a ternary operator, meaning that it takes three operands b. The first operand is a boolean expression c. The second operand is the resulting value if the condition evaluates to true d. The third operand is the resulting value if the condition evaluates to true 4) Which of the following is a proper way to call the method readdata four times? a. int i=0; while(i<=4) { readdata(); i=i+1; b. int i=0; while(i<4) { readdata(); c. int i = 9; while(i!=4) { readdata(); i--; 5) Which of the following for loop headers results in equivalent numbers of iterations? A. for(int q=1; q<=100; q++) B. for(int q=100; q >=0; q--) C. for(int q=99; q > 0; q -= 9) D. for(int q=990; q > 0; q -= 90) a. A and B b. C and D c. A and B have equivalent iterations and C and D have equivalent iterations d. None of the loops have equivalent iterations 6) Which of the following code choices results in having a value for total that is equivalent to the one computed by the code segment given below? 2

int total = 0; for(int i=0; i<=20; i+=2) total += i; a. int total=0; for(int i=2; i<=20; i++) { total += i; i++; b. int i=2, total = 0; while(i<=20) { if(i%2!= 0) { i++; continue; total+=i; i++; c. All of the above 7) For the code segment below: switch(q) { case 3: System.out.println( banana ); break; case 4: System.out.println( pear ); case 5: System.out.println( grapes ); default: System.out.println( kiwi ); Which of the following values for q will result in kiwi being included in the output? a. Any value different from 3, 4, and 5 b. Anything greater than or equal to 4 c. All of the above 8) Which of the following is false about Math.PI? a. It is a static method defined in the Math class b. It is a static data member of the Math class c. It is a double constant value is false 9) Which of the following is false about static variables? a. Only one copy of a static variable is created b. A static variable cannot be referenced by a static method c. A static variable can be accessed through the name of the class is false 10) Which of the following is not a Scanner method? a. hasnext() b. nextline() c. nexttoken() 3

4 Problem 2: True or false questions (15 minutes) [12 points] 1. The output of the program below is only: Exiting boolean notdone = false; int numberofpieces = 4; if(notdone) if(numberofpieces > 4) { System.out.println( You won ); else { System.out.println( Keep playing ); System.out.println( Exiting ); 2. The following code prints the words: second Done char c = b ; switch(c) { case a : System.out.print( third ); case b : System.out.print( second ); case c : System.out.print( first ); System.out.println( Done ); 3. Consider the code fragment given in the box below, where Piece, Board, and PlayGame are all Java classes. Assume this code fragment is syntactically correct. The code shown in the box below would give the same result as the following statement: thecolor=theboard.getpieceatindex(5).getcircle().getcolor(); Board theboard = new theboard(); int x = 5; Piece apiece = theboard.getpieceatindex(x); Circle acircle = apiece.getcircle(); thecolor = acircle.getcolor(); 4. The following code in Java stores in variable sum the sum of the positive odd integers less than 10. int sum = 0; int x; for(x=-1; x<=10; x+=2) if(x>0) sum += x; 5. The following is a valid declaration in Java: Boolean If = true; 6. The contents of two strings can be compared using either (==) or equals method.

5 7. Any code that can be written with multiple if-else statements can also be written with a switch statement. 8. The output of the program segment given below is: true String last = first ; if(last.equals( first )) System.out.print( last == first ); 9. Consider the following sequence of if statements: if(a < b) if(c < d) if(e < f) answer = e; The series of if statements above can be rewritten as follows: if((a < b) (c < d) (e < f)) answer = e; 10. The output of the segment of code shown below is: sum: 0 int sum=-1; for(sum=0; sum > 0; sum++) sum--; System.out.println( sum: + sum); 11. The following can be used to check to see if the value of variable x is between 10 (inclusive) and 20 (inclusive): if(!(x<10 x>20)) 12. The following code prints the words: Grade is: B int x = 87; char result = A ; System.out.print( Grade is: ); if(x > 90) result = A ; if(x > 80) result = B ; if(x > 70) result = C ; if(x > 60) result = D ; System.out.print(result);

6 Problem 3: Code analysis (20 minutes) [12 points] 1) Assume that an instance of the class called Compare given below is created as follows: Compare compareinstance = new Compare(4); What output is produced by this constructor call? public class Compare { private int x, y; public Compare(int x) { this.x = x; y = 2; first(); // end constructor Compare public void first() { int n = 2; if(second(n, x) && second(y, n)) System.out.print(x +, + y); System.out.print( Done ); // end method first() public void second(int a, int b) { x = b/a; y = y-x; if(x < 3) return true; else return false; // end method second() // end class Compare a. 2,0 Done b. 0,2 Done c. Done 2) Again consider the code for the Compare class given above. What output is produced if the following statement is executed: Compare compareinstance = new Compare(8); a. 2,0 Done b. 0,2 Done c. Done 3) Consider the methods given below. What would be the output if it were called using the statement: method1(35, 10);? a. 0 b. 10 c. 70 d. none of the above public void method1(int x, int y){ int temp = method2(x,y); System.out.print(x*y/temp); public int method2(int x, int y) { while (x!= y) if (x > y) x -= y; else y -= x; return x;

Problem 4: Evaluating java expressions (20 minutes) [12 points] For each of the following code fragments, what is the value of x after the statements are executed? (1) int x=0; for(int i=0; i<3; i++) for( int j=i; j<3; j++) x = x + j; Answer: x = 8 (2) String x = ; boolean notdone = true; if (notdone!= false) x.concat( Not ); x += done ; if(notdone == true) x += End ; Answer: x = NotdoneEnd (3) String x = ; int y = 1; for(int i=0; i<4; i=y-i) { x += i; y += i; Answer: x = 01123 (4) String coolname = "regit *nnhoj", x = ""; int i = 1; while(i <= coolname.length()) { if (coolname.charat(i-1) == ' ') x += 'y'; else x += coolname.charat(coolname.length() - i); i++; Answer: x = johnny tiger (5) String s = new String("this is it"); int x = 0, y = 0; do { if (s.charat(y) == 'i') x++; y += 2; while (y < s.length()); Answer: x = 2 (6) int x=3, i=1; do { x %= i; i++; while(i < 5); x -= i; Answer: x = -5 7

8 Problem 5: Debugging Problem (10 minutes) [6 points] Consider the following program, which is supposed to print out an approximation of calculated according to the following equation, where is a non-negative integer that is entered by the user. 1 import java.util.scanner; 2 public class PiApproximationBuggy { 3 public static void main(string[] args){ 4 Scanner scan = new Scanner(System.in); 5 int N = scan.nextint(); 6 int i = 0; 7 float pi = 0.0; 8 while (i <= N){ 9 if (i % 2 == 0) 10 pi += 1/(2*i+1); 11 else 12 pi -= 1/(2*i+1); 13 i++; 14 pi *= 4; 15 System.out.println( PI = + pi); 16 This program has three bugs. A. Which bug prevents the program from compiling successfully? Identify the line number where the bug appears and give a correct version of this line of code. Line number _7 Correct version: float pi = 0.0f; B. Identify the line numbers where the two logical errors appear and give a correct version of each line of code. Line number _10 Correct version: pi += 1.0/(2*i+1); Line number 12 Correct version: pi -= 1.0/(2*i+1);

9 Problem 6: Method definition (20 minutes) [8 points] You are given below the headers of 3 methods called extractint, isprime, reverseint and containsemirp. Your job is to complete the definition of each one of these methods as per the provided guidelines. 1. extractint()is a method that accepts a String parameter, extracts all the digits contained inside this String and combines them together in the order of their occurrence resulting in a new integer. For example, if the entered String is The 1st 4 prime numbers are 2, 3, 5 and 7. then the method would return the int 142357. public int extractint(string s){ String result = ; char d; String digits = 0123456789 ; for (int i = 0; i < s.length(); i++){ d = s.charat(i); if (digits.indexof(d)!= -1) result += d; return Integer.parseInt(result); 2. isprime() is a method that accepts an int parameter and returns true if the number is prime, i.e. only divisible by itself and by 1. public boolean isprime(int n) { //check if n is a multiple of 2 if (n % 2 == 0) return false; //if not, then just check the odds for(int i = 3; i*i <= n; i+=2) { if(n % i == 0) return false; return true;

10 3. reverseint() is a method that takes as a parameter an int and returns a reversed version of that int. public int reverseint(int original){ int reversed = 0; while (original > 0) reversed = reversed * 10 + original % 10; original /= 10; return reversed; 4. containsemirp() is a method that accepts a String parameter, extracts an int from it using the extractint() method defined earlier and returns true if both the extracted int and its reversal (i.e. the number written backwards obtained through the use of reverseint()) are prime; you should also use the isprime() method defined earlier. For example, if the String is He1ll7o9, then the method will return true since the extracted int 179 and its reversal 971 are both prime numbers. public boolean containsemirp(string s) { int original = extractint(s); int reversed = reverseint(original); return (isprime(original) && isprime(reversed));

11 Problem 7: Coding (40 minutes) [40 points] 1. Write a program named CountChars that reads a String from the user and prints the number of vowels (the letters a, i, e, o and u, regardless of capitalization), the number of consonants (all other alphabetic characters) and the number of all non-alphabetic characters (digits, spaces, punctuation, etc.) found in the string. Sample output Enter a sentence: This is the exam for COE212 Vowel count: 8 Consonant Count: 11 All other characters Count: 8 import java.util.scanner; public class CountChars { public static void main (String[] args) { Scanner scan = new Scanner(System.in); String vowels = aeiouaeiou ; String consonants = bcdfghjklmnopqrstvwxyz + BCDFGHJKLMNOPQRSTVWXYZ ; int countvows = 0, countcons = 0, countother = 0; char c; System.out.println( Enter a string: ); String s = scan.nextline(); for (int j = 0; j < s.length(); j++){ c = s.charat(i); if (vowels.indexof(c) > 0) countvows++; else if (consonants.indexof(c) > 0) countcons++; else countother++; System.out.println( There are + countvows + vowels, + countcons + consonants and + countother + other characters. );

12 2. Write a program called MilesToKM that reads from the user a lower and an upper bound on the number of miles and an integer step size and produces a conversion table to kilometers (note that 1 mile is 1.609 miles) for all values between the lower (inclusive) and upper bound (inclusive), taking steps equal to the step size. Sample output Enter minimum number of miles: 5 Enter maximum number of miles: 30 Enter step size: 10 Miles Kilometers 5 8.045 15 24.135 25 40.225 import java.util.scanner; public class MilesToKM { public static void main (String[] args){ Scanner scan = new Scanner(System.in); System.out.print( Enter a lower bound: ); int lowerbound = scan.nextint(); System.out.print( Enter an upper bound: ); int upperbound = scan.nextint(); System.out.print( Enter a step size: ); int stepsize = scan.nextint(); int kilometers, miles; System.out.println( Miles \t Kilometers ); for (int i = lowerbound; i <= upperbound; i+= lowerbound) { miles = i; kilometers = miles * 1.609; System.out.println(miles + \t + Kilometers);

13 3. Write a program that prints the numbers from 1 to 100 (inclusive). But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". public class FizzBuzz { public static void main (String[] args) { for (int i = 1; i <= 100; i++) { if(i % 3 == 0 && i % 5!=0) System.out.println( Fizz ); if(i % 3!= 0 && i % 5 == 0) System.out.println( Buzz ); if(i % 3 == 0 && i % 5 == 0) System.out.println( FizzBuzz ); if(i % 3!= 0 && i % 5!= 0) System.out.println(i);

14 4. Write a program to read the contents of a text file called test.txt. The program has to write the following to a file called filestats.txt : 1. The total number of words in the file. 2. The number of times the word the (ignoring capitalization) occurred in the file. import java.io.*; import java.util.*; public class ContentStats { public static void main (String[] args) throws IOException{ File f = new File( test.txt ); File g = new File( filestats.txt ); FileWriter fw = new FileWriter(g); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); Scanner filescan = new Scanner(f); int countwords = 0, countthe = 0; while (filescan.hasnext()){ String s = filescan.nextline(); Scanner stringscan = new Scanner(s); while(stringscan.hasnext()){ countwrods++; String word = stringscan.next(); if (word.equalsignorecase( the )) countthe++; pw.println( The number of words is: + countwords); pw.println( The frequency of occurrence of + the word \ the\ is: + countthe); pw.close();