Arjun's khan academy programming unit test
A programmer uses this nested conditional in an online graphing calculator. IF (x < 0 AND y < 0) { quadrant ← "BL" } ELSE { IF (x < 0 AND y > 0) { quadrant ← "TL" } ELSE { IF (x > 0 AND y < 0) { quadrant ← "BR" } ELSE { IF (x > 0 AND y > 0) { quadrant ← "TR" } } } } When x is 52 and y is -23, what will be the value of quadrant?
"BR"
A local search website lets users create lists of their favorite restaurants. When the user first starts, the website runs this code to create an empty list: localFavs ← [] The user can then insert and remove items from the list. Here's the code that was executed from one user's list making session: 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) What does the localFavs variable store after that code runs?
"Udupi", "The Flying Falafel", "Gaumenkitzel", "Rojbas Grill", "Platano", "Cafe Nostos"
Consider the following code segment: x ← 2 y ← 0 z ← -3 result ← max( min(x, y), z) The code relies on these built-in procedures: NameDescriptionmin(a, b)Returns the smaller of the two arguments.max(a, b)Returns the greater of the two arguments. After the code runs, what value is stored in result?
0
Marlon is programming a simulation of a vegetable garden. Here's the start of his code: temperature ← 65 moisture ← 30 acidity ← 3 DISPLAY (acidity) DISPLAY (temperature) DISPLAY (moisture) After running that code, what will be displayed?
3 65 30
Nyala is making a program to display a monster on the screen. This is her code for storing the monster's coordinates: x ← 55 y ← 82 What will be the value of x after this code runs?
55
Consider the following code snippet: DISPLAY (":") DISPLAY ("-") DISPLAY ("O") After the code runs, what is displayed?
: - O (has space)
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: codeCorrect ← 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? 👁️Note that there are 2 answers to this question.
Between line 10 and 11 Between line 14 and 15
Barry is making a program to process user birthdays. The program uses the following procedure for string slicing: NameDescriptionSUBSTRING (string, startPos, numChars)Returns a substring of string starting at startPos of length numChars. The first character in the string is at position 1. His program starts with this line of code: userBday ← "03/31/84" Which of these lines of code displays the day of the month ("31")?
DISPLAY (SUBSTRING (userBday, 4, 2))
A toy for a baby indicates that it should only be used for babies that weigh less than 25 pounds and are less than 30 inches tall. The variable weight represents a baby's weight in pounds and the variable height represents a baby's height in inches. Which of the following expressions evaluates to true if a baby meets the criteria?
NOT (weight ≥ 25) AND NOT (height ≥ 30)
Joline is writing code to calculate formulas from her electrical engineering class. She's currently working on a procedure to calculate electrical resistance, based on this formula: \text{Resistance} = \dfrac{\text{Voltage}}{\text{Current}}Resistance=CurrentVoltagestart text, R, e, s, i, s, t, a, n, c, e, end text, equals, start fraction, start text, V, o, l, t, a, g, e, end text, divided by, start text, C, u, r, r, e, n, t, end text, end fraction Which of these is the best procedure for calculating and displaying resistance?
PROCEDURE calcResistance (voltage, current) { DISPLAY (voltage/current) }
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.
What is a benefit to using pseudocode?
Pseudocode can represent coding concepts common to all programming languages.
Which of these is the best explanation of pseudocode?
Pseudocode is a language that represents concepts across programming languages, but cannot actually be run by a computer.
Ada notices that her classmate's program is very long and none of the code is grouped into procedures. How can Ada persuade her classmate to start organizing their code into procedures?
She can find places where her classmate's program has repeated code, and suggest using a procedure to wrap up that code.
A program races four creatures against each other: a frog, a fox, a dog, and an alien: 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 digital artist is creating an animation with code. Their code needs to convert polar coordinates to cartesian coordinates, using these formulas: x = r × cos( θ )\\y = r × sin( θ )x=r×cos(θ)y=r×sin(θ) The environment provides these built-in procedures: NameDescriptionsin(angle)Returns the sine of the given angle.cos(angle)Returns the cosine of the given angle. In their code, theta represents the current angle and r represents the current radius. Which of these code snippets properly implements the conversion formulas?
x ← r * cos(theta) y ← r * sin(theta)
This code is from a program for a carbon monoxide detector. IF (carbonMonoxide ≥ 70) { state ← "elevated" } ELSE { state ← "normal" } Which of these tables shows the expected values of state for the given values of carbonMonoxide?
carbonMonoxidestate52.6"normal" 69.9"normal" 70.0"elevated" 71.4"elevated" 122"elevated"
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
Consider the following code segment: a ← 2 b ← 4 c ← 6 d ← 8 result ← max( min(a, b), min(c, d) ) The code relies on these built-in procedures: NameDescriptionmin(a, b)Returns the smaller of the two arguments.max(a, b)Returns the greater of the two arguments. After the code runs, what value is stored in result?
6
Rui is creating a digital cook book and is using variables to store the ingredient quantities. Here's the start of his code: onionCount ← 2 garlicCount ← 6 What will be the value of garlicCount after this code runs?
6
Consider the following code snippet: DISPLAY (">") DISPLAY ("_") DISPLAY ("<") After the code runs, what is displayed?
> _ < (has space between the characters)
A visual artist is programming an 8x8 LED display: 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?
the one in the left corner filled in like a triangle
Dario is writing an activity planner program to help him remember what physical activities to do each day. 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" } } } } Which of these tables shows expected values for activity after running this program with a variety of values for today?
todayactivity "Sunday""none"" Monday""swimming" "Tuesday""jogging" "Wednesday""none" "Thursday""juggling" "Friday""none" "Saturday""gardening"
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: 3\text{ m}3 m5\text{ m}5 m4\text{ m}4 m 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? 👁️Note that there may be multiple answers to this question.
trapezoidArea (5, 3, 4) trapezoidArea (3, 5, 4)
Demi is writing a program to calculate chemistry formulas for a science experiment. Her procedure calcPressure should return the pressure of a gas, based on the ideal gas formula: \text{P}=\dfrac{\text{nRT}}{\text V}P=VnRTstart text, P, end text, equals, start fraction, start text, n, R, T, end text, divided by, start text, V, end text, end fraction \,\,1PROCEDURE calcPressure (numMoles, temp, volume)2{3\,\,\,\,R ← 8.314414\,\,\,\,topPart ← numMoles * R * temp5\,\,\,\,pressure ← topPart / volume6} 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 5 RETURN pressure
A nutrition scientist is working on code to calculate the most magnesium-rich foods. Their program processes a list of numbers representing milligrams of magnesium in servings of food. The goal of the program is to create a new list that contains only the numbers that represent at least 30% of the recommended daily intake of 360 milligrams. 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> } } A line of code is missing, however. What can replace <MISSING CODE> so that this program will work as expected?
APPEND(bestAmounts, mgAmount)
This code is from a website error monitoring system. IF (currentNum > expectedNum) { status ← "Elevated error rate" } ELSE { status ← "All is well" } Which of these tables shows the expected values of status for the given values of currentNum and expectedNum?
currentNumexpectedNumstatus 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"
Regina is writing a program to process user-inputted phone numbers. The program relies on multiple string operations: PseudocodeDescriptionCONCAT(string1, string2)Concatenates (joins) two strings to each other, returning the combined string.TRIM(string)Removes any whitespace at the beginning or end of string. Here's a snippet of her code: userPhone ← " 202-555-0183 " usCode ← "+1" usPhone ← CONCAT(usCode, TRIM(userPhone)) What value does the usPhone variable store?
"+1202-555-0183"
Ayaan is writing a program that generates wizard spells. The program relies on multiple string operations: PseudocodeDescriptionCONCAT(string1, string2)Concatenates (joins) two strings to each other, returning the combined string.UPPER(string)Returns the string in uppercase. Here's a snippet of his code: start ← "Bibbidi Bobbidi" end ← "Boo" spell ← CONCAT(start, UPPER(end)) What value does the spell variable store?
"Bibbidi BobbidiBOO"
The following code segment stores and updates a list of cities to visit: topCities ← ["Kyoto", "Florianopolis", "Wellington", "Puerto Viejo", "Sevilla"] topCities[2] ← "Ankara" topCities[4] ← "Taipei" After running that code, what does the topCities list store?
"Kyoto", "Ankara", "Wellington", "Taipei", "Sevilla"
Corey is experimenting with assigning and displaying variables. Here's his code: test1 ← 200 DISPLAY (test1) test2 ← 100 test2 ← test1 DISPLAY (test2) test1 ← test2 DISPLAY (test1) What will be the output of that code?
200 200 200
The following code snippet processes a list of strings with a loop and conditional: 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. What value will this program display?
3
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?
4.7"low" 5.4"low" 5.5"optimal" 6.2"optimal" 6.5"optimal" 6.7"high" 7.2"high"
Darrell is making a program to track his grades. He made the mistake of using the same variable name to track 3 different test grades, though. Here's a snippet of his code: a ← 89 a ← 97 a ← 93 What will be the value of a after this code runs?
93
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" [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" }
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? 👁️Note that there are 2 answers to this question.
IF (riderHeight < 48) { canRide ← false } ELSE { canRide ← true } IF (riderHeight ≥ 48) { canRide ← true } ELSE { canRide ← false }
A visual artist is programming a 7x7 LED display: 7x7 grid of squares. This is their program so far: 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 } 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 1 and the left-most column is column 1. What will the output of their program look like?
One in the middle like dead center
KittyBot is a programmable robot that obeys the following commands: NameDescriptionwalkForward()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. 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() }
Haruki is writing a program to share fun emoticons: DISPLAY ("Going for a walk:") DISPLAY ("ᕕ( ᐛ )ᕗ") The following paragraph describes how the program works.
This is a computer program with 2 statements. Each statement calls a procedure named DISPLAY which expects a single parameter to determine what to display on the screen.
The code segment below uses a loop to repeatedly sum up numbers. sum ← 0 i ← 10 REPEAT 11 TIMES { sum ← sum + i i ← i + 1 } Which description best describes what this program does?
This program sums up the integers from 10 to 20 (inclusive).
This program uses a conditional to determine whether a child will have free or attached earlobes. if (fatherAllele = "G" OR motherAllele = "G") { earlobeType ← "free" } ELSE { earlobeType ← "attached" } In which situations will earlobeType be "free"? 👁️Note that there may be multiple answers to this question.
When fatherAllele is "G" and motherAllele is "G" When fatherAllele is "G" and motherAllele is "g" When fatherAllele is "g" and motherAllele is "G"
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). Which of these code snippets properly implements the wave formula?
amp * cos( ((2 * PI)/wL) * x)
Greg is hosting a chocolate tasting night for his friends to taste chocolate truffles. He's writing a program to help him plan the festivities. The box of chocolates comes with 35 truffles, and there will be 6 people at the party. numChocolates ← 35 numPeople ← 6 Greg is going to distribute the truffles evenly and then save the extras for himself. Which line of code successfully calculates and stores the number of extra truffles?
numExtras ← numChocolates MOD numPeople
Phoebe is holding a pie eating party and is writing a program to help her determine what ice cream to pair with each pie. IF (pie = "apple") { iceCream ← "caramel" } ELSE { IF (pie = "razzleberry") { iceCream ← "cinnamon" } ELSE { IF (pie = "peach") { iceCream ← "nutmeg" } ELSE { IF (pie = "plum") { iceCream ← "honey" } ELSE { iceCream ← "vanilla" } } } } Which of these tables shows expected values for iceCream after running this program with a variety of values for pie?
pieiceCream "cherry""vanilla" "apple""caramel" "razzleberry""cinnamon" "coconut""vanilla" "peach""nutmeg" "raspberry""vanilla" "plum""honey"
The following variable assignments are from an online music app. Identify which variables store numbers and which store strings:
title ← "I am a rock" string minutes ←2 number seconds ← 50 number artist ← "Simon & Garfunkel" string recorded ← "Dec 14, 1965" string
A programmer for a music company is developing a program to determine the highest level of certification for an album. The program needs to follow this table of thresholds for each certification level: Minimum albums soldCertification500,000gold1,000,000platinum10,000,000diamond The code segment below uses nested conditionals to assign the certification variable to the appropriate value, but its conditions are missing operators. certification ← "none" IF (albumsSold <?> 10000000) { certification ← "diamond" } ELSE { IF (albumsSold <?> 1000000) { certification ← "platinum" } ELSE { IF (albumsSold <?> 500000) { certification ← "gold" } } } Which operator could replace <?> so that the code snippet works as expected?
≥
This short program displays the winning result in a ship naming contest: DISPLAY ("Schoolie") DISPLAY ("McSchoolFace") Part 1: How many statements are in the above program? Part 2: What does the program output?
2 Schoolie McSchoolFace
Darian is coding a program that draws a face and is storing the eye coordinates in variables. They mistakenly used the same variable names for both eyes, however: eyeX ← 200 eyeX ← 250 What will be the value of eyeX after this code runs?
250
The code segment below uses a loop to repeatedly operate on a sequence of numbers. result ← 1 i ← 6 REPEAT 6 TIMES { result ← result * i i ← i + 3 } Which description best describes what this program does?
This program multiplies together the multiples of 3 from 6 to 21 (inclusive).
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? 👁️Note that there may be multiple answers to this question.
stepsPerMin ← (stepsPerDay / hoursAwake) / 60 stepsPerMin ← stepsPerDay / hoursAwake / 60
Seth is writing a dialogue engine for an emergency preparedness game. The program relies on multiple string operations: PseudocodeDescriptionCONCAT(string1, string2)Concatenates (joins) two strings to each other, returning the combined string.UPPER(string)Returns the string in uppercase. Here's a snippet of his code: yell ← "ahhhh" danger ← "fire!" emoted ← CONCAT(yell, UPPER(danger)) What value does the emoted variable store?
"ahhhhFIRE!"
Brayden is writing code to calculate the surface area of a cylinder based on this formula: \text{Surface area} = 2 \pi r h + 2 \pi r^2Surface area=2πrh+2πr2start text, S, u, r, f, a, c, e, space, a, r, e, a, end text, equals, 2, pi, r, h, plus, 2, pi, r, squared He's testing the code on this cylinder: 2233 The code starts with these variables, where radius represents rrr and height represents hhh: radius ← 3 height ← 2 The built-in constant PI stores an approximation of \piπpi. Which expression correctly calculates the surface area?
(2 * PI * radius * height) + (2 * PI * radius * radius)
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?
18, 2, 42, 10, 1, 4, 6, 3
This program uses a nested conditional to assign the variable mystery to a value: 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?
24
Aleena is developing a program to track her weekly fitness routine. Here is a part of her program that sets up some variables: type ← "swimming" day ← "wednesday" duration ← 50 laps ← 20 location ← "YMCA" How many string variables is this code storing?
3
Dixie is planning a water balloon fight for her birthday party and writing a program to help calculate how many bags of balloons they'll need to buy. The procedure calcBalloonBags returns the number of bags needed for a given number of players, number of rounds, and number of balloons in the bag. PROCEDURE calcBalloonBags(numPlayers, numRounds, balloonsInBag) { numTeams ← FLOOR(numPlayers / 2) numBalloons ← numTeams * numRounds RETURN CEILING(numBalloons / balloonsInBag) } This procedure relies on two built-in procedures, FLOOR for rounding a number down and CEILING for rounding a number up, which avoids the issue of partial teams and partial bags. Dixie then runs this line of code: bagsNeeded ← calcBalloonBags(30, 10, 50) What value is stored in bagsNeeded?
3
Everett is developing a photo editing app. Here is a part of his program that sets up some variables: filter ← "sepia" width ← 640 width ← 480 border ← "grooved" filename ← "1456.jpg" How many string variables is this code storing?
3
Damien is writing a program to teach Elvish languages: DISPLAY ("Mae govannen!") DISPLAY ("=") DISPLAY ("Well met!") The following paragraph describes how the program works.
3 procedure parameter
This program uses a nested conditional to assign the variable mystery to a value: IF (x > y) { mystery ← x - y } ELSE { IF (x = y) { mystery ← y / x } ELSE { mystery ← x * y } } If we set x to 4 and y to 8, what value will the mystery variable store after running this code?
32
The procedure calcSwimYards returns the number of yards swam 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: yardsSwam ← calcSwimYards(25, 10) What value is stored in yardsSwam?
500
This code snippet stores and updates a list that represents playing cards in a player's deck: 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]) What does this program output to the display?
7 8
Danielle is programming a kitty simulator. Here's part of her code: hunger ← 6 cuddliness ← 9 playfulness ← 7 DISPLAY (playfulness) DISPLAY (cuddliness) DISPLAY (hunger) After running that code, what will be displayed?
7 9 6
Consider the following code snippet: DISPLAY (":") DISPLAY ("-") DISPLAY ("D") After the code runs, what is displayed?
: - D (with space)
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?
<COUNTER> = 2, <AMOUNT> = 4, <STEP> = 2
A software engineer for a movie theater is writing a program to calculate ticket prices based on customer ages. The program needs to implement this pricing chart: Ticket typePriceGeneral Admission$16Senior (Ages 65+)$12Child (Ages 2-12)$8Infants (Ages 0-1)Free The code segment below uses nested conditionals to assign the price variable to the appropriate value, but its conditions are missing operators. price ← 0 IF (age <?> 64) { price ← 12 } ELSE { IF (age <?> 12) { price ← 16 } ELSE { IF (age <?> 1) { price ← 8 } } } Which operator could replace <?> so that the code snippet works as expected?
>
unit and collect up to 1600 Mastery pointsTake Unit test again About this unit This unit introduces fundamental programming concepts. Learn about variables, strings, procedures, Boolean logic, randomness, repetition, and lists, with examples in JavaScript, Snap, Python. With more than 200 questions written in the AP CSP exam pseudocode, you can practice what you've learned and study for the AP Computer Science Principles exam. Unit test Problem This program simulates two players rolling dice to determine the start player for a game. Once a player rolls a die higher in value than the other player, that player starts the game. 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? 👁️Note that there are 2 answers to this question.
Between line 8 and 9 Between line 12 and 13
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) Which of these statements best describes these two programs?
Both programs display the correct total number of hours, but Program 2 unnecessarily repeats arithmetic operations.
Barry is making a program to process user birthdays. The program uses the following procedure for string slicing: NameDescriptionSUBSTRING (string, startPos, numChars)Returns a substring of string starting at startPos of length numChars. The first character in the string is at position 1. His program starts with this line of code: userBday ← "03/31/84" Which of these lines of code displays the year ("84")?
DISPLAY (SUBSTRING (userBday, 7, 2))
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?
Program 1 displays the expected output, while Program 2 displays more output than necessary.
The code below processes two numerical values with a conditional statement. numA ← INPUT() numB ← INPUT() IF (numA < numB) { DISPLAY(numA) } ELSE { DISPLAY(numB) } The code relies on a built-in procedure, INPUT(), which prompts the user for a value and returns it. Which of the following best describes the result of running this code?
The code displays whichever number is smaller (numA or numB) or displays numB if they are equal.
This program uses a nested conditional to recommend a heat level for cooking eggs. IF (inHurry = true AND eggDish = "fried") { heatLevel ← "high" } ELSE { IF (inHurry = false AND eggDish = "scrambled") { heatLevel ← "low" } ELSE { heatLevel ← "medium" } } In which situations will heatLevel be "medium"? 👁️Note that there may be multiple answers to this question.
When inHurry is false and eggDish is "fried" When inHurry is true and eggDish is "scrambled"
Gabriel is writing a program to calculate the area of a trapezoid, based on this formula: A = \dfrac{h}{2}(b_1 + b_2)A=2h(b1+b2)A, equals, start fraction, h, divided by, 2, end fraction, left parenthesis, b, start subscript, 1, end subscript, plus, b, start subscript, 2, end subscript, right parenthesis 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 Which lines of code successfully calculate the area? 👁️Note that there may be multiple answers to this question.
area ← (height / 2) * (base1 + base2) area ← height / 2 * (base1 + base2)
A pool manager is writing a program to make sure their swimming pools contain a safe level of chlorine. IF (chlorinePPM > 3.0) { chlorineLevel ← "high" } ELSE { IF (chlorinePPM < 1.0) { chlorineLevel ← "low" } ELSE { chlorineLevel ← "safe" } } Which of these tables shows the expected values of chlorineLevel for the given values of chlorinePPM?
chlorinePPMchlorineLevel 0.0"low" 0.9"low" 1.0"safe" 2.6"safe" 3.0"safe" 3.2"high" 4.5"high"
This code is from a program that diagnoses anemia, a health condition. IF (ironLevel < 10) { diagnosis ← "anemic" } ELSE { diagnosis ← "normal" } Which of these tables shows the expected values of diagnosis for the given values of ironLevel?
ironLeveldiagnosis 4.5"anemic" 8.2"anemic" 9.9"anemic" 10.0"normal" 22.5"normal"
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 Which of these code snippets successfully calculates and stores her total footprint? 👁️Note that there are 2 answers to this question.
laNyCarbon ← calcFlightFootprint(2451, 118) nyLondonCarbon ← calcFlightFootprint(3442, 252) totalFootprint ← laNyCarbon + nyLondonCarbon totalFootprint ← calcFlightFootprint(2451, 118) + calcFlightFootprint(3442, 252)
Kunto is working on a program for generating baby name ideas. Her program uses the following procedure for string concatenation: PseudocodeDescriptionconcatenate(string1, string2)Concatenates (joins) two strings to each other, returning the combined string. These variables are at the start of her program: first1 ← "Ella" first2 ← "Kai" mid1 ← "Mae" mid2 ← "Lynn" Which line of code would store the string "Kai Lynn"?
name ← concatenate(concatenate(first2, " "), mid2)
DonorsChoose is a website that lets people find classrooms to financially support: The code to display the search results relies on many variables. Which of these variables are storing a string data type? 👁️Note that there may be multiple answers to this question.
queryNear ← "13078" query ← "sensory" category ← "Special Needs" projectTitle ← "Jumpin' To Learn!"
Isabel is programming an app called Plantwatch, which lets users monitor the health of their plants. Which variables would she most likely use a string data type for?
species: The name of the plant species
Google Maps lets users search for anything in the world: The code to display the map and search results relies on many variables. Which of these variables are storing a string data type? 👁️Note that there may be multiple answers to this question.
state ← "CA" searchQuery ← "90210" weather ← "Partly Cloudy" city ← "Beverly Hills"
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: 4\text{ m}4 m7\text{ m}7 m3\text{ m}3 m Trapezoid diagram with upper base of 7 meters, lower base of 4 meters, and height of 3 meters. Which of these lines of code correctly calls the procedure to calculate the area of this trapezoid? 👁️Note that there may be multiple answers to this question.
trapezoidArea (4, 7, 3) trapezoidArea (7, 4, 3)
Aden is working on a program that can generate domain names. His program uses the following procedure for string concatenation: PseudocodeDescriptionconcatenate(string1, string2)Concatenates (joins) two strings to each other, returning the combined string. These variables are at the start of his program: company ← "cactus" tld1 ← "com" tld2 ← "io" Which line of code would store the string "cactus.io"?
name2 ← concatenate(company, concatenate(".", tld2))
The following variable assignments are from a family tree program. Identify which variables store numbers and which store strings:
numSiblings ← 3 number fatherName ← "Godfrey" string motherName ← "Rosemarie" string birthYear ← 2003 number birthMonth ← 6 number
Veda is writing code to calculate the volume of a cylinder based on this formula: \text{Volume} = \pi r^2 hVolume=πr2hstart text, V, o, l, u, m, e, end text, equals, pi, r, squared, h She's testing her code on this cylinder: 3344 The code starts with these variables, where radius represents rrr and height represents hhh: radius ← 4 height ← 3 The built-in constant PI stores an approximation of \piπpi. Which expression correctly calculates the volume?
PI * (radius * radius) * (height)
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=MassForcestart text, A, c, c, e, l, e, r, a, t, i, o, n, end text, equals, start fraction, start text, F, o, r, c, e, end text, divided by, start text, M, a, s, s, end text, end fraction Which of these is the best procedure for calculating and displaying acceleration?
PROCEDURE calcAcceleration (force, mass) { DISPLAY (force/mass) }
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"? 👁️Note that there may be multiple answers to this question.
When motherGene is "normal" and babySex is "XX" When motherGene is "normal" and babySex is "XY"
Camilla is planning a birthday party where she'll fill various rooms in her house with colorful plastic balls, and is writing a program to help her with the planning. This procedure calculates the total number of balls needed for a room of a given length, width, and number of layers: PROCEDURE calcBallCount(width, length, layers) { BALL_DIAMETER ← 0.1 numPerWidth ← FLOOR(width/BALL_DIAMETER) numPerLength ← FLOOR(length/BALL_DIAMETER) ballsPerLayer ← numPerWidth * numPerLength ballCount ← ballsPerLayer * layers RETURN ballCount } Camilla wants to use that procedure to calculate the total ball count for two rooms: bathroom: 2 meters by 2.5 meters, 3 layers deep garage: 3 meters by 3 meters, 2 layers deep Which of these code snippets successfully calculates and stores the total ball count? 👁️Note that there are 2 answers to this question.
bathroomCount ← calcBallCount(2, 2.5, 3) garageCount ← calcBallCount(3, 3, 2) totalCount ← bathroomCount + garageCount totalCount ← calcBallCount(2, 2.5, 3) + calcBallCount(3, 3, 2)
Fletcher is making an online ticket buying system for a museum. His program needs to calculate the final cost of a ticket with extra options added, a planetarium show and an IMAX 3D movie. The initial code looks like this: ticket ← 32 starShow ← 16 imax3D ← 9 Which code successfully calculates and stores the final cost? 👁️Note that there may be multiple answers to this question.
finalCost ← ticket + imax3D + starShow finalCost ← ticket + starShow + imax3D
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. What value will this program display?
2
A children's book editor is writing code to detect words that are too large for a target reading level. Their program processes a list of words from sentences in the book, and creates a new list with the words that are too large, those with more than 5 letters. words ← ["See", "Jane", "run", "swiftly", "towards", "home"] bigWords ← [] FOR EACH word IN words { IF (LEN(word) > 5) { <MISSING CODE> } } The code relies on one string procedure, LEN(string), which returns the number of characters in the string. As you can see, a line of code is missing. What can replace <MISSING CODE> so that this program will work as expected?
APPEND(bigWords, word)
Charlee is developing a program to calculate shipping costs for an online clothing store. The clothing store has this shipping policy: Purchase costShipping costLower 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? 👁️Note that there are 2 answers to this question.
IF (purchaseCost ≥ 50) { shippingCost ← 0 } ELSE { shippingCost ← 15 } IF (purchaseCost < 50) { shippingCost ← 15 } ELSE { shippingCost ← 0 }
Giovanni is researching cars, so that he can buy his first car. He's very interested in how many miles his future car can go on a full tank, as he loves to go on very long road trips. He makes this program to compare the different fuel tank capacity and miles per gallon of the cars he's considering: fuelCapacity ← 16.5 milesPerGallon ← 30 milesPerTank ← fuelCapacity * milesPerGallon DISPLAY(CONCAT(fuelCapacity, CONCAT(" x ", milesPerGallon))) DISPLAY(CONCAT(" = ", milesPerTank)) fuelCapacity ← 18.5 milesPerGallon ← 28 milesPerTank ← fuelCapacity * milesPerGallon DISPLAY(CONCAT(fuelCapacity, CONCAT(" x ", milesPerGallon))) DISPLAY(CONCAT(" = ", milesPerTank)) fuelCapacity ← 14.5 milesPerGallon ← 40 milesPerTank ← fuelCapacity * milesPerGallon DISPLAY(CONCAT(fuelCapacity, CONCAT(" x ", milesPerGallon))) DISPLAY(CONCAT(" = ", milesPerTank)) Giovanni realizes his program has a lot of duplicate code, and decides to make a procedure to reduce the duplicated code. Which of these procedures best generalizes his code for easy reuse?
PROCEDURE calcMilesPerTank(fuelCapacity, milesPerGallon) { milesPerTank ← fuelCapacity * milesPerGallon DISPLAY(CONCAT(fuelCapacity, CONCAT(" x ", milesPerGallon))) DISPLAY(CONCAT(" = ", milesPerTank)) }
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=T2/R3start text, C, o, n, s, t, a, n, t, end text, equals, T, squared, slash, R, cubed 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: NameDescriptionadd(n, m)Returns the addition of n to m.sqrt(n)Returns the square root of nnn.square(n)Returns the value of n^2n2n, squared.cube(n)Returns the value of n^3n3n, cubed.pow(n, m)Returns the value of n^mnmn, start superscript, m, end superscript. How could the code be rewritten using the procedures? 👁️Note that there are 2 answers to this question.
keplerRatio ← square(period) / cube(radius) keplerRatio ← pow(period, 2) / pow(radius, 3)
This is a computer program with 2 statements. Each statement calls a procedure named DISPLAY which expects a single parameter to determine what to display on the screen.
Nothing will be displayed
Viktoria is writing a program to communicate with pirates: DISPLAY ("Ahoy") DISPLAY ("mateys!") The following paragraph describes how the program works.
This is a computer program with 2 statements. Each statement calls a procedure named DISPLAY which expects a single parameter to determine what to display on the screen.
A program races four avatars against each other: Piceratops, Leafers, Duskpin, and Aqualine. Here they are lined up at the start line, in that order: Each of the avatars is controlled by a different program. Piceratops: moveAmount ← 2 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount + 1 } Leafers: moveAmount ← 0 REPEAT UNTIL ( reachedFinish() ) { moveAmount ← moveAmount + 2 moveForward(moveAmount) } Duskpin: moveAmount ← 5 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount - 2 } Aqualine: moveAmount ← 2 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.
Neriah is writing code for a website that publishes attention-grabbing news articles. The code relies on multiple string operations: PseudocodeDescriptionCONCATENATE(string1, string2)Concatenates (joins) two strings to each other, returning the combined string.UPPER(string)Returns the string in uppercase. Her code uses these variables: title1 ← "Cat rips Xmas tree to shreds" title2 ← "Cat stuck in tree for weeks" title3 ← "New world record: fluffiest cat ever" Which of the following expressions results in the string "CAT STUCK IN TREE FOR WEEKS!!!"? 👁️Note that there are 2 answers to this question.
UPPER( CONCATENATE(title2, "!!!") ) CONCATENATE( UPPER(title2), "!!!")
This program uses a conditional to predict the hair type of a baby. IF (fatherAllele = "C" AND motherAllele = "C") { hairType ← "curly" } ELSE { IF (fatherAllele = "s" AND motherAllele = "s") { hairType ← "straight" } ELSE { hairType ← "wavy" } } In which situations will hairType be "wavy"? 👁️Note that there may be multiple answers to this question.
When fatherAllele is "s" and motherAllele is "C" When fatherAllele is "C" and motherAllele is "s"
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: NameDescriptioncookFor(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. Part 2: What is the maximum times the computer will execute the code inside the REPEAT loop?
When numKernels is equal to 0 When elapsedSeconds is greater than 700 The computer wouldn't execute the code more than 4 times.
This program uses a conditional to determine if seafood is safe to consume. IF (seafood = "mollusk" OR daysFrozen ≥ 7) { rating ← "safe" } ELSE { rating ← "unsafe" } In which situations will rating be "safe"? 👁️Note that there may be multiple answers to this question.
When seafood is "mollusk" and daysFrozen is 9 When seafood is "salmon" and daysFrozen is 7 When seafood is "mollusk" and daysFrozen is 1
An embedded systems engineer is writing a program to automate filling a bath tub with water: filledWater ← 0 tankCapacity ← 50 fillAmount ← 10 waterHeight ← measureHeight() REPEAT UNTIL (waterHeight ≥ 30 OR filledWater ≥ tankCapacity) { fillTub(fillAmount) filledWater ← filledWater + fillAmount waterHeight ← measureHeight() } The program relies on two methods provided by the tub software: NameDescriptionfillTub(numGallons)Fills the tub with the specified number of gallons of water.measureHeight()Returns the height of the water in the tub, in inches. Part 1: In what situations will the computer execute the code inside the REPEAT loop? 👁️Note that there may be multiple answers to this question. 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.
Nikolas is writing a program to calculate the area of a triangle, based on this formula: A = \dfrac{bh}{2}A=2bhA, equals, start fraction, b, h, divided by, 2, end fraction The area of the triangle is equal to the length of the base multiplied by the height, all divided by 2. The program starts with this code: base ← 37 height ← 21 Which lines of code successfully calculate the area? 👁️Note that there may be multiple answers to this question.
area ← (base * height) / 2 area ← base * height / 2
Osian is making an online shopping comparison site. His code needs to compare the cost of two items and show the difference. The initial code looks like this: item1Cost ← 32 item2Cost ← 29 Which code successfully calculates and stores how much more expensive item1 is than item2? 👁️Note that there may be multiple answers to this question.
costDiff ← item1Cost - item2Cost costDiff ← item1Cost + (-1 * item2Cost) costDiff ← (item1Cost - item2Cost)
A movie website lets users create lists of their favorite movies. When the user first starts, the website runs this code to create an empty list: favMovies ← [] The user can then insert and remove items from the list. Here's the code that was executed from one user's session: 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"
The following code segment stores and updates a list of cool dinosaurs: coolDinos ← ["Triceratops", "Stegosaurus", "Ankylosaurus", "Ultrasauros", "Therizinosaurus"] coolDinos[1] ← "Torosaurus" coolDinos[4] ← "Supersaurus" After running that code, what does the coolDinos list store?
"Torosaurus", "Stegosaurus", "Ankylosaurus", "Supersaurus", "Therizinosaurus"
Joselyn is developing a recipes app. Here is a part of her program that sets up some variables: title ← "Mashed parsnips" prepTime ← 10 cookTime ← 30 rating ← 4.5 category ← "veggies" How many string variables is this code storing?
2
Tyrone 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, Tyrone decides to use a different way to draw the bottom line of the clubs cards: DISPLAY ("|O,O|\n") Part 1: How many lines will Tyrone need to update in his code? Now imagine that Tyrone had originally defined a procedure to draw the club cards, like so: PROCEDURE drawClubs () { DISPLAY ("| O |\n") DISPLAY ("|OxO|\n") } DISPLAY ("Ace of clubs\n") DISPLAY (" ___ \n") DISPLAY ("|A |\n") drawClubs () DISPLAY ("7 of diamonds\n") DISPLAY (" ___ \n") DISPLAY ("|7 |\n") DISPLAY ("| /\\|\n") DISPLAY ("|_\\/|\n") DISPLAY ("5 of clubs\n") DISPLAY (" ___ \n") DISPLAY ("|5 |\n") drawClubs () Part 2: Given this starting code, if Tyrone decides on a new way to draw the bottom line of the clubs, how many lines will he need to update? Part 3: Which of these is not a drawback of Tyrone having to update code in multiple places?
2 1 If he has to update multiple places in the code, the program will run much slower.
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)
Jace is making a simulation of conversations with his 2-year-old son. Here's the program: PROCEDURE yellNo () { DISPLAY ("NOOOO!") DISPLAY ("😭😭😭") } DISPLAY ("Can you wear your gloves?") yellNo () DISPLAY ("How about a scarf?") yellNo () DISPLAY ("What about this super soft hat?") yellNo () In total, how many times does this code call the yellNo procedure?
3
Stella is making a program to explain how to make her family's famous lasagna. Here's part of the program: PROCEDURE makeLayer () { DISPLAY ("Spread 2 cups sauce") DISPLAY ("Lay 3 noodles on top") DISPLAY ("Slather 1/3 of ricotta mixture") DISPLAY ("Sprinkle with 1 cup of Mozzarella") DISPLAY ("Scatter 2 tablespoons of Parmesan") } DISPLAY ("Cook noodles according to package") DISPLAY ("Make sauce by heating up tomatoes and basil") DISPLAY ("Mix egg, ricotta cheese, parsley, and salt") makeLayer () makeLayer () makeLayer () In total, how many times does this code call the makeLayer procedure?
3
This program uses a nested conditional to assign the variable mystery to a value: IF (x > y) { mystery ← x - y } ELSE { IF (x < y) { mystery ← y / x } ELSE { mystery ← x + y } } If we set x to 8 and y to 24, what value will the mystery variable store after running this code?
3
Simone is writing a program to report on her daily moods. Here's her program for the first week: DISPLAY ("Monday: I feel happy!") DISPLAY ("(•‿•)") DISPLAY ("Tuesday: Sigh, annoyed") DISPLAY ("ಠ_ಠ") DISPLAY ("Wednesday: Feeling happy again") DISPLAY ("(•‿•)") DISPLAY ("Thursday: Kind of confused") DISPLAY ("(⊙_☉)") DISPLAY ("Friday: TGIF! Whee!") DISPLAY ("(•‿•)") After writing that code, Simone finds a new way to draw the happy face: DISPLAY ("。◕‿◕。") Part 1: How many lines of code will Simone need to update? Now imagine that Simone had originally defined a procedure to draw the happy face, like so: PROCEDURE drawHappy () { DISPLAY ("(•‿•)") } DISPLAY ("Monday: I feel happy!") drawHappy () DISPLAY ("Tuesday: Sigh, annoyed") DISPLAY ("ಠ_ಠ") DISPLAY ("Wednesday: Feeling happy again") drawHappy () DISPLAY ("Thursday: Kind of confused") DISPLAY ("(⊙_☉)") DISPLAY ("Friday: TGIF! Whee!") drawHappy () Part 2: Given this starting code, if Simone decides on a new way to draw the happy face, how many lines of code will she need to update? Part 3: Which of these is not a drawback of Simone having to update code in multiple places?
3 1 If she has to update multiple places in the code, the program will run much slower.
This short program displays the winning result in the Greenpeace whale naming contest: DISPLAY ("Mister") DISPLAY ("Splashy") DISPLAY ("Pants") Part 1: How many statements are in the above program? Part 2: What does the program output?
3 Mister Splashy Pants
Emmet is creating a program to display words in their binary form, according to the ASCII encoding standard. This is what his program contains so far: PROCEDURE showA () { DISPLAY ("01000001") } PROCEDURE showB () { DISPLAY ("01000010") } PROCEDURE showC () { DISPLAY ("01000011") } PROCEDURE showD () { DISPLAY ("01000100") } PROCEDURE showE () { DISPLAY ("01000101") } showD () showA () showB () showB () showE () showD () When this program executes, how many total calls does it make to the DISPLAY procedure?
6
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) What value is stored in hoursNeeded?
6
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). Which line of code successfully calculates and stores the number of leftover crackers in the final box?
extras ← crackersPerBox - (neededCrackers MOD crackersPerBox)
Angelique is creating a text-based weather report. She starts off with this code that reports the weather in 3 cities: DISPLAY ("Portland: 56 °F, Rainy\n") DISPLAY (" _ - _ - _ - \n") DISPLAY (" _ - _ - _ \n") DISPLAY (" _ - _ - _ - \n") DISPLAY ("Buffalo: 52 °F, Cloudy\n") DISPLAY (" .--. \n") DISPLAY (" .-( ). \n") DISPLAY ("(___.__)__) \n") DISPLAY ("Seattle: 43 °F, Rainy\n") DISPLAY (" _ - _ - _ - \n") DISPLAY (" _ - _ - _ \n") DISPLAY (" _ - _ - _ - \n") After writing that code, Angelique decides on a different way to draw the raining illustration: DISPLAY (" ' ' ' '\n") DISPLAY (" ' ' ' ' \n") DISPLAY ("' ' ' ' \n") Part 1: How many lines of code will Angelique need to update? Now imagine that Angelique had originally defined a procedure to draw the rain, like so: PROCEDURE drawRain () { DISPLAY (" _ - _ - _ - \n") DISPLAY (" _ - _ - _ \n") DISPLAY (" _ - _ - _ - \n") } DISPLAY ("Portland: 56 °F, Rainy\n") drawRain () DISPLAY ("Buffalo: 52 °F, Cloudy\n") DISPLAY (" .--. \n") DISPLAY (" .-( ). \n") DISPLAY ("(___.__)__) \n") DISPLAY ("Seattle: 43 °F, Rainy\n") drawRain () Part 2: Given this starting code, if Angelique decides on a new way to draw the rain, how many lines of code will she need to update? Part 3: Which of these is not a drawback of Angelique having to update code in multiple places?
6 3 If she has to update multiple places in the code, the program will run much slower.
Shari is making an app to sing her favorite silly songs. Here's part of the code: PROCEDURE singVerse () { DISPLAY ("This is the song that never ends.") DISPLAY ("Yes, it just goes on and on my friends.") DISPLAY ("Some people started singing it, not knowing what it was,") DISPLAY ("And they'll continue singing it forever just because...") } singVerse () singVerse () singVerse () singVerse () singVerse () singVerse () singVerse () In total, how many times does this code call the singVerse procedure?
7
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
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
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=(x2−x1)2+(y2−y1)2d, equals, square root of, left parenthesis, x, start subscript, 2, end subscript, minus, x, start subscript, 1, end subscript, right parenthesis, squared, plus, left parenthesis, y, start subscript, 2, end subscript, minus, y, start subscript, 1, end subscript, right parenthesis, squared, 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
Allyson is making an online store. Her code needs to calculate the final cost of a $32 item with a $5 coupon applied. The initial code looks like this: itemCost ← 32 couponAmount ← 5 Which code successfully calculates and stores the final cost? 👁️Note that there may be multiple answers to this question.
finalCost ← itemCost + (-1 * couponAmount) finalCost ← (itemCost - couponAmount) finalCost ← itemCost - couponAmount
Mira is writing a program to help her decide what cheese to pair with what fruit. IF (fruit = "watermelon") { cheese ← "feta" } ELSE { IF (fruit = "peach") { cheese ← "burrata" } ELSE { IF (fruit = "pear") { cheese ← "brie" } ELSE { IF (fruit = "strawberry") { cheese ← "ricotta" } ELSE { cheese ← "goat" } } } } Which of these tables shows expected values for cheese after running this program with a variety of values for fruit?
fruitcheese "mango""goat" "watermelon""feta" "peach""burrata" "fig""goat" "pear""brie" "raspberry""goat" "strawberry""ricotta"
Melody is organizing a bake sale and making a program to help her plan the ingredients. Each batch of cookies requires 3 eggs, and she's going to make 9 batches. This code calculates the total eggs required: eggsInBatch ← 3 numBatches ←9 neededEggs ← eggsInBatch * numBatches Melody realizes she'll need to buy more eggs than necessary, since she needs to buy eggs by the dozen. Now she wants to calculate how many eggs will be leftover in the final carton of eggs. That will help her decide whether to make extra icing. Which line of code successfully calculates and stores the number of leftover eggs in the final carton?
leftoverEggs ← 12 - (neededEggs MOD 12)
The two procedures below are both intended to return the total number of excess calories eaten in a day based on a list of calories in each meal. Procedure 1: PROCEDURE calcExcess1(meals) { totalCalories ← 0 FOR EACH meal IN meals { totalCalories ← totalCalories + meal } excessCalories ← totalCalories - 2000 RETURN excessCalories } Procedure 2: PROCEDURE calcExcess2(meals) { totalCalories ← 0 FOR EACH meal IN meals { totalCalories ← totalCalories + meal excessCalories ← totalCalories - 2000 } RETURN excessCalories } Consider these procedure calls: excess1 ← calcExcess1([700, 800, 600, 300]) excess2 ← calcExcess2([700, 800, 600, 300]) Which of these statements best describes the difference between the procedure calls?
Both procedure calls return the same value, but the second procedure requires more computations.
The following procedure calculates the slope of a line and takes 4 numeric parameters: the x coordinate of the first point, the y coordinate of the first point, the x coordinate of the second point, and the y coordinate of the second point. PROCEDURE lineSlope (x1, y1, x2, y2) { result ← (y2 - y1) / (x2 - x1) DISPLAY (result) } This graph contains a line with unknown slope, going through the points [1, 1][1,1]open bracket, 1, comma, 1, close bracket and [3, 4][3,4]open bracket, 3, comma, 4, close bracket: \small{1}1\small{2}2\small{3}3\small{4}4\small{1}1\small{2}2\small{3}3\small{4}4yyxx Graph with line going through 2 marked points [1, 1] and [3, 4] Which of these lines of code correctly calls the procedure to calculate the slope of this line?
lineSlope(1, 1, 3, 4)
The following procedure calculates the slope of a line and takes 4 numeric parameters: the x coordinate of the first point, the y coordinate of the first point, the x coordinate of the second point, and the y coordinate of the second point. PROCEDURE lineSlope (x1, y1, x2, y2) { result ← (y2 - y1) / (x2 - x1) DISPLAY (result) } 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: \small{1}1\small{2}2\small{3}3\small{4}4\small{1}1\small{2}2\small{3}3\small{4}4yyxx Graph with line going through 2 marked points [2, 1] and [4, 3]. Which of these lines of code correctly calls the procedure to calculate the slope of this line?
lineSlope(2, 1, 4, 3)
Nanami is researching how much software engineers make. She's writing a program to convert yearly salaries into hourly rates, based on 52 weeks in a year and 40 hours in a week. The program starts with this code: salary ← 105000 wksInYear ← 52 hrsInWeek ← 40 Which lines of code successfully calculate and store the hourly rate? 👁️Note that there may be multiple answers to this question.
ourlyRate ← salary / wksInYear / hrsInWeek hourlyRate ← (salary / wksInYear) / hrsInWeek
Yelp provides a restaurant search feature on their website: The code to display the search filter and results relies on many variables. Which of these variables are storing a string data type? 👁️Note that there may be multiple answers to this question.
searchQuery ← "sushi" category ← "japanese" sortBy ← "closest" searchNear ← "94701" state ← "CA"
A game programmer decides to use the Pythagorean distance formula for collision detection: d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}d=(x2−x1)2+(y2−y1)2d, equals, square root of, left parenthesis, x, start subscript, 2, end subscript, minus, x, start subscript, 1, end subscript, right parenthesis, squared, plus, left parenthesis, y, start subscript, 2, end subscript, minus, y, start subscript, 1, end subscript, right parenthesis, squared, end square root The programming environment provides these built-in procedures: NameDescriptionsqrt(n)Returns the square root of nnn.square(n)Returns the value of n^2n2n, squared. In the programmer's code, the coordinates are represented by the variables x1, y1, x2, y2. Which of these code snippets properly implements the distance formula?
sqrt( square(x2 - x1) + square(y2 - y1) )
Harper is writing code to calculate the surface area of a sphere, based on this formula: \text{Surface area} = 4 \pi r^2Surface area=4πr2start text, S, u, r, f, a, c, e, space, a, r, e, a, end text, equals, 4, pi, r, squared This is their code so far: surfaceArea ← 4 * 3.14159 * (radius * radius) They then discover that the coding environment has a built-in constant for PI plus a number of useful mathematical procedures: NameDescriptionadd(n, m)Returns the addition of n to m.sqrt(n)Returns the square root of nnn.square(n)Returns the value of n^2n2n, squared.cube(n)Returns the value of n^3n3n, cubed.pow(n, m)Returns the value of n^mnmn, start superscript, m, end superscript. How could the code be rewritten using the constant and procedures? 👁️Note that there are 2 answers to this question.
surfaceArea ← 4 * PI * pow(radius, 2) surfaceArea ← 4 * PI * square(radius)
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. Which of these is the best refactor of the code?
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)
Jing-sheng is working with a game level designer on a new video game. The designer sends them this flow chart: Flow chart that starts with diamond and branches into two rectangles. * Diamond contains question, "Is enemy strength at least 10?" * Arrow marked "true" leads to rectangle with text "Subtract 6 from player health" * Arrow marked "false" leads to rectangle with text "Subtract 2 from player health" [How do you read a flowchart?] He must implement that logic in code, using the variables enemyStrength and playerHealth. Which of these code snippets correctly implements the logic in that flow chart?
IF (enemyStrength ≥ 10) { playerHealth ← playerHealth - 6 } ELSE { playerHealth ← playerHealth - 2 }
MouseyBot is a programmable robot that can be programmed using the following procedures: NameDescriptionwalkForward(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).canCharge()Returns true if robot is on a space with a charging station. MouseyBot is currently positioned inside a grid environment, facing right in the fourth row, first column. His charging station is located in the first row, fourth column. MouseyBot would like to reach the charging station. Here's the start of a program that uses a loop to program his journey: REPEAT UNTIL ( canCharge() ) { <MISSING CODE> } There are many ways for him to reach the station. Of the options below, which will require the most repetitions of the loop?
IF (facingWall()) { turnLeft() } ELSE { walkForward(1) }
Donal is writing a program that suggests usernames for Instagram, the photo sharing app. The program relies on multiple string operations: PseudocodeDescriptionLOWER(string)Returns the string in lowercase.REPLACE(string, old, new)Returns string with all occurrences of old replaced with new. In their program, the variable userInput stores the string "Chicken Biggle 007". Which of the following expressions results in the string "chicken_biggle_007"? 👁️Note that there are 2 answers to this question.
LOWER( REPLACE(userInput, " ", "_")) REPLACE( LOWER(userInput), " ", "_")
Yong is making a program to help him figure out how much money he spends eating. This procedure calculates a yearly cost based on how much an item costs, and how many times a week he consumes it: PROCEDURE calcYearlyCost(numPerWeek, itemCost) { numPerYear ← numPerWeek * 52 yearlyCost ← numPerYear * itemCost RETURN yearlyCost } Yong wants to use that procedure to calculate the total cost of his breakfast beverages: hot tea, which he drinks 5 days a week and costs $2.00 boba, which he drinks 2 days a week and costs $6.00 Which of these code snippets successfully calculates and stores their total cost? 👁️Note that there are 2 answers to this question.
totalCost ← calcYearlyCost(2, 6.00) + calcYearlyCost(5, 2.00) teaCost ← calcYearlyCost(5, 2.00) bobaCost ← calcYearlyCost(2, 6.00) totalCost ← teaCost + bobaCost
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: 8\text{ m}8 m4\text{ m}4 m2\text{ m}2 m Trapezoid diagram with upper base width of 4 meters, lower base width of 8 meters, and height of 2 meters. Which of these lines of code correctly calls the procedure to calculate the area of this trapezoid? 👁️Note that there may be multiple answers to this question.
trapezoidArea (8, 4, 2) trapezoidArea (4, 8, 2)
According to the US constitution, a presidential candidate must be at least 35 years old and have been a US resident for at least 14 years. The variable age represents a candidate's age and the variable residency represents their years of residency. Which of the following expressions evaluates to true if a candidate meets the criteria?
NOT(age < 35) AND NOT (residency < 14)
One way to calculate wildfire risk is to consider the temperature, humidity, and wind. Wildfire risk is elevated if the humidity is below 15%, wind speed is faster than 15 miles per hour, and temperature is greater than 50°F. The variable humidity represents the humidity percentage, the variable wind represents the wind speed (mph), and the variable temp represents the temperature in degrees Fahrenheit. Which of the following expressions evaluates to true if there is an elevated wildfire risk?
NOT(humidity ≥ 15) AND wind > 15 AND temp > 50
Fabian is looking through a classmate's code and sees this procedure called fancyMath: PROCEDURE fancyMath(expression) { divideFixed ← REPLACE(expression, "/", "÷") multFixed ← REPLACE(divideFixed, "*", "×") RETURN multFixed } That procedure relies on the built-in procedure REPLACE(string, old, new), which returns string with all instances of old replaced by new. Fabian then decides to try out the procedure on a math expression: fancyMath("(5 / 3) * 6") After that line of code runs, what will be displayed on the screen?
Nothing will be displayed
Joo-won is writing code to calculate the volume of a cone based on this formula: \text{Volume} = \pi r^2 \dfrac{h}3Volume=πr23hstart text, V, o, l, u, m, e, end text, equals, pi, r, squared, start fraction, h, divided by, 3, end fraction He's testing his code on this cone: 2255 The code starts with these variables, where radius represents rrr and height represents hhh: radius ← 2 height ← 5 The built-in constant PI stores an approximation of \piπpi. Which expression correctly calculates the volume?
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 TimeTotal Distancestart text, A, v, e, r, a, g, e, space, s, p, e, e, d, end text, equals, start fraction, start text, T, o, t, a, l, space, D, i, s, t, a, n, c, e, end text, divided by, start text, T, o, t, a, l, space, T, i, m, e, end text, end fraction Which of these is the best procedure for calculating and displaying average speed?
PROCEDURE calcAvgSpeed (distance, time) { DISPLAY (distance/time) }
Mia and her friends decide to do a push-up challenge, to do a certain number of push-ups over a certain number of days. Mia is writing a program to help choose the number of push-ups and days. numPushUps ← 1000 numDays ← 20 pushUpsPerDay ← numPushUps / numDays DISPLAY(CONCAT(numPushUps, CONCAT(" over ", numDays))) DISPLAY(CONCAT(" = ", pushUpsPerDay)) numPushUps ← 10000 numDays ← 60 pushUpsPerDay ← numPushUps / numDays DISPLAY(CONCAT(numPushUps, CONCAT(" over ", numDays))) DISPLAY(CONCAT(" = ", pushUpsPerDay)) numPushUps ← 5000 numDays ← 30 pushUpsPerDay ← numPushUps / numDays DISPLAY(CONCAT(numPushUps, CONCAT(" over ", numDays))) DISPLAY(CONCAT(" = ", pushUpsPerDay)) Mia realizes her program has a lot of duplicate code, and decides to make a procedure to reduce the duplicated code. Which of these procedures best generalizes her code for easy reuse?
PROCEDURE calcDailyPushUps(numPushUps, numDays) { pushUpsPerDay ← numPushUps / numDays DISPLAY(CONCAT(numPushUps, CONCAT(" over ", numDays))) DISPLAY(CONCAT(" = ", pushUpsPerDay)) }
Maria is baking cookies for a bake sale and writing a program to help her decide what price to sell them at. Her program computes possible profits based on estimates for how many she'll sell at different price points. 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)) Maria realizes her program has a lot of duplicate code, and decides to make a procedure to reduce the duplicated code. Which of these procedures best generalizes her code for easy reuse?
PROCEDURE calcProfit(numSold, pricePer) { moneyMade ← numSold * pricePer DISPLAY(CONCAT(numSold, CONCAT(" x ", pricePer))) DISPLAY(CONCAT(" = ", moneyMade)) }
Which of the following is a benefit of procedures in programming?
Programmers can write more organized programs by using procedures for repetitive code.
Ling is writing code for a browser extension that transforms online comments to sound less emotional. The code relies on multiple string operations: PseudocodeDescriptionLOWER(string)Returns the string in lowercase.REMOVE(string, target)Removes all occurrences of target from string and returns the new string. Their code includes these variables: 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"? 👁️Note that there are 2 answers to this question.
REMOVE( LOWER(commentB), "!") LOWER( REMOVE(commentB, "!"))
KittyBot is a programmable robot that obeys the following commands: NameDescriptionwalkForward()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. 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() }
The code below is from a sign-up form. It accepts two string inputs from a user and then processes them with a conditional statement. email1 ← INPUT() email2 ← INPUT() IF (UPPER(email1) = UPPER(email2)) { DISPLAY("Looks good!") } ELSE { DISPLAY("Try again!") } The code relies on two built-in procedures: ProcedureDescriptionINPUT()Prompts the user for a value and returns it.UPPER(string)Converts the given string to uppercase and returns it. Which of the following best describes the result of running this code?
The code displays "Looks good!" if the two emails are equal once they're uppercased, and displays "Try again!" otherwise.
Charlotte is writing code to turn sentences into Pig Latin. This is what she has so far: 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) The code relies on two string procedures: NameDescriptionCONCATENATE (string1, string2, ...)Returns a single string that combines the provided strings together in order.SUBSTRING (string, startPos, numChars)Returns a substring of string starting at startPos of length numChars. The first character in the string is at position 1. A friend points out that she can reduce the complexity of her code by using the abstractions of lists and loops. Charlotte 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?
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)
A programmer for an online store is developing a program to calculate discount pricing for bulk orders. The program needs to implement this pricing table: Minimum quantityDiscount105%757%15010% The code segment below uses nested conditionals to assign the discount variable to the appropriate value, but its conditions are missing operators. 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?
≥
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? 👁️Note that there may be multiple answers to this question.
APPEND(quarterCosts, cost)
Eliott is working with a game designer on a video game. The designer sends them this flow chart: Flow chart that starts with diamond and branches into two rectangles. * Diamond contains question, "Are experience points greater than 100?" * Arrow marked "true" leads to rectangle with text "Add 10 to the level". * Arrow marked "false" leads to rectangle with text "Add 1 to the level". [How do you read a flowchart?] He must implement that logic in code, using the variables experiencePoints and level. Which of these code snippets correctly implements the logic in that flow chart?
IF (experiencePoints > 1000) { level ← level + 10 } ELSE { level ← level + 1 }
Lucie is developing a program to assign pass/fail grades to students in her class, based on their percentage grades. Their college follows this grading system: PercentageGrade70% and abovePASSLower than 70%FAIL The variable percentGrade represents a student's percentage grade, and her program needs to set grade to the appropriate value. Which of these code segments correctly sets the value of grade? 👁️Note that there are 2 answers to this question.
IF (percentGrade ≥ 70) { grade ← "PASS" } ELSE { grade ← "FAIL" } IF (percentGrade < 70) { grade ← "FAIL" } ELSE { grade ← "PASS" }
KittyBot is a programmable robot that obeys the following commands: NameDescriptionwalkForward()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. We want to program KittyBot to reach the ball of yarn, located in the fifth row and fifth column. Which of these code segments accomplishes that goal?
REPEAT 3 TIMES { walkForward() turnRight() walkForward() turnLeft() }
The code below processes two numerical values with a conditional statement. numA ← INPUT() numB ← INPUT() IF (numA > numB) { DISPLAY(numA) } ELSE { DISPLAY(numB) } The code relies on a built-in procedure, INPUT(), which prompts the user for a value and returns it. Which of the following best describes the result of running this code?
The code displays whichever number is greater, numA or numB, or displays numB if they are equal.
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?
phLevelsolutionType-0.4"acidic" 4.7"acidic" 6.9"acidic" 7"neutral" 7.4"basic" 14.2"basic"
Alissa is programming an app called ShirtItUp, where users can customize a t-shirt with their own phrase on it. Which variable would she most likely use a string data type for?
phrase: The custom phrase entered by the user
Malcolm is writing code to calculate the volume of a sphere, based on this formula: \text{Volume} = \dfrac43 \pi r^3Volume=34πr3start text, V, o, l, u, m, e, end text, equals, start fraction, 4, divided by, 3, end fraction, pi, r, cubed This is his code so far: volume ← (4/3) * 3.14159 * (radius * radius * radius) He then discovers that the coding environment has a built-in constant for PI plus a number of useful mathematical procedures: NameDescriptionadd(n, m)Returns the addition of n to m.sqrt(n)Returns the square root of nnn.square(n)Returns the value of n^2n2n, squared.cube(n)Returns the value of n^3n3n, cubed.pow(n, m)Returns the value of n^mnmn, start superscript, m, end superscript. How could the code be rewritten using the constant and procedures? 👁️Note that there are 2 answers to this question.
volume ← (4/3) * PI * cube(radius) volume ← (4/3) * PI * pow(radius, 3)
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
This program uses a conditional to help a gardener plan their potato harvesting. IF (month = "July" OR tuberSize > 2) { activity ← "harvest" } ELSE { activity ← "wait" } In which situations will activity be "harvest"? 👁️Note that there may be multiple answers to this question.
When month is "July" and tuberSize is 1.5 When month is "July" and tuberSize is 2.5 When month is "August" and tuberSize is 2.1
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: NameDescriptioncookFor(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? Part 2: What is the maximum times the computer will execute the code inside the REPEAT loop?
When numKernels is equal to 0 When elapsedSeconds is greater than 700 The computer wouldn't execute the code more than 4 times.
Casper is programming a game called GhostHunter Extreme, where players must capture as many ghosts as possible in 5 minutes. Which variable would he most likely use a string data type for?
playerName: The player's name
MouseyBot is a programmable robot that can be programmed using the following procedures: NameDescriptionwalkForward(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 left in the fifth row, fourth column. A wedge of DigiCheese is located in the second row, first column. 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()
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"
A software engineer uses this nested conditional for the online mapping software they're building. IF (lat > 38 AND lng < -134) { direction ← "NW" } ELSE { IF (lat > 38 AND lng > -134) { direction ← "NE" } ELSE { IF (lat < 38 AND lng < -134) { direction ← "SW" } ELSE { IF (lat < 38 AND lng > -134) { direction ← "SE" } } } } When lat is 37.5 and lng is -131.2, what will be the value of direction?
"SE"
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) What will be the output of that code?
1 0 3 3
Oakley is making a program to display events for the next few days. Here's a snippet of the code: today ← 11 tomorrow ← 12 DISPLAY (tomorrow) DISPLAY (today) After running that code, what will be displayed?
12 11
Elvira is experimenting with assigning and displaying variables. Here's a snippet of her code: a ← 12 DISPLAY (a) b ← 32 DISPLAY (b) a ← b b ← 52 DISPLAY (a) DISPLAY (b) What will be the output of that code?
12 32 32 52
A game programmer uses this nested conditional in their online Four Square game. 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
Consider the following code segment: a ← 3 b ← 8 c ← 5 result ← min( max(a, b), c) The code relies on these built-in procedures: NameDescriptionmin(a, b)Returns the smaller of the two arguments.max(a, b)Returns the greater of the two arguments. After the code runs, what value is stored in result?
5
Dahlia is creating a program to display Morse code. This is what her program contains so far: PROCEDURE sendA () { DISPLAY ("• −") } PROCEDURE sendB () { DISPLAY ("− • • •") } PROCEDURE sendC () { DISPLAY ("− • − •") } PROCEDURE sendD () { DISPLAY ("− • •") } PROCEDURE sendE () { DISPLAY ("•") } PROCEDURE sendF () { DISPLAY ("• • − •") } sendF () sendA () sendD () sendE () sendD () When this program executes, how many total calls does it make to the DISPLAY procedure?
5
Helena is creating a program to spell out words using the NATO phonetic alphabet. That's the alphabet used by pilots and radio operators to clearly pronounce words one letter at a time. This is what her program contains so far: 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 () When this program executes, how many total calls does it make to the DISPLAY procedure?
6
Marius is writing a program that calculates physics formulas. His procedure calcGravForce should return the gravitational force between two objects at a certain radius from each other, based on this formula: F = G\dfrac{m_1m_2}{r^2}F=Gr2m1m2F, equals, G, start fraction, m, start subscript, 1, end subscript, m, start subscript, 2, end subscript, divided by, r, squared, end fraction \,\,1PROCEDURE calcGravForce (mass1, mass2, radius)2{3\,\,\,\,G ← 6.674 * POWER(10, −11)4\,\,\,\,masses ← mass1 * mass25\,\,\,\,force ← G * ( masses / POWER(radius, 2) )6} The 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 5 RETURN force
This program simulates two players rolling dice to determine the start player for a game. Once a player rolls a die higher in value than the other player, that player starts the game. 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? 👁️Note that there are 2 answers to this question.
Between line 8 and 9 Between line 12 and 13
This program simulates a game where two players try to make basketball shots . Once either player misses 5 shots, the game is over. 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: } Unfortunately, this code is incorrect; the REPEAT UNTIL loop never stops repeating. Where would you add code so that the game ends when expected? 👁️Note that there are 2 answers to this question.
Between line 9 and 10 Between line 13 and 14
Barry is making a program to process user birthdays. The program uses the following procedure for string slicing: NameDescriptionSUBSTRING (string, startPos, numChars)Returns a substring of string starting at startPos of length numChars. The first character in the string is at position 1. His program starts with this line of code: userBday ← "03/31/1984" Which of these lines of code displays the month ("03")?
DISPLAY (SUBSTRING (userBday, 1, 2))
Lilia is looking through her friend's code and sees a procedure called pacifyName: PROCEDURE pacifyName(fullName) { heartified ← REPLACE(fullName, " ", "♥") florified ← REPLACE(heartified, "o", "❀") RETURN LOWER(florified) } That procedure manipulates strings using two built-in procedures: ProcedureDescriptionREPLACE(string, old, new)Returns string with all instances of old replaced by new.LOWER(string)Returns lowercase version of string. Lilia then decides to try out the procedure on her own name: pacifyName("Lilia Potter") After that line of code runs, what will be displayed on the screen?
Nothing will be displayed
Wynter is working on an app for learning fractions. His program uses the following procedure for string concatenation: PseudocodeDescriptionconcatenate(string1, string2)Concatenates (joins) two strings to each other, returning the combined string. These variables are at the start of the program: denom ← "third" num1 ← "one" num2 ← "two" Which line of code would store the string "one-third"?
frac ← concatenate(concatenate(num1, "-"), denom)
The following procedure calculates the slope of a line and takes 4 numeric parameters: the x coordinate of the first point, the y coordinate of the first point, the x coordinate of the second point, and the y coordinate of the second point. PROCEDURE lineSlope (x1, y1, x2, y2) { result ← (y2 - y1) / (x2 - x1) DISPLAY (result) } This graph contains a line with unknown slope, going through the points [1, 3][1,3]open bracket, 1, comma, 3, close bracket and [5, 2][5,2]open bracket, 5, comma, 2, close bracket: \small{1}1\small{2}2\small{3}3\small{4}4\small{5}5\small{1}1\small{2}2\small{3}3\small{4}4yyxx Graph with line going through 2 marked points [1, 3] and [5, 2]. Which of these lines of code correctly calls the procedure to calculate the slope of this line?
lineSlope(1, 3, 5, 2)
Majken is turning 18 years old soon and wants to calculate how many seconds she will have been alive. Her code looks like this: numYears ← 18 secondsInDay ← 60 * 60 * 24 Which code successfully calculates and stores the total number of seconds? 👁️Note that there may be multiple answers to this question.
totalSeconds ← secondsInDay * 365 * numYears totalSeconds ← (numYears * 365) * secondsInDay totalSeconds ← numYears * 365 * secondsInDay