copyright 2009 by pearson education midterm review session programming problems for more practice:

34
Copyright 2009 by Pearson Education Midterm Review Session Programming Problems For more practice: http://webster.cs.washington.edu:8080/pra cticeit/

Upload: harriet-lauren-hunt

Post on 18-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Copyright 2009 by Pearson Education

Midterm Review Session

Programming Problems

For more practice:http://webster.cs.washington.edu:8080/practiceit/

Copyright 2009 by Pearson Education 2

Midterm LogisticsBring your UW Student ID card!!

Will check your ID while you’re leavingBring your stuff with you while you exit (don’t go back to seat)

60 minute exam-10 if you start early or try to write after time

Any paper notes allowed, but NO ELECTRONICSBook OK, section handouts OK, past exams + solutions OK, etc.NO CALCULATORS! NO LAPTOPS!

Aiming for a median of 80Will be a curve if the exam is too hard, will not have a hurtful

curve if exam is too easy

Copyright 2009 by Pearson Education 3

About the Exam100 pts, 20% of course grade

Non-programming – 61 pts Expressions (10), parameter mystery (12), if/else simulation (12),

while loop simulation (12), assertions (15)Easy Programming – 15 ptsMedium Programming – 15 ptsReally Hard Programming – 9 pts

Topics covered: Chapters 1-5

Topics not covered: see website!Includes Graphics, printf, do/while, break

Copyright 2009 by Pearson Education 4

More Exam InfoNon-programming questions

You do not need to show your workYou are not allowed to use calculators (e.g. on expressions)

Programming questions Are not graded on style, only external correctnessMust write valid Java code that would compile

Will not grade comments or pseudo-code Do NOT use abbreviations Do not have to write import statements

Substantial partial credit is given for partially working solutions Write as much as you can: even a method header and the beginnings

of a while loop could earn you partial points!

More info on course website!

Copyright 2009 by Pearson Education 5

General TipsBE AFRAID. Success on HW is not an indication of being

prepared for the exam.

Watch the clock! The hardest part about this exam will be the time limit.

PRACTICE Q1-Q5 so that you can go through them fast and accurately! You want as much time as possible for the programming questions.

Write as much as you can!A partial answer is better than none at all.Writing the correct method header will earn at least 1 point.Writing a partial loop, if statements, returns, etc. will points too

Copyright 2009 by Pearson Education 6

General TipsRead the instructions now and learn the format so you

won't be surprised tomorrow The format of the midterm will be the same as the samples

For more practice, use Marty Stepp's Practice-it tool: http://webster.cs.washington.edu:8080/practiceit/

Copyright 2009 by Pearson Education

Concepts Review

Some essential topics from Ch1-5

Copyright 2009 by Pearson Education 8

For-loopsUse to repeat stuff when you know exactly* how much

you want to repeat* Could also have a variable or expression that tells you exactly

how much you want to repeat

Nested for-loops: loops within a loopWhen you want to do task multiple times, and that task has

repetition to itE.g. multiplication table

Cumulative sum: variable that keeps a sum in progress and is updated repeatedly until summing is finished

In general: think about bounds, possible fencepost issues

Copyright 2009 by Pearson Education 9

Conditionals and TestsIf/else statement: Decide between several logical choices

While loop: Repeat unknown number of timesSentinel loops: repeat until a certain signal is seen (e.g. prompt

until you see a -1)

boolean: primitive type with a true or false valueWhen to return??Boolean flag is helpful

Copyright 2009 by Pearson Education 10

Stringslength() to get length of a String

indexOf/contains to search for substring within String

equals/equalsIgnoreCase to test equalitystartsWith/endsWith to test beginning/end of word

substring(index1, index2) to get a piece of a Stringindex1 inclusive, index2 exclusiveIndex 0 for first letter, index length() -1 for last letter

+ to concatenate Strings together

Copyright 2009 by Pearson Education 11

Other miscellaneous stuffScanner to prompt for input

hasNext, hasNextInt, hasNextDouble, hasNextLine

Random to get a random valueTo generate random number between [min, max]:r.nextInt(range) + minWhere range: max – min + 1r.nextInt(51) + 50; // produces random value 50 - 100

Expressions stuff: % 10 and / 10 to get digits% 2 == 0 to test for even (!= for odd)

Copyright 2009 by Pearson Education

Programming Practice

Practice problems from previous exams

Copyright 2009 by Pearson Education 13

Programming TipsRead the problems carefully:

Does it want you to print a result, or return it?

What values does the method use for computation? Are these values parameters, are they read from a Scanner, etc.?

What type of value (if any) does the method return?

Have you handled all special cases? What if the integer is 0, or negative? What if the string has no letters? What if there is only one word in the string? Many words?

Copyright 2009 by Pearson Education 14

Practice Problem 1: Print MultiplesWrite a static method named printMultiples

Takes two integers n and m as parameters and prints the first m multiples of nAssume m >= 1

Multiples are separated by commas

printMultiples(3, 5);The first 5 multiples of 3 are 3, 6, 9, 12, 15

printMultiples(7, 3);The first 3 multiples of 7 are 7, 14, 21

Copyright 2009 by Pearson Education 15

Print Multiples Solutionpublic static void printMultiples(int n, int times) {

System.out.print("The first " + times + " multiples of " + n + " are " + n);

for (int i = 2; i <= times; i++) {

System.out.print(", " + i * n);

}

System.out.println();

}

Copyright 2009 by Pearson Education 16

Practice Problem 2: Count Even DigitsWrite a static method named countEvenDigits

Accepts an integer as its parameter and returns the number of even-valued digits in that number.Even digits: 0, 2, 4, 6, or 8

Assume value passed to your method is non-negative

// 4 even digits: two 8s, the 4, and 6int x = countEvenDigits(8346387) ;

System.out.println("x is " + x); // x is 4

Copyright 2009 by Pearson Education 17

Count Even Digits Solutionpublic static int countEvenDigits(int n) { int count = 0; while (n != 0) { int digit = n % 10; n = n / 10; if (digit % 2 == 0) { count++; } } return count;}

Copyright 2009 by Pearson Education 18

Practice Problem 3: CheerleaderWrite a static method named cheerleader

Takes two params:number of lines of outputnumber of "cheers" per line

Cheer structure:1 cheer: Go2 cheers: Go Team Go3 cheers: Go Team Go Team Go

Each line indented by 3 spaces; first line at 0 spaces

cheerleader(2, 1);Go Go

cheerleader(4, 3); Go Team Go Team Go Go Team Go Team Go Go Team Go Team Go Go Team Go Team Go

cheerleader(2, 4);Go Team Go Team Go Team Go Go Team Go Team Go Team Go

Copyright 2009 by Pearson Education 19

Cheerleader Solutionpublic static void cheerleader(int lines, int cheers) { for (int line = 1; line <= lines; line++) { for (int space = 1; space <= line - 1; space++) {

System.out.print(" "); } for (int cheer = 1; cheer <= cheers - 1; cheer++) {

System.out.print("Go Team "); } System.out.println("Go"); }}

Copyright 2009 by Pearson Education 20

Practice Problem 4: Favorite LetterWrite a static method named faveLetter

Accepts two parameters: Scanner for the consoleFavorite letter represented as a

one-letter String

Repeatedly prompt the user until two consecutive words are entered that start with that letter. Case sensitive

Print a message showing the last word typed.

(assume a Scanner named console was made earlier in code)

faveLetter(console, "y");Looking for two "y" words.Type a word: hiType a word: byeType a word: yesType a word: what?Type a word: yellowType a word: yippee"y" is for "yippee"

Copyright 2009 by Pearson Education 21

Favorite Letter Solutionpublic static void faveLetter(Scanner console, String letter) { System.out.println("Looking for two \"" + letter + "\" words."); int count = 0; String word = ""; while (count < 2) { System.out.print("Type a word: "); word = console.next(); if (word.startsWith(letter)) { count++; } else { count = 0; } } System.out.println("\"" + letter + "\" is for \"" + word + "\"");}

Copyright 2009 by Pearson Education 22

Practice Problem 5: Random RectsWrite a static method named randomRects

Calculates and displays the area of randomly-generated rectangles.

Each rectangle has random width and height btwn 1 and 10 inclusive

Keep generating rectangles until an increasing sequence of four areas is printed. Stop when the last four rectangles

generated have areas of a1, a2, a3 and a4 such that a1 < a2 < a3 < a4

randomRects();w: 5, h: 6, area: 30w: 10, h: 5, area: 50w: 2, h: 8, area: 16w: 4, h: 4, area: 16w: 2, h: 9, area: 18w: 8, h: 3, area: 24w: 7, h: 2, area: 14w: 3, h: 10, area: 30w: 7, h: 9, area: 63w: 9, h: 8, area: 72End random rectangles.

Copyright 2009 by Pearson Education 23

Random Rectangles Solutionpublic static void randomRects() { Random r = new Random(); int last = 0; int count = 0; while (count != 4) { int w = r.nextInt(10) + 1; int h = r.nextInt(10) + 1; int area = w * h; if (area <= last) { count = 1; // need to count first rect in sequence } else { count++; } System.out.println("w: " + w + ", h: " + h + ", area: " +

area); last = area; } System.out.println("End random rectangles.");}

Copyright 2009 by Pearson Education

Non-Programming Practice

Tips on Questions 1-4

(For assertions help, see lecture 14)

Copyright 2009 by Pearson Education 25

Expressionsinteger division and mod: quotient and remainder

14 / 3 is 4, 14 % 3 is 27 / 10 is 0, 7 % 10 is 7

precedence: ( ) before * / % before + -5 + 2 * 6 - (1 + 7) % 35 + 2 * 6 - 8 % 35 + 12 - 8 % 35 + 12 - 2 17 - 2 15

Copyright 2009 by Pearson Education 26

Expressions 2String concatenation: same precedence as integer + -,

evaluated left-to-right with other + - operations1 + 2 + "3" + 4 + 5 3 + "3" + 4 + 5 "33" + 4 + 5 "334" + 5 "3345"

type promotion: done as needed when int and double are mixed50 / 6 / 5.0 8 / 5.0 1.6

Copyright 2009 by Pearson Education 27

Expression questionsEvaluate the following expressions:

16 / 3 + 3.2 * 28 / 7 + "5 / 4" + 8 / 388 % 10 % 3 * 16 / 1029 / 3 / 2 / 4.0 + 3.6 * 21.4 + (3 + 2 * 6) / (8 - 14 / 3) * 2.2

Copyright 2009 by Pearson Education 28

Expression answersCorrect answers:

16 / 3 + 3.2 * 2 11.48 / 7 + "5 / 4" + 8 / 3 "15 / 42"

88 % 10 % 3 * 16 / 10 329 / 3 / 2 / 4.0 + 3.6 * 2 8.21.4 + (3 + 2 * 6) / (8 - 14 / 3) * 2.2 8.0

Copyright 2009 by Pearson Education 29

Parameter mystery questionWhat is the output of the following program?public class Mystery { public static void main(String[] args) { String john = "skip"; String mary = "george"; String george = "mary"; String fun = "drive"; String work = "john";

speak(mary, john, fun); speak(george, work, john); speak(fun, "george", "work"); speak(george, mary, john); speak(george, "john", "dance"); }

public static void speak(String mary, String john, String fun) { System.out.println(john + " likes to " + fun + " with " + mary); }}

Copyright 2009 by Pearson Education 30

Parameter mystery tipsTry making a table of the parameters passed to each call:public class Mystery { public static void main(String[] args) { String john = "skip"; String mary = "george"; String george = "mary"; String fun = "drive"; String work = "john";

speak(mary, john, fun); speak(george, work, john); speak(fun, "george", "work"); speak(george, mary, john); speak(george, "john", "dance"); }

public static void speak(String mary, String john, String fun) { System.out.println(john + " likes to " + fun + " with " + mary); }}

george skip drive

mary john skip

drive george work

mary george skip

mary john dance

Copyright 2009 by Pearson Education 31

Parameter mystery answerWhat is the output of the following program?public class Mystery { public static void main(String[] args) { String john = "skip"; String mary = "george"; String george = "mary"; String fun = "drive"; String work = "john";

speak(mary, john, fun); skip likes to drive with george speak(george, work, john); john likes to skip with mary speak(fun, "george", "work"); george likes to work with drive speak(george, mary, john); george likes to skip with mary speak(george, "john", "dance"); john likes to dance with mary }

public static void speak(String mary, String john, String fun) { System.out.println(john + " likes to " + fun + " with " + mary); }}

Copyright 2009 by Pearson Education 32

While loop mystery questionGiven the following program,

public static void mystery(int y) { int x = 0; int z = 0; while (y > 0) { System.out.print(x + " " + z + " "); x++; z = z + y % 10; y = y / 10; } System.out.println(x + " " + z);}

What is the output of the following sequence of calls?mystery(0);mystery(8);mystery(32);mystery(72);mystery(184);mystery(8239);

Copyright 2009 by Pearson Education 33

While loop mystery tipsKeep track of each variable's value as it changes:

public static void mystery(int y) { int x = 0; int z = 0; while (y > 0) { System.out.print(x + " " + z + " "); x++; z = z + y % 10; y = y / 10; } System.out.println(x + " " + z);}

What is the output of the following call?mystery(184);

Sometimes, these problems are performingreal computations in disguise.What is this problem really doing?

x y z

0 184 0

1 18 4

2 1 12

3 0 13

Copyright 2009 by Pearson Education 34

While loop mystery answersGiven the following program,

public static void mystery(int y) { int x = 0; int z = 0; while (y > 0) { System.out.print(x + " " + z + " "); x++; z = z + y % 10; y = y / 10; } System.out.println(x + " " + z);}

What is the output of the following sequence of calls?mystery(0); 0 0mystery(8); 0 0 1 8mystery(32); 0 0 1 2 2 5mystery(72); 0 0 1 2 2 9mystery(184); 0 0 1 4 2 12 3 13mystery(8239); 0 0 1 9 2 12 3 14 4 22