CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

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

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name:

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

Data Representation and Applets

Applets and the Graphics class

Data Representation and Applets

Data Representation and Applets

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I

Algorithms and Conditionals

Chapter 2 Exercise Solutions

Data Representation and Applets

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

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

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

Chapter 3. Selections

Using Classes and Objects


Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

Happy Cinco de Mayo!!!!

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

Using Classes and Objects

Using Java Classes Fall 2018 Margaret Reid-Miller

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Objects and Primitive Data

Using Classes and Objects

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

Happy Cinco de Mayo!!!!

Java I/O and Control Structures Algorithms in everyday life

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

Primitive Data Types: Intro

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

CSC 1051 Data Structures and Algorithms I

Practice Midterm 1 Answer Key

Java I/O and Control Structures

AP CS Unit 3: Control Structures Notes

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

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

AP Computer Science Unit 1. Programs

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

Chapter. Let's explore some other fundamental programming concepts

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Introduction to Computer Science Unit 2. Notes

TWO-DIMENSIONAL FIGURES

CSC 1051 Data Structures and Algorithms I

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Chapter 2: Objects and Primitive Data

Data Representation Classes, and the Java API

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Full file at

Lecture Set 2: Starting Java

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

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

We now start exploring some key elements of the Java programming language and ways of performing I/O

Lecture Set 2: Starting Java

Selection Statements and operators

Selection and Repetition Revisited

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

CS 312 Midterm 1 Spring 2013

2: Basics of Java Programming

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

AP Computer Science Unit 1. Writing Programs Using BlueJ

CSCI 135 Midterm Fundamentals of Computer Science I Fall 2011

Graphical User Interfaces

Java Classes: Math, Integer A C S L E C T U R E 8

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

Methods CSC 121 Fall 2016 Howard Rosenthal

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Selection Statements and operators

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

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

Practice Midterm 1. Problem Points Score TOTAL 50

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

Introduction to Computer Science Unit 2. Notes

What did we talk about last time? Examples switch statements

Computer Science 145 Midterm 1 Fall 2016

CS1004: Intro to CS in Java, Spring 2005

Introduction to Arrays

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Methods CSC 121 Spring 2017 Howard Rosenthal

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Introduction to Java Unit 1. Using BlueJ to Write Programs

Graphical User Interfaces

Introduction to Java Applications

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

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

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

CS111: PROGRAMMING LANGUAGE II

Selection and Repetition

Transcription:

CSC 1051 Algorithms and Data Structures I Midterm Examination October 7, 2013 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces provided. If you make a mistake or for some other reason need more space, please use the back of pages or the extra blank page at the end and clearly indicate where the answer can be found. Good luck!

1. [ /10] Short answer questions. a) If a language uses 30 unique letters and symbols, how many bits would be needed to store each character of a document? Explain. b) Give examples of two types of Java comments and explain the differences between them. c) Java is case sensitive. What does that mean? d) What is a variable declaration? Give two examples. e) Why are widening conversions safer than narrowing conversions?

2. [ /10] List the following items with respect to the code below: a) a boolean expression b) all variable identifiers for integers c) all variables identifiers for floating point numbers d) all constant identifiers (any type of value) e) a comment f) an input statement g) an output statement h) a statement that is executed conditionally // Wages.java calculates wages with overtime. //******************************************************************** import java.text.numberformat; import java.util.scanner; public class Wages public static void main (String[] args) final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours in a work week Scanner scan = new Scanner (System.in); double pay = 0.0; System.out.print ("Enter the number of hours worked: "); int hours = scan.nextint(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-standard) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println (""Gross earnings: " + fmt.format(pay));

3. [ /10] Short answer questions. a) [7 points] Suppose you want to draw a yellow circle inside a green square, positioned at the top left corner of your applet. the square should have sides of length 80 pixels and the circle should have a smaller diameter, 40 pixels. As usual, the paint method is passed a Graphics object called page. Here is a start finish writing the Java code: page.setcolor(color.green); // finish writing this code page.fillrect( b) [3 points] if (a>0) if (b<0) x = x + 5; else if (a>5) x = x + 4; else x = x + 3; else x = x + 2; If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed?

4. [ /10] What gets printed by the following program? public class Mystery public static void main(string args[]) String str = midterm ; int left = 0; int right = str.length() - 1; while (str.charat(left) == str.charat(right) && left < right) System.out.println( Yes! ); System.out.println( left = + left); System.out.println( right = + right); System.out.println( The characters are + str.charat(left) + str.charat(right)); left ++; right --; Output System.out.println( Out of the loop now ); System.out.println( left = + left); System.out.println( right = + right); System.out.println( The characters are + str.charat(left) + str.charat(right));

5. [ /10] Recall that the Random class is part of the java.util package. a) Write an import declaration for the Random class b) Write some code to declare and instantiate an object of the Random class (call the object reference rand). c) Write some code that uses the object rand, above, to generate pseudorandom numbers in the following specified ranges (including the endpoints): 0 to 9 1 to 100 0 to.4999999 (i.e., as close to 0.5 as it gets, but not including 0.5)

6. [ /10] Short answer questions. For each of the following expressions, indicate the order in which the operations are performed by writing a number beneath each operator. a / b d * e + f a / (b + c) / e f For each of the following Java code fragments, mark the error and show how to correct it. What do you need to do to fix it so that it works as appears to be intended? a) if (value = 0) System.out.print ("Right!"); b) if (value > 0); System.out.print ("Right!"); c) if (value > 0) System.out.print ("Right!"); System.out.println( value is positive );

7. [ /10] Given the following declarations: int iresult, num1= 5, num2 = 2; double fresult, val1 = 8.0; Show the results if the following assignment statements are executed (or write ERROR if the statement causes an error). The resulting value of the expression that will be stored in the variable and its type The kind of data conversion, i.e., one of the following: o none (no data conversion of any kind) o automatic (through assignment or mixed type experession) o cast (specify whether widening or narrowing) Note that there may be none or more than one conversion be sure to list all, if any FOR EACH ANWER WRITE AN EXPLANATION Source code value stored in variable Type of value Data Conversion(s) iresult = val1; fresult = num1 / num2; iresult = (int) val1 / num2; fresult =(double) num1 / num2;

8. [ / 10] What gets printed? Please show output as it will appear, or indicate NO OUTPUT, or show some of the output followed by INFINITE LOOP. int a = 0; while (a<6) System.out.println(a); a++; Output: int a = 0; while (a<6) System.out.println(a); a++; Output: // (same as previous one, only no braces) int a = 5; Output: while (a > 5) System.out.println(a); a = a - 2; int a = 1; while (a >= 1) System.out.println(2*a); a++; Output:

9. ( / 10) Construct an algorithm that inputs several positive integers in the range 1 100 from the user, terminated with a - 1 (sentinel value). The algorithm should print the numbers entered and determine and print the minimum value. After the minimum is printed, print a goodbye message. You can assume that the numbers entered will be between 1 and 100 (except for the terminating - 1), so you do not need to check for mistakes in the input. Note: Be careful not to process the terminating - 1, i.e., make sure your algorithm does not produce - 1 as the minimum. Example: If the numbers 25 86 13 54-1 are entered as input, the algorithm should print: 25 86 13 54 Min = 13 Goodbye [Note that the terminating - 1 should NOT be printed.] Directions: Write your algorithm by rearranging and structuring elements chosen from the list below, using indentation to show structure. Do not use anything else and note that not all of these are needed, but you may use one of them more than once, if necessary. input num input min num = 0 min = 0 min = 100 num = 100 num = num + 1 min= num num = min if (num < min) if (num > min) if (num!= - 1) if (num!= min) else while (num < min) while (num > min) while (num!= - 1) while (num!= min) print Min = min print Min = num print num print Goodbye

10. ( / 10) Write a complete Java program that asks the user to input his/her age and then calculates and prints the user s age in days (ignore leap years assume all years have 365 days). Be sure to write a complete Java program, including class definition, variable and constant declarations, as appropriate, comments, and proper indentation, to make it readable.

//******************************************************************** // Einstein.java Author: Lewis/Loftus // // Demonstrates a basic applet. //******************************************************************** import javax.swing.japplet; import java.awt.*; public class Einstein extends JApplet //----------------------------------------------------------------- // Draws a quotation by Albert Einstein among some shapes. //----------------------------------------------------------------- public void paint (Graphics page) page.drawrect (50, 50, 40, 40); // square page.drawrect (60, 80, 225, 30); // rectangle page.drawoval (75, 65, 20, 20); // circle page.drawline (35, 60, 100, 120); // line page.drawstring ("Out of clutter, find simplicity.", 110, 70); page.drawstring ("-- Albert Einstein", 130, 100); Drawing a Line 20 45 Y 10 150 Start x y page.drawline (10, 20, 150, 45); or End x y page.drawline (150, 45, 10, 20); X CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Drawing a Rectangle Drawing an Oval 50 X 175 X 20 20 40 80 Y 100 Start x y Width Height Y bounding rectangle 50 page.drawrect (50, 20, 100, 40); page.drawoval (175, 20, 50, 80); CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Drawing an Arc An arc is defined by an oval, a start angle, and an arc angle: Filled vs unfilled shapes Instead of using drawrect(), drawoval() etc, we can use fillrect(), filloval() etc We can set the color using setcolor() See Snowman.java See also Snowman applet on a webpage CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University 1

Some methods of the String class boolean isempty() Returns true if, and only if, length() is 0. char charat(int index) Returns the char value at the specified index. int length() Returns the length of this string. String touppercase() Converts all of the characters in this String to lower case using the rules of the default locale. Some methods of the Random class double nextdouble() Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 int nextint() Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. int nextint(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. Some methods of the Math class static double abs(double a) Returns the absolute value of a double value. static double cos(double a) Returns the trigonometric cosine of an angle. static double pow(double a, double b) Returns the value of the first argument raised to the power of the second argument. static double random() Returns a double value greater than or equal to 0.0 and less than 1.0. static long round(double a) Returns the closest long to the argument. static double sin(double a) Returns the trigonometric sine of an angle. static double sqrt(double a) Returns the correctly rounded positive square root of a double value. Some Java Escape Sequences and their meaning: \t tab \n newline \" double quote \' single quote \\ backslash CSC1051 Data Structures and Algorithms I Dr. Papalaskari

CSC 1051 Algorithms and Data Structures I Midterm Examination October 7, 2013 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces provided. If you make a mistake or for some other reason need more space, please use the back of pages or the extra blank page at the end and clearly indicate where the answer can be found. Good luck!

1. [ /10] Short answer questions. f) If a language uses 50 unique letters and symbols, how many bits would be needed to store each character of a document? Explain. g) Give examples of two types of Java comments and explain the differences between them. h) Java is case sensitive. What does that mean? i) What is a variable declaration? Give two examples. j) Why are widening conversions safer than narrowing conversions?

2. [ /10] List the following items with respect to the code below: a) a boolean expression b) all variable identifiers for integers c) all variables identifiers for floating point numbers d) all constant identifiers (any type of value) e) a comment f) an output statement g) an input statement h) a statement that is executed conditionally // Wages.java calculates wages with overtime. //******************************************************************** import java.text.numberformat; import java.util.scanner; public class Wages public static void main (String[] args) final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours in a work week Scanner scan = new Scanner (System.in); double pay = 0.0; System.out.print ("Enter the number of hours worked: "); int hours = scan.nextint(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-standard) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println (""Gross earnings: " + fmt.format(pay));

3. [ /10] Short answer questions. a) [7 points] Suppose you want to draw a red circle inside a green square, positioned at the top left corner of your applet. the square should have sides of length 100 pixels and the circle should have a smaller diameter, 80 pixels. As usual, the paint method is passed a Graphics object called page. Here is a start finish writing the Java code: page.setcolor(color.green); // finish writing this code page.fillrect( b) [3 points] if (a>0) if (b<0) x = x + 5; else if (a>5) x = x + 4; else x = x + 3; else x = x + 2; If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed?

4. [ /10] What gets printed by the following program? public class Mystery public static void main(string args[]) String str = elle ; int left = 0; int right = str.length() - 1; while (str.charat(left) == str.charat(right) && left < right) System.out.println( Yes! ); System.out.println( left = + left); System.out.println( right = + right); System.out.println( The characters are + str.charat(left) + str.charat(right)); left ++; right --; Output System.out.println( Out of the loop now ); System.out.println( left = + left); System.out.println( right = + right); System.out.println( The characters are + str.charat(left) + str.charat(right));

5. [ /10] Recall that the Random class is part of the java.util package. a) Write an import declaration for the Random class b) Write some code to declare and instantiate an object of the Random class (call the object reference rand). c) Write some code that uses the object rand, above, to generate pseudorandom numbers in the following specified ranges (including the endpoints): 0 to 100 1 to 10 0 to.9.999999 (i.e., as close to 10 as it gets, but not including 10)

6. [ /10] Short answer questions. For each of the following expressions, indicate the order in which the operations are performed by writing a number beneath each operator. a - b + d / e / f b + e + a + f + c For each of the following Java code fragments, mark the error and show how to correct it. What do you need to do to fix it so that it works as appears to be intended? a) if (value = 0) System.out.print ("Right!"); b) if (value > 0); System.out.print ("Right!"); c) if (value > 0) System.out.print ("Right!"); System.out.println( value is positive );

7. [ /10] Given the following declarations: int iresult, num1= 5, num2 = 2; double fresult, val1 = 8.0; int iresult, num1= 5, num2 = 3; double fresult, val1 = 6.0; Show the results if the following assignment statements are executed (or write ERROR if the statement causes an error). The resulting value of the expression that will be stored in the variable and its type The kind of data conversion, i.e., one of the following: o none (no data conversion of any kind) o automatic (through assignment or mixed type experession) o cast (specify whether widening or narrowing) Note that there may be none or more than one conversion be sure to list all, if any FOR EACH ANWER WRITE AN EXPLANATION Source code value stored in variable Type of value Data Conversion(s) fresult = num1; iresult = num1 / num2; fresult = val1 / num2; fresult = (double) (num1/num2);

8. [ / 10] What gets printed? Please show output as it will appear, or indicate NO OUTPUT, or show some of the output followed by INFINITE LOOP. int a = 0; while (a<5) System.out.println(a); a++; Output: int a = 0; while (a<5) System.out.println(a); a++; Output: // (same as previous one, only no braces) int a = 6; Output: while (a>0) System.out.println(a); a = a - 2; int a = 1; while (a <= 6) System.out.println(2*a); a++; Output:

9. ( / 10) Construct an algorithm that inputs 10 positive integers from the user and determines how many of the numbers entered are even (i.e., divisible by 2). The algorithm should print the numbers as they are entered, and meanwhile keep track of how many have been even (hint: use the variable evencount). After all the numbers have been entered, print the result (how many were even) and a goodbye message. Example: If the numbers 25 86 13 54 1 52 4 88 9 41 are entered as input, the algorithm should print: 25 86 13 55 1 52 9 88 9 41 3 of these numbers are even Goodbye Directions: Write your algorithm by rearranging and structuring elements chosen from the list below, using indentation to show structure. Do not use anything else and note that not all of these are needed, but you may use one of them more than once, if necessary. num = 0 count = 0 count = 1 evencount= 0 count = count + 1 evencount = evencount + 1 num = num + 1 print evencount print of these numbers are even print Goodbye input num input evencount input count while (count < num) while (count <= num) while (count < 10) while (num < 10) while (num %2 == evencount) while (num % 2 == 0) while (count <=10) if (num %2 == evencount) if (num % 2 == 0) else

10. ( / 10) Write a complete Java program that asks the user to input an integer representing a number of days and then calculates and prints the equivalent as a number of weeks and days. For example, if the user inputs 18 for the number of days, the output should state that it is equivalent to 2 weeks and 4 days. Be sure to write a complete Java program, including class definition, variable and constant declarations, as appropriate, comments, and proper indentation, to make it readable.

//******************************************************************** // Einstein.java Author: Lewis/Loftus // // Demonstrates a basic applet. //******************************************************************** import javax.swing.japplet; import java.awt.*; public class Einstein extends JApplet //----------------------------------------------------------------- // Draws a quotation by Albert Einstein among some shapes. //----------------------------------------------------------------- public void paint (Graphics page) page.drawrect (50, 50, 40, 40); // square page.drawrect (60, 80, 225, 30); // rectangle page.drawoval (75, 65, 20, 20); // circle page.drawline (35, 60, 100, 120); // line page.drawstring ("Out of clutter, find simplicity.", 110, 70); page.drawstring ("-- Albert Einstein", 130, 100); Drawing a Line 20 45 Y 10 150 Start x y page.drawline (10, 20, 150, 45); or End x y page.drawline (150, 45, 10, 20); X CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Drawing a Rectangle Drawing an Oval 50 X 175 X 20 20 40 80 Y 100 Start x y Width Height Y bounding rectangle 50 page.drawrect (50, 20, 100, 40); page.drawoval (175, 20, 50, 80); CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Drawing an Arc An arc is defined by an oval, a start angle, and an arc angle: Filled vs unfilled shapes Instead of using drawrect(), drawoval() etc, we can use fillrect(), filloval() etc We can set the color using setcolor() See Snowman.java See also Snowman applet on a webpage CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University 1

Some methods of the String class boolean isempty() Returns true if, and only if, length() is 0. char charat(int index) Returns the char value at the specified index. int length() Returns the length of this string. String touppercase() Converts all of the characters in this String to lower case using the rules of the default locale. Some methods of the Random class double nextdouble() Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 int nextint() Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. int nextint(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. Some methods of the Math class static double abs(double a) Returns the absolute value of a double value. static double cos(double a) Returns the trigonometric cosine of an angle. static double pow(double a, double b) Returns the value of the first argument raised to the power of the second argument. static double random() Returns a double value greater than or equal to 0.0 and less than 1.0. static long round(double a) Returns the closest long to the argument. static double sin(double a) Returns the trigonometric sine of an angle. static double sqrt(double a) Returns the correctly rounded positive square root of a double value. Some Java Escape Sequences and their meaning: \t tab \n newline \" double quote \' single quote \\ backslash CSC1051 Data Structures and Algorithms I Dr. Papalaskari