AP Computer Science Principles Programming (Khan Academy)

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

playingCards ← ["3", "5", "6", "7", "9", "J", "A"] DISPLAY(playingCards[4]) REMOVE(playingCards, 1) INSERT(playingCards, 4, "8") REMOVE(playingCards, 1) INSERT(playingCards, 1, "3") DISPLAY(playingCards[4])

7 8

a ← 89 a ← 97 a ← 93

93

A board games website includes a feature for users to list their favorite board games. When the user first starts their list, the website runs this code to create an empty list: bestGames ← [] The user can then insert and remove items from the list. Here's the code that was executed from one user's session: APPEND(bestGames, "Dixit") APPEND(bestGames, "Codenames") APPEND(bestGames, "Mysterium") APPEND(bestGames, "Scrabble") APPEND(bestGames, "Catchphrase") APPEND(bestGames, "Lost Cities") INSERT(bestGames, 2, "Carcassonne") REMOVE(bestGames, 4) What does the bestGames variable store after that code runs?

"Dixit", "Carcassonne", "Codenames", "Scrabble", "Catchphrase", "Lost Cities"

coolDinos ← ["Triceratops", "Stegosaurus", "Ankylosaurus", "Ultrasauros", "Therizinosaurus"] coolDinos[1] ← "Torosaurus" coolDinos[4] ← "Supersaurus"

"Torosaurus", "Stegosaurus", "Ankylosaurus", "Supersaurus", "Therizinosaurus"

Kobe is working on a basketball game and is experimenting with the variables he'll use for the game. His code looks like this: score ← 1 shots ← 0 DISPLAY (score) DISPLAY (shots) shots ← 3 score ← shots DISPLAY (shots) DISPLAY (score)

1 0 3 3

title ← "Mashed parsnips" prepTime ← 10 cookTime ← 30 rating ← 4.5 category ← "veggies"

2

In the classic arcade game Donkey Kong, the code calculates the time allowed per level by multiplying the current level and adding 40. On level 22, that calculated time is 260. However, the game displays a time of 4 instead of 260. It is impossible for anyone to complete the level in just 4 seconds, so no player ever makes it past level 22. What is the most likely cause of the level 22 bug?

Integer overflow error

NOT ( state = "loading" OR result = "error" )

NOT ( state = "loading" OR result = "error" )

Which of the following is a benefit of procedures for programmers?

Programmers can more easily understand programs with procedures, since procedures give names to complex pieces of code.

A web developer is creating an online lottery scratch card. This incomplete code segment decides whether the player wins a prize: IF (<MISSING CONDITION>) { awardAmount ← 10 } The code should only give the player a 3% chance of winning a prize.

RANDOM(1, 100) > 97 RANDOM(1, 100) <= 3

commentA ← "ISN'T IT OBVIOUS?!!!" commentB ← "YOU'RE SO SILLY!!!!" commentC ← "I DON'T BELIEVE YOU!!!" Which of the following expressions results in the string "you're so silly"?

REMOVE( LOWER(commentB), "!") LOWER( REMOVE(commentB, "!"))

A digital artist is programming a natural simulation of waves. They plan to calculate the y position of the wave using this wave equation: y = Acos(\dfrac{2\pi}{\lambda}x)y=Acos( λ 2π ​ x)y, equals, A, c, o, s, left parenthesis, start fraction, 2, pi, divided by, lambda, end fraction, x, right parenthesis The environment provides the built-in procedure cos(angle) which returns the cosine of angle. The built-in constant PI stores an approximation of PI. In the artist's code, the variable x represents the x position (xxx), wL represents the wavelength (\lambdaλlambda), and amp represents the amplitude (AAA).

amp * cos( ((2 * PI)/wL) * x)

NOT ( calendar = "user" AND rsvp = "yes" )

calendar ≠ "user" OR rsvp ≠ "yes"

Amelie is planning a gingerbread house making workshop for the neighborhood, and is writing a program to plan the supplies. She's buying enough supplies for 15 houses, with each house being made out of 5 graham crackers. Her favorite graham cracker brand has 20 crackers per box. Her initial code: numHouses ← 15 crackersPerHouse ← 5 crackersPerBox ← 20 neededCrackers ← crackersPerHouse * numHouses Amelie realizes she'll need to buy more crackers than necessary, since the crackers come in boxes of 20. Now she wants to calculate how many graham crackers will be leftover in the final box, as she wants to see how many extras there will be for people that break their crackers (or get hungry and eat them).

extras ← crackersPerBox - (neededCrackers MOD crackersPerBox)

Which line of code would store the string "one-third"?

frac ← concatenate(concatenate(num1, "-"), denom))

An astronomer is writing a program demonstrating Kepler's three laws of planetary motion, including this ratio of orbital period compared to average orbital radius: \text{Constant} = T^2/R^3Constant=T 2 /R 3 C, o, n, s, t, a, n, t, equals, T, start superscript, 2, end superscript, slash, R, start superscript, 3, end superscript This is their code for computing that ratio: keplerRatio ← (period * period) / (radius * radius * radius) They then discover that the coding environment offers a number of useful mathematical procedures:

keplerRatio ← pow(period, 2) / pow(radius, 3) keplerRatio ← square(period) / cube(radius)

eggsInBatch ← 3 numBatches ←9 neededEggs ← eggsInBatch * numBatches

leftoverEggs ← 12 - (neededEggs MOD 12)

PROCEDURE lineSlope (x1, y1, x2, y2) { result ← (y2 - y1) / (x2 - x1) DISPLAY (result) }

lineSlope(1, 1, 3, 4)

A gardener is writing a program to detect whether the soils for their citrus trees are the optimal level of acidity. IF (measuredPH > 6.5) { soilState ← "high" } ELSE { IF (measuredPH < 5.5) { soilState ← "low" } ELSE { soilState ← "optimal" } } Which of these tables shows the expected values of soilState for the given values of measuredPH?

measuredPH soilState 4.7 "low" 5.4 "low" 5.5 "optimal" 6.2 "optimal" 6.5 "optimal" 6.7 "high" 7.2 "high"

A chemistry student is writing a program to help classify the results of experiments. solutionType ← "unknown" IF (phLevel = 7) { solutionType ← "neutral" } ELSE { IF (phLevel > 7) { solutionType ← "basic" } ELSE { solutionType ← "acidic" } } Which of these tables shows the expected values of solutionType for the given values of phLevel? Choose 1 answer:

phLevel solutionType -0.4 "acidic" 4.7 "acidic" 6.9 "acidic" 7 "neutral" 7.4 "basic" 14.2 "basic"

The following expression is from the logic of an online game. NOT ( score > 7 OR minutes > 20 ) Which of these expressions are logically equivalent?

score ≤ 7 AND minutes ≤ 20

A game programmer decides to to use the Pythagorean distance formula for collision detection:

sqrt( square(x2 - x1) + square(y2 - y1) )

Nikki read that it's healthy to take 10,000 steps every day. She's curious how many steps that'd be per minute, walking from 10AM to 10PM, and is writing a program to figure it out. The program starts with this code: stepsPerDay ← 10000 hoursAwake ← 12 Which lines of code successfully calculate and store the steps per minute? 👁️

stepsPerMin ← (stepsPerDay / hoursAwake) / 60 stepsPerMin ← stepsPerDay / hoursAwake / 60

rowNum ← 1 REPEAT 4 TIMES { colNum ← rowNum + 4 REPEAT (5 - rowNum) TIMES { fillPixel(rowNum, colNum, "blue") colNum ← colNum + 1 } rowNum ← rowNum + 1 }

top right corner

The following procedure calculates the area of a trapezoid and takes three parameters: the width of the first base, the width of the second base, and the height of the trapezoid. PROCEDURE trapezoidArea (b1, b2, h) { result ← ((b1 + b2) * h) / 2 DISPLAY (result) } Here is a trapezoid with an unknown area: Trapezoid diagram with upper base width of 5 meters, lower base width of 3 meters, and height of 4 meters. Trapezoid diagram with upper base width of 5 meters, lower base width of 3 meters, and height of 4 meters. Which of these lines of code correctly calls the procedure to calculate the area of this trapezoid?

trapezoidArea (5, 3, 4) trapezoidArea (3, 5, 4)

certification ← "none" IF (albumsSold <?> 10000000) { certification ← "diamond" } ELSE { IF (albumsSold <?> 1000000) { certification ← "platinum" } ELSE { IF (albumsSold <?> 500000) { certification ← "gold" } }

discount ← 0 IF (quantity <?> 150) { discount ← 10 } ELSE { IF (quantity <?> 75) { discount ← 7 } ELSE { IF (quantity <?> 10) { discount ← 5 } } } Which operator could replace <?> so that the code snippet works as expected?

The following numbers are displayed by a program: 2 4 6 8 The program code is shown below, but it is missing three values: <COUNTER>, <AMOUNT>, and <STEP>. i ← <COUNTER> REPEAT <AMOUNT> TIMES { DISPLAY(i * 2) i ← i + <STEP> } Given the displayed output, what must the missing values be?

<COUNTER> = 1, <AMOUNT> = 4, <STEP> = 1

userBday ← "03/31/84"

DISPLAY (SUBSTRING (userBday, 7, 2))

At that distance, the code should give the player a 30% chance of making the goal.

RANDOM(1, 100) <= 30 RANDOM(1, 10) <= 3

strings ← ["A", "b", "C", "d", "e"] numFound ← 0 FOR EACH string IN strings { IF (UPPER(string) != string) { numFound ← numFound + 1 } } DISPLAY(numFound) The code relies on one string operation, UPPER(string), which returns string in uppercase.

3

Aarush is writing a program to help him calculate how much exercise he does at the gym. The procedure calcSwimYards returns the number of yards swum for a given number of laps in a pool of a given length. PROCEDURE calcSwimYards(poolLength, numLaps) { lapLength ← poolLength * 2 RETURN lapLength * numLaps } Aarush then runs this line of code: yardsSwum ← calcSwimYards(25, 10) What value is stored in yardsSwum?

500

1: player1Misses ← 0 2: player2Misses ← 0 3: REPEAT UNTIL (player1Misses = 5 OR player2Misses = 5) 4: { 5: player1Shot ← RANDOM(1, 2) 6: player2Shot ← RANDOM(1, 2) 7: IF (player1Shot = 2) 8: { 9: DISPLAY("Player 1 missed! ☹") 10: } 11: IF (player2Shot = 2) 12: { 13: DISPLAY("Player 2 missed! ☹") 14: } 15: IF (player1Shot = 1 AND player2Shot = 1) 16: { 17: DISPLAY("No misses! ☺") 18: } 19: }

9 and 10 13 and 14

The following numbers are displayed by a program: 4 5 5 6 The program code is shown below, but it is missing three values: <COUNTER>, <AMOUNT>, and <STEP>. i ← <COUNTER> REPEAT <AMOUNT> TIMES { DISPLAY(i) DISPLAY(i + 1) i ← i + <STEP> } Given the displayed output, what must the missing values be?

<COUNTER> = 4, <AMOUNT> = 2, <STEP> = 1

A digital artist is writing a program to draw a landscape with a randomly generated mountain range. This code draws a single mountain: xPos ← RANDOM(4, 240) height ← RANDOM(70, 120) drawMountain(xPos, 80, height) The code relies on the drawMountain() procedure, which accepts three parameters for the mountain's x position, y position, and height. Here's what's drawn from one run of the program: Graphic of landscape with mountain 210 pixels from the left side. Which of these describes mountains that might be drawn from this program?

A mountain at an x position of 4 and a height of 120 A mountain at an x position of 180 and a height of 110

IF (currentNum > expectedNum) { status ← "Elevated error rate" } ELSE { status ← "All is well" }

currentNum expectedNum status 2 5 "All is well" 5 5 "All is well" 6 5 "Elevated error rate" 9 10 "All is well" 10 10 "All is well" 15 10 "Elevated error rate"

DISPLAY ("Schoolie") DISPLAY ("McSchoolFace")

Schoolie McSchoolFace

Athena is writing a program to calculate the carbon footprint of her activities. The procedure calcFlightFootprint calculates the pounds of carbon dioxide produced per passenger in a flight that covers a given number of miles and seats a given number of passengers. PROCEDURE calcFlightFootprint(numMiles, numPassengers) { CO2_PER_MILE ← 53.29 carbonPerFlight ← numMiles * CO2_PER_MILE carbonPerPassenger ← carbonPerFlight / numPassengers RETURN carbonPerPassenger } Athena wants to use that procedure to calculate the total footprint for her two upcoming flights: LA to NY: 2,451 miles and 118 passengers NY to London: 3,442 miles and 252 passengers

laNyCarbon ← calcFlightFootprint(2451, 118) nyLondonCarbon ← calcFlightFootprint(3442, 252)` totalFootprint ← laNyCarbon + nyLondonCarbon totalFootprint ← calcFlightFootprint(2451, 118) + calcFlightFootprint(3442, 252)

The following code snippet processes a list of strings with a loop and conditionals: words ← ["belly", "rub", "kitty", "pet", "cat", "water"] counter ← 0 FOR EACH word IN words { IF (FIND(word, "e") = -1 AND FIND(word, "a") = -1) { counter ← counter + 1 } } DISPLAY(counter) The code relies on one string procedure, FIND(source, target), which returns the first index of the string target inside of the string source, and returns -1 if target is not found.

2

IF (x > y) { mystery ← x - y } ELSE { IF (x < y) { mystery ← y / x } ELSE { mystery ← x + y } } If we set x to 32 and y to 8, what value will the mystery variable store after running this code? Choose 1 answer:

24

a ← 2 b ← 4 c ← 6 d ← 8 result ← max( min(a, b), min(c, d) )

6

Danielle is programming a kitty simulator. Here's part of her code: hunger ← 6 cuddliness ← 9 playfulness ← 7 DISPLAY (playfulness) DISPLAY (cuddliness) DISPLAY (hunger)

7 9 6

This graph contains a line with unknown slope, going through the points [2, 1][2,1]open bracket, 2, comma, 1, close bracket and [4, 3][4,3]open bracket, 4, comma, 3, close bracket:

(2, 1, 4, 3)

strings ← ["A", "b", "C", "d", "e"] numFound ← 0 FOR EACH string IN strings { IF (UPPER(string) != string) { numFound ← numFound + 1 } } DISPLAY(numFound)`

3

This list represents the top runners in a marathon, using their bib numbers as identifiers: frontRunners ← [308, 147, 93, 125, 412, 219, 73, 34, 252, 78] This code snippet updates the list: tempRunner ← frontRunners[3] frontRunners[3] ← frontRunners[2] frontRunners[2] ← tempRunner What does the frontRunners variable store after that code runs?

308, 93, 147, 125, 412, 219, 73, 34, 252, 78

This code snippet stores and updates a list of high scores for a video game: highScores ← [750, 737, 714, 672, 655, 634, 629, 618, 615, 610] DISPLAY(highScores[5]) INSERT(highScores, 5, 668) INSERT(highScores, 2, 747) REMOVE(highScores, 12) REMOVE(highScores, 11) DISPLAY(highScores[5]) What does this program output to the display?

655 672

The two programs below are both intended to display the total number of hours from a list of durations in minutes. Program 1: totalMins ← 0 durations ← [32, 56, 28, 27] FOR EACH duration IN durations { totalMins ← totalMins + duration } totalHours ← totalMins / 60 DISPLAY(totalHours) Program 2: totalMins ← 0 durations ← [32, 56, 28, 27] FOR EACH duration IN durations { totalMins ← totalMins + duration totalHours ← totalMins / 60 } DISPLAY(totalHours)

Both programs display the correct total number of hours, but Program 2 unnecessarily repeats arithmetic operations.

PROCEDURE pacifyName(fullName) { heartified ← REPLACE(fullName, " ", "♥") florified ← REPLACE(heartified, "o", "❀") RETURN LOWER(florified) }

Nothing will be displayed

sevenWonders ← ["Aurora", "Grand Canyon", "Great Barrier Reef", "Guanabara Bay", "Mount Everest", "Parícutin", "Victoria Falls"] sevenWonders[4] ← "Komodo" sevenWonders[6] ← "Table Mountain"

"Aurora", "Grand Canyon", "Great Barrier Reef", "Komodo", "Mount Everest", "Table Mountain", "Victoria Falls"

topCities ← ["Kyoto", "Florianopolis", "Wellington", "Puerto Viejo", "Sevilla"] topCities[2] ← "Ankara" topCities[4] ← "Taipei"

"Kyoto", "Ankara", "Wellington", "Taipei", "Sevilla"

result ← 0 i ← 8 REPEAT 7 TIMES { result ← result + i i ← i - 1 }

This program sums up the integers from 2 to 8 (inclusive).

mgAmounts ← [50, 230, 63, 98, 80, 120, 71, 158, 41] bestAmounts ← [] mgPerDay ← 360 mgMin ← mgPerDay * 0.3 FOR EACH mgAmount IN mgAmounts { IF (mgAmount ≥ mgMin) { <MISSING CODE> } }

APPEND(bestAmounts, mgAmount)

words ← ["See", "Jane", "run", "swiftly", "towards", "home"] bigWords ← [] FOR EACH word IN words { IF (LEN(word) > 5) { <MISSING CODE> } }

APPEND(bigWords, word)

Michaela is working with a game designer on an online role playing game. The designer sends them this flow chart: Flow chart that starts with diamond and branches into two rectangles. * Diamond contains question, "Is dice roll at least 15?" * Arrow marked "true" leads to rectangle with text "Action succeeds" * Arrow marked "false" leads to rectangle with text "Action fails" Flow chart that starts with diamond and branches into two rectangles. * Diamond contains question, "Is dice roll at least 15?" * Arrow marked "true" leads to rectangle with text "Action succeeds" * Arrow marked "false" leads to rectangle with text "Action fails" [How do you read a flowchart?] She must implement that logic in code, using the variables diceRoll and action. Which of these code snippets correctly implements the logic in that flow chart?

IF (diceRoll ≥ 15) { action ← "success" } ELSE { action ← "failure" }

REPEAT UNTIL ( canTakeCheese() ) { <MISSING CODE> } There are many ways for him to reach the cheese. Of the options below, which will require the most repetitions of the loop?

IF (facingWall()) { turnRight() } ELSE { walkForward(2) }

Kash is writing code to calculate formulas from his physics class. He's currently working on a procedure to calculate acceleration, based on this formula: \text{Acceleration} = \dfrac{\text{Force}}{\text{Mass}}Acceleration= Mass Force ​ A, c, c, e, l, e, r, a, t, i, o, n, equals, start fraction, F, o, r, c, e, divided by, M, a, s, s, end fraction Which of these is the best procedure for calculating and displaying acceleration?

PROCEDURE calcAcceleration (force, mass) { DISPLAY (force/mass) }

numSold ← 10 pricePer ← 2 moneyMade ← numSold * pricePer DISPLAY(CONCAT(numSold, CONCAT(" x ", pricePer))) DISPLAY(CONCAT(" = ", moneyMade)) numSold ← 20 pricePer ← 1.5 moneyMade ← numSold * pricePer DISPLAY(CONCAT(numSold, CONCAT(" x ", pricePer))) DISPLAY(CONCAT(" = ", moneyMade)) numSold ← 30 pricePer ← 1.25 moneyMade ← numSold * pricePer DISPLAY(CONCAT(numSold, CONCAT(" x ", pricePer))) DISPLAY(CONCAT(" = ", moneyMade))

PROCEDURE calcProfit(numSold, pricePer) { moneyMade ← numSold * pricePer DISPLAY(CONCAT(numSold, CONCAT(" x ", pricePer))) DISPLAY(CONCAT(" = ", moneyMade)) }

The two programs below are both intended to display the total number of overtime hours worked, based on a list of logged hours for each day of a week. Program 1: totalHours ← 0 loggedTimes ← [12, 8, 11, 10, 8] FOR EACH loggedTime IN loggedTimes { totalHours ← totalHours + loggedTime } IF (totalHours > 40) { overtimeHours ← totalHours - 40 DISPLAY(overtimeHours) } Program 2: totalHours ← 0 loggedTimes ← [12, 8, 11, 10, 8] FOR EACH loggedTime IN loggedTimes { totalHours ← totalHours + loggedTime IF (totalHours > 40) { overtimeHours ← totalHours - 40 DISPLAY(overtimeHours) } } Which of these statements best describes these two programs? Choose 1 answer:

Program 1 displays the expected output, while Program 2 displays more output than necessary.

IF (<MISSING CONDITION>) { DISPLAY("meow!") }

RANDOM(1, 100) <= 4

A game developer is working on a basketball playing game. This incomplete code segment simulates a player attempting a 3-pointer shot: shotMade ← false IF (<MISSING CONDITION>) { shotMade ← true score ← score + 3 DISPLAY("Score!") } ELSE { DISPLAY("Miss!") } The code should give the player a 40% chance of making the shot. Which of these can replace <MISSING CONDITION> so that the code works as intended?

RANDOM(1, 100) <= 40 RANDOM(1, 5) <= 2

KittyBot is a programmable robot that obeys the following commands: Name Description walkForward() Walks forward one space in the grid. turnLeft() Rotates left 90 degrees (without moving forward). turnRight() Rotates right 90 degrees (without moving forward). KittyBot is currently positioned in the second row and third column of the grid, and is facing the bottom edge of the grid. 5x5 grid of squares. Cat is shown in the square in the second row and third column. One mouse is shown in the square in the third row and second column, another mouse is shown in the square in the fourth row and third column. We want to program KittyBot so that she pounces on both of the MouseyBots, walking exactly into the squares where they're hiding. Which of these code segments accomplishes that goal? Choose 1 answer: Choose 1 answer: (Choice A, Incorrect) INCORRECT REPEAT 2 TIMES { walkForward() turnRight() walkForward() turnLeft() } (Choice B, Checked, Correct) CORRECT (SELECTED) REPEAT 2 TIMES { walkForward() turnRight() walkForward() turnLeft() turnLeft() } (Choice C, Incorrect) INCORRECT REPEAT 2 TIMES { walkForward() turnRight() walkForward() turnRight() } (Choice D, Incorrect) INCORRECT REPEAT 2 TIMES { walkForward() turnLeft() walkForward() turnRight() }

REPEAT 2 TIMES { walkForward() turnRight() walkForward() turnLeft() turnLeft() }

KittyBot is a programmable robot that obeys the following commands: Name Description walkForward() Walks forward one space in the grid. turnLeft() Rotates left 90 degrees (without moving forward). turnRight() Rotates right 90 degrees (without moving forward). KittyBot is currently positioned in the second row and second column of the grid, and is facing the right side of the grid. 6x6 grid of squares. Cat is shown in the square in the second row and second column. Yarn is shown in the square in the fifth row and fifth column. We want to program KittyBot to reach the ball of yarn, located in the fifth row and fifth column.

REPEAT 3 TIMES { walkForward() turnRight() walkForward() turnLeft() }

Each of the creatures is controlled by a different program. Frog: moveAmount ← 0.5 REPEAT UNTIL ( reachedFinish() ) { moveAmount ← moveAmount * 2 moveForward(moveAmount) } Fox: moveAmount ← 1 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount + 2 } Dog: moveAmount ← 1 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) } Alien: moveAmount ← 4 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount / 2 } After 3 repetitions of each loop, which creature will be ahead?

The fox will be ahead.

A scientist is running a program to calculate the volume of a cone: radius ← 17.24 height ← 5.24 volume ← PI * (radius * radius) * (height / 3) The code relies on the built-in constant PI. After running the code, the variable volume stores 1630.9266447568566. Their supervisor checks their results by running the same calculation on their own computer. Their program results in a volume of 1630.9266447564448. The two values are very close, but not quite the same. Which of these is the most likely explanation for the difference?

The two computers represent the constant PI with a different level of precision, due to their rounding strategy or size limitations.

Mr. Pink: moveAmount ← 1 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount + 1 } Purple Pi: moveAmount ← 1 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount * 2 } Hopper: moveAmount ← 4 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount / 2 } Spunky Sam: moveAmount ← 4 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount - 2 } After the first 3 repetitions of each loop, which avatar will be ahead?

Two avatars will be tied for the lead.

This program attempts to automate the process of giving fluids to a hospital patient to stabilize their blood pressure: ivFluid ← 0 meanPressure ← measureBP() REPEAT UNTIL (meanPressure > 65 OR ivFluid > 2000) { injectFluid(500) ivFluid ← ivFluid + 500 meanPressure ← measureBP() } The program relies on two methods built-in to the IV machine: Name Description injectFluid(amountML) Injects the given amount of fluid (in milliliters). measureBP() Returns a number representing the patient's mean arterial pressure. Part 1: When will the computer stop executing the code inside the REPEAT loop? 👁️Note that there may be multiple answers to this question.

When meanPressure is greater than 65 When ivFluid is greater than 2000 When ivFluid is greater than 2000

IF (today = "Monday") { activity ← "swimming" } ELSE { IF (today = "Tuesday") { activity ← "jogging" } ELSE { IF (today = "Thursday") { activity ← "juggling" } ELSE { IF (today = "Saturday") { activity ← "gardening" } ELSE { activity ← "none" } } } }

today activity "Sunday" "none" "Monday" "swimming" "Tuesday" "jogging" "Wednesday" "none" "Thursday" "juggling" "Friday" "none" "Saturday" "gardening"

A visual artist is programming an 8x8 LED display: 8x8 grid of squares. 8x8 grid of squares. This is their program so far: rowNum ← 0 REPEAT 5 TIMES { colNum ← 0 REPEAT (5 - rowNum) TIMES { fillPixel(rowNum, colNum, "red") colNum ← colNum + 1 } rowNum ← rowNum + 1 } The code relies on this procedure: fillPixel(row, column, color) : Lights up the pixel at the given row and column with the given color (specified as a string). The top row is row 0 and the left-most column is column 0. What will the output of their program look like?

top left corner

We want to program KittyBot so that she pounces on both of the MouseyBots, walking exactly into the squares where they're hiding. Which of these code segments accomplishes that goal?

REPEAT 2 TIMES { walkForward() turnRight() walkForward() turnLeft() turnLeft() }

This code snippet stores and updates a list that represents files in a folder: fileNames ← ["cow.mov", "dog.wav", "cat.jpg", "bird.avi", "fly.gif"] DISPLAY(fileNames[3]) INSERT(fileNames, 2, "goat.tif") INSERT(fileNames, 6, "spider.html") DISPLAY(fileNames[3]) What does this program output to the display? Choose 1 answer:

cat.jpg dog.wav

Lillie is writing a program that calculates geometry formulas. Her procedure calcDistance should return the distance between two points, based on the Pythagorean distance formula: d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}d= (x 2 ​ −x 1 ​ ) 2 +(y 2 ​ −y 1 ​ ) 2 ​ d, equals, square root of, left parenthesis, x, start subscript, 2, end subscript, minus, x, start subscript, 1, end subscript, right parenthesis, start superscript, 2, end superscript, plus, left parenthesis, y, start subscript, 2, end subscript, minus, y, start subscript, 1, end subscript, right parenthesis, start superscript, 2, end superscript, end square root This is the code of the procedure with line numbers: PROCEDURE calcDistance (x1, y1, x2, y2) { xDiff ← x2 - x1 yDiff ← y2 - y1 sum ← POW(xDiff, 2) + POW(yDiff, 2) distance ← SQRT(sum) } The procedure relies on two provided functions, POW which returns a number raised to an exponent, and SQRT which returns the square root of a number. This procedure is missing a return statement, however. Part 1: Which line of code should the return statement be placed after? Part 2: Which of these return statements is the best for this procedure?

After line 6 RETURN distance

DISPLAY (":") DISPLAY ("-") DISPLAY ("O")

: - O

start ← "Bibbidi Bobbidi" end ← "Boo" spell ← CONCAT(start, UPPER(end)) What value does the spell variable store?

"Bibbidi BobbidiBOO"

a ← 3 b ← 8 c ← 5 result ← min( max(a, b), c)

5

This list represents the leading cars in a race, according to the car numbers: raceCars ← [18, 2, 42, 10, 4, 1, 6, 3] This code snippet updates the list: tempCar ← raceCars[6] raceCars[6] ← raceCars[5] raceCars[5] ← tempCar

18, 2, 42, 10, 1, 4, 6, 3

IF (mouseX < 200 AND mouseY < 200) { currentSquare ← 1 } ELSE { IF (mouseX > 200 AND mouseY < 200) { currentSquare ← 4 } ELSE { IF (mouseX < 200 AND mouseY > 200) { currentSquare ← 2 } ELSE { IF (mouseX > 200 AND mouseY > 200) { currentSquare ← 3 } } } } When mouseX is 173 and mouseY is 271, what will be the value of currentSquare?

2

sum ← 0 i ← 10 REPEAT 11 TIMES { sum ← sum + i i ← i + 1 }

This program sums up the integers from 10 to 20 (inclusive).

A digital artist is writing a program to draw a face. This is the part of the code that draws the eyes and pupils: eyeSize ← RANDOM(5, 20) CIRCLE("white", 20, 20, eyeSize) CIRCLE("white", 40, 20, eyeSize) pupilSize ← RANDOM(2, 5) CIRCLE("black", 20, 20, pupilSize) CIRCLE("black", 40, 20, pupilSize) The code relies on the CIRCLE() procedure from a drawing library, which accepts four parameters for the circle's fill color, x position, y position, and diameter. Here's what's drawn from one run of the program: Two circles with two black circles inside them. Which of these best describes what his program can draw?

Two equally-sized eyes ranging in size, with a minimum size of 5 pixels and a maximum size of 20 pixels. Each eye has a black pupil that ranges in size from a minimum of 2 pixels to a max of 5 pixels.

This program uses a conditional to predict how a baby will be affected by an X-linked disease. IF (motherGene = "mutated" AND babySex = "XY") { babyStatus ← "affected" } ELSE { IF (motherGene = "mutated" AND babySex = "XX") { babyStatus ← "carrier" } ELSE { babyStatus ← "unaffected" } } In which situations will babyStatus be "unaffected"?

When motherGene is "normal" and babySex is "XX" When motherGene is "normal" and babySex is "XY"

The area of the trapezoid is equal to the sum of the length of its bases, multiplied by the half of the height. The program starts with this code: base1 ← 23 base2 ← 42 height ← 7

area ← height / 2 * (base1 + base2) area ← (height / 2) * (base1 + base2)

A javelin thrower is writing code to track the distance of their throws and how far they are from their target distance. This is what they have so far: totalDistance ← 0 targetDistance ← 90 throw1 ← 85.2 DISPLAY(targetDistance - throw1) totalDistance ← totalDistance + throw1 throw2 ← 82.8 DISPLAY(targetDistance - throw2) totalDistance ← totalDistance + throw2 throw3 ← 87.3 DISPLAY(targetDistance - throw3) totalDistance ← totalDistance + throw3 avgDistance ← totalDistance / 3 DISPLAY(avgDistance) A friend points out that they can reduce the complexity of their code by using the abstractions of lists and loops. The programmer decides to "refactor" the code, to rewrite it so that it produces the same output but is structured better.

targetDistance ← 90 throws ← [85.2, 82.8, 87.3] totalDistance ← 0 FOR EACH throw IN throws { DISPLAY(targetDistance - throw) totalDistance ← totalDistance + throw } avgDistance ← totalDistance / LENGTH(throws) DISPLAY(avgDistance)

MouseyBot is currently positioned inside a grid environment, facing left in the fifth row, fourth column. A wedge of DigiCheese is located in the second row, first column. A 4x5 grid of squares. A cheese is located in the first column and second row. A mouse is located in the fourth column and fifth row. MouseyBot would like to reach the DigiCheese. Here's the start of a program that uses a loop to program his journey: REPEAT UNTIL ( canTakeCheese() ) { <MISSING CODE> } There are many ways for him to reach the cheese. Of the options below, which will require the least repetitions of the loop?

walkForward(3) turnRight()

This list represents the leading cars in a race, according to the car numbers: raceCars ← [18, 2, 42, 10, 4, 1, 6, 3] This code snippet updates the list: tempCar ← raceCars[6] raceCars[6] ← raceCars[5] raceCars[5] ← tempCar What does the raceCars variable store after that code runs? Choose 1 answer:

18, 2, 42, 10, 1, 4, 6, 3

A programmer is creating a simulation of a city where natural disasters can randomly occur. This incomplete code segment simulates a Godzilla disaster: IF (<MISSING CONDITION>) { cityHealth ← cityHealth - 30 disasterMode ← "godzilla" } The code should only give Godzilla a 2% chance of storming the city. Which of these can replace <MISSING CONDITION> so that the code works as intended?

RANDOM(1, 100) <= 2

This list represents the horses leading in a race: leadHorses ← ["Justify", "Bravazo", "Good Magic", "Tenfold", "Lone Sailor", "Sporting Chance", "Diamond King", "Quip"] This code snippet updates the list: tempHorse ← leadHorses[3] leadHorses[3] ← leadHorses[4] leadHorses[4] ← tempHorse What does the leadHorses variable store after that code runs?

"Justify", "Bravazo", "Tenfold", "Good Magic", "Lone Sailor", "Sporting Chance", "Diamond King", "Quip"

Landry is writing a program to help her calculate how long it will take to read the books she received for Christmas. The procedure calcReadingHours returns the number of hours it will take her to read a given number of pages, if each page takes a given number of minutes to read. PROCEDURE calcReadingHours(numPages, minPerPage) { totalMin ← numPages * minPerPage RETURN totalMin / 60 } Landry then runs this line of code: hoursNeeded ← calcReadingHours(180, 2)

6

Emanuel is writing a program to decide which fairgoers can ride on the rollercoaster, based on their height. The rollercoaster has a sign posted that states: "RIDERS MUST BE AT LEAST 48" TALL TO RIDE" The variable riderHeight represents a potential rider's height (in inches), and his program needs to set canRide to either true or false. Which of these code segments correctly sets the value of canRide?

IF (riderHeight < 48) { canRide ← false } ELSE { canRide ← true } IF (riderHeight ≥ 48) { canRide ← true } ELSE { canRide ← false }

KittyBot is a programmable robot that obeys the following commands: Name Description walkForward() Walks forward one space in the grid. turnLeft() Rotates left 90 degrees (without moving forward). turnRight() Rotates right 90 degrees (without moving forward). KittyBot is currently positioned in the fourth row and second column of the grid, and is facing the right side of the grid. 5x5 grid of squares. Cat is shown in the square in the fourth row and second column. Water bowl is shown in the square in the first row and fifth column. Water puddle is shown in the square in the second row and third column. We want to program KittyBot to reach the bowl of RoboWater, located in the first row and fifth column, while making sure that she avoids the puddle of water along the way. Which of these code segments accomplishes that goal?

REPEAT 3 TIMES { walkForward() turnLeft() walkForward() turnRight() }

filledWater ← 0 tankCapacity ← 50 fillAmount ← 10 waterHeight ← measureHeight() REPEAT UNTIL (waterHeight ≥ 30 OR filledWater ≥ tankCapacity) { fillTub(fillAmount) filledWater ← filledWater + fillAmount waterHeight ← measureHeight() } Part 1: In what situations will the computer execute the code inside the REPEAT loop? Part 2: What is the maximum times the computer will execute the code inside the REPEAT loop?

When waterHeight is 0 and filledWater is 25 The computer wouldn't execute the code more than 5 times.

rowNum ← 1 numPixels ← 1 REPEAT 3 TIMES { colNum ← 5 - rowNum REPEAT (numPixels) TIMES { fillPixel(rowNum, colNum, "green") colNum ← colNum + 1 } numPixels ← numPixels + 2 rowNum ← rowNum + 1 }

Middle pyramid hanging on the top and not touching sides

IF (ironLevel < 10) { diagnosis ← "anemic" } ELSE { diagnosis ← "normal" } Which of these tables shows the expected values of diagnosis for the given values of ironLevel? Choose 1 answer:

4.5 "anemic" 8.2 "anemic" 9.9 "anemic" 10.0 "normal" 22.5 "normal"

PROCEDURE sayA () { DISPLAY ("Alfa") } PROCEDURE sayB () { DISPLAY ("Bravo") } PROCEDURE sayC () { DISPLAY ("Charlie") } PROCEDURE sayD () { DISPLAY ("Delta") } PROCEDURE sayE () { DISPLAY ("Echo") } sayC () sayA () sayB () sayB () sayE () sayD ()

6

The following numbers are displayed by a program: 4 8 12 16 The program code is shown below, but it is missing three values: <COUNTER>, <AMOUNT>, and <STEP>. i ← <COUNTER> REPEAT <AMOUNT> TIMES { DISPLAY(i * 2) i ← i + <STEP> } Given the displayed output, what must the missing values be? Choose 1 answer:

<COUNTER> = 2, <AMOUNT> = 4, <STEP> = 2

sentence ← "" word1 ← "Hello" firstLetter1 ← SUBSTRING(word1, 1, 1) otherLetters1 ← SUBSTRING(word1, 2, LENGTH(word1) - 1) pigLatin1 ← CONCAT(otherLetters1, firstLetter1, "ay") sentence ← CONCAT(sentence, pigLatin1, " ") word2 ← "Mister" firstLetter2 ← SUBSTRING(word2, 1, 1) otherLetters2 ← SUBSTRING(word2, 2, LENGTH(word2) - 1) pigLatin2 ← CONCAT(otherLetters2, firstLetter2, "ay") sentence ← CONCAT(sentence, pigLatin2, " ") word3 ← "Rogers" firstLetter3 ← SUBSTRING(word3, 1, 1) otherLetters3 ← SUBSTRING(word3, 2, LENGTH(word3) - 1) pigLatin3 ← CONCAT(otherLetters3, firstLetter3, "ay") sentence ← CONCAT(sentence, pigLatin3, " ") DISPLAY(sentence) Which of these is the best refactor of the code?

words ← ["Hello", "Mister", "Rogers"] sentence ← "" FOR EACH word IN words { firstLetter ← SUBSTRING(word, 1, 1) otherLetters ← SUBSTRING(word, 2, LENGTH(word) - 1) pigLatin ← CONCAT(otherLetters, firstLetter, "ay") sentence ← CONCAT(sentence, pigLatin, " ") } DISPLAY(sentence)

MouseyBot is a programmable robot that can be programmed using the following procedures: Name Description walkForward(numSpaces) Walks forward the given number of spaces in the grid. turnLeft() Rotates left 90 degrees (without moving forward). turnRight() Rotates right 90 degrees (without moving forward). facingWall() Returns true if robot is facing a wall (in the space in front). canTakeCheese() Returns true if robot is on a space with cheese. MouseyBot is currently positioned inside a grid environment, facing the top in the fifth row, first column. A wedge of DigiCheese is located in the first row, fifth column. 5x5 grid of squares. Cheese is shown in the first row, fifth column. Mouse is shown in the fifth row, first column, facing the top edge of the grid. MouseyBot would like to reach the DigiCheese. Here's the start of a program that uses a loop to program his journey: REPEAT UNTIL ( canTakeCheese() ) { <MISSING CODE> } There are many ways for him to reach the cheese. Of the options below, which will require the most repetitions of the loop?

IF (facingWall()) { turnRight() } ELSE { walkForward(2) }

Volume=πr 2 3 h ​

PI * (radius * radius) * (height / 3)

Kash is writing code to calculate formulas from his physics class. He's currently working on a procedure to calculate average speed, based on this formula: \text{Average speed} = \dfrac{\text{Total Distance}}{\text{Total Time}}Average speed= Total Time Total Distance ​ A, v, e, r, a, g, e, space, s, p, e, e, d, equals, start fraction, T, o, t, a, l, space, D, i, s, t, a, n, c, e, divided by, T, o, t, a, l, space, T, i, m, e, end fraction Which of these is the best procedure for calculating and displaying average speed? Choose 1 answer:

PROCEDURE calcAvgSpeed (distance, time) { DISPLAY (distance/time) }

Program 1: totalCalories ← 0 loggedMeals ← [700, 800, 600, 300] FOR EACH loggedMeal IN loggedMeals { totalCalories ← totalCalories + loggedMeal } IF (totalCalories > 2000) { excessCalories ← totalCalories - 2000 DISPLAY(excessCalories) } Program 2: totalCalories ← 0 loggedMeals ← [700, 800, 600, 300] FOR EACH loggedMeal IN loggedMeals { totalCalories ← totalCalories + loggedMeal IF (totalCalories > 2000) { excessCalories ← totalCalories - 2000 } } DISPLAY(excessCalories)

Program 1 and Program 2 display the same output, but Program 2 requires more computations.

numA ← INPUT() numB ← INPUT() IF (numA > numB) { DISPLAY(numA) } ELSE { DISPLAY(numB)

The code displays whichever number is bigger, numA or numB.

result ← 1 i ← 6 REPEAT 6 TIMES { result ← result * i i ← i + 3 }

This program multiplies together the multiples of 3 from 6 to 21 (inclusive).

Which of the following expressions results in the string "CAT STUCK IN TREE FOR WEEKS!!!"?

UPPER( CONCATENATE(title2, "!!!")) CONCATENATE( UPPER(title2), "!!!")

APPEND(favMovies, "The Lion King") APPEND(favMovies, "Toy Story") APPEND(favMovies, "The Matrix") APPEND(favMovies, "Shrek") APPEND(favMovies, "Spider-Man") REMOVE(favMovies, 2) INSERT(favMovies, 3, "Lord of the Rings") What does the favMovies variable store after that code runs?

"The Lion King", "The Matrix", "Lord of the Rings", "Shrek", "Spider-Man"

APPEND(localFavs, "Udupi") APPEND(localFavs, "The Flying Falafel") APPEND(localFavs, "Rojbas Grill") APPEND(localFavs, "Cha-Ya") APPEND(localFavs, "Platano") APPEND(localFavs, "Cafe Nostos") INSERT(localFavs, 3, "Gaumenkitzel") REMOVE(localFavs, 5)

"Udupi", "The Flying Falafel", "Gaumenkitzel", "Rojbas Grill", "Platano", "Cafe Nostos"

Problem What is a benefit to using pseudocode?

(Choice C, Checked) C Pseudocode can represent coding concepts common to all programming languages.

costs ← [1.15, 1.25, 2.50, 2.45, 3.75, 2.00] quarterCosts ← [] FOR EACH cost IN costs { costInCents ← cost * 100 IF (costInCents MOD 25 = 0) { <MISSING CODE> } }

(Choice F, Checked) F APPEND(quarterCosts, cost)

words ← ["cab", "lab", "cable", "cables", "bales", "bale"] wordScore ← 0 FOR EACH word IN words { IF (LEN(word) ≥ 5) { wordScore ← wordScore + 3 } ELSE { IF (LEN(word) ≥ 4) { wordScore ← wordScore + 2 } ELSE { IF (LEN(word) ≥ 3) { wordScore ← wordScore + 1 } } } } DISPLAY(wordScore)

13

A computer uses 5 bits to represent positive integers, using all 5 bits to represent the value. Which of the following operations would result in integer overflow?

18 + 14 8 * 4

Jack is creating a text-based card game. He starts off with this code that deals 3 cards: DISPLAY ("Ace of clubs\n") DISPLAY (" ___ \n") DISPLAY ("|A |\n") DISPLAY ("| O |\n") DISPLAY ("|OxO|\n") DISPLAY ("7 of diamonds\n") DISPLAY (" ___ \n") DISPLAY ("|7 |\n") DISPLAY ("| /\|\n") DISPLAY ("|_\/|\n") DISPLAY ("5 of clubs\n") DISPLAY (" ___ \n") DISPLAY ("|5 |\n") DISPLAY ("| O |\n") DISPLAY ("|OxO|\n") After writing that code, Jack decides to use a different way to draw the bottom line of the clubs cards: DISPLAY ("|O,O|\n")

2 1 If he has to update multiple places in the code, the program will run slower.

A vending machine manufacturer is writing code to determine the optimal prices for their products. The program below processes a list of costs (in dollars and cents). The goal of the program is to create a new list that contains only the costs that can be paid entirely in quarters. costs ← [1.15, 1.25, 2.50, 2.45, 3.75, 2.00] quarterCosts ← [] FOR EACH cost IN costs { costInCents ← cost * 100 IF (costInCents MOD 25 = 0) { <MISSING CODE> } } A line of code is missing, however. What can replace <MISSING CODE> so that this program will work as expected?

APPEND(quarterCosts, cost)

This program prompts a user to enter a secret code. Once they type the right code, it lets them continue. But if they make more than 3 bad attempts, it doesn't let them keep guessing. 1: badAttempts ← 0 2: passwordCorrect ← false 3: secretCode ← "banana" 4: REPEAT UNTIL (codeCorrect = true OR badAttempts > 3) 5: { 6: DISPLAY("Enter the secret code") 7: guessedCode ← INPUT() 8: IF (guessedCode = secretCode) 9: { 10: DISPLAY("You're in!") 11: } 12: ELSE 13: { 14: DISPLAY("Beeeep! Try again!") 15: } 16: } This code is incorrect, however: the loop in the code never stops repeating. Where would you add code so that the loop ends when expected?

Between line 10 and 11 Between line 14 and 15

1: startPlayer ← 0 2: REPEAT UNTIL (startPlayer ≠ 0) 3: { 4: player1Roll ← RANDOM(1, 6) 5: player2Roll ← RANDOM(1, 6) 6: IF (player1Roll > player2Roll) 7: { 8: DISPLAY("Player 1 starts") 9: } 10: ELSE IF (player2Roll > player1Roll) 11: { 12: DISPLAY("Player 2 starts") 13: } 14: ELSE 15: { 16: DISPLAY("Roll again") 17: } 18: } Unfortunately, this code is incorrect; the REPEAT UNTIL loop never stops repeating. Where would you add code so that the game starts when expected?

Between line 8 and 9 Between line 12 and 13

Charlee is developing a program to calculate shipping costs for an online clothing store. The clothing store has this shipping policy: Purchase cost Shipping cost Lower than $50 $15 $50 and above $0 (FREE) The variable purchaseCost represents a customer's purchase cost and her program needs to set shippingCost to the appropriate value. Which of these code segments correctly sets the value of shippingCost?

IF (purchaseCost ≥ 50) { shippingCost ← 0 } ELSE { shippingCost ← 15 } IF (purchaseCost < 50) { shippingCost ← 15 } ELSE { shippingCost ← 0 }

An embedded systems engineer is working on an automated popcorn-cooking program for a smart microwave: cookingSeconds ← 400 elapsedSeconds ← 0 numKernels ← countKernels() REPEAT UNTIL (numKernels = 0 OR elapsedSeconds > 700) { cookFor(cookingSeconds) elapsedSeconds ← elapsedSeconds + cookingSeconds cookingSeconds ← cookingSeconds/2 numKernels ← countKernels() } The program relies on two methods provided by the microwave software: Name Description cookFor(numSeconds) Turns the microwave on for the given number of seconds. countKernels() Returns the number of unpopped kernels. Part 1: When will the computer stop executing the code inside the REPEAT loop? 👁️Note that there may be multiple answers to this question.

When numKernels is equal to 0 When elapsedSeconds is greater than 700 The computer wouldn't execute the code more than 4 times.

An audio engineer is writing code to display the durations of various songs. This is what they have so far: totalDuration ← 0 dur1 ← 72 DISPLAY(dur1/60) totalDuration ← totalDuration + dur1 dur2 ← 112 DISPLAY(dur2/60) totalDuration ← totalDuration + dur2 dur3 ← 144 DISPLAY(dur3/60) totalDuration ← totalDuration + dur3 DISPLAY(totalDuration) A friend points out that they can reduce the complexity of their code by using the abstractions of lists and loops. The engineer decides to "refactor" the code, to rewrite it so that it produces the same output but is structured better. Which of these is the best refactor of the code?

durations ← [72, 112, 144] totalDuration ← 0 FOR EACH duration in durations { DISPLAY(duration/60) totalDuration ← totalDuration + duration } DISPLAY(totalDuration)


Kaugnay na mga set ng pag-aaral

Chapter 7: Interest rates and Bond Valuation

View Set

PrepU Chapter 19: Postop Care (Exam 1)

View Set

PrepU Health Assess Ch. 3 Assignment 3

View Set

Pharmacology Central Nervous System Stimulants

View Set