Khan Academy Programming Study List
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
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
A game developer is working on a soccer video game. This incomplete code segment is run when a player attempts a goal from outside the 6 yard box: inGoal ← false IF (<MISSING CONDITION>) { inGoal ← true DISPLAY("Goal!") } ELSE { DISPLAY("Miss!") } At that distance, the code should give the player a 30% chance of making the goal. Which of these can replace <MISSING CONDITION> so that the code works as intended? 👁️Note that there are 2 answers to this question.
RANDOM(1, 100) <= 30 RANDOM(1, 10) <= 3
Nuru writes this code to calculate the final cost of an item with a discount applied: price ← 0.7 discount ← 0.2 final ← price - discount They're surprised to see that final stores the value 0.49999999999999994 instead of 0.5. What is the best explanation for that result?
The arithmetic operations on floating-point numbers resulted in a round-off error.
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: 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)
An indie game developer is making a grid-based game, and is programming logic to randomly spawn monsters on the grid. The following code spawns a monster: row ← RANDOM(1, 3) col ← RANDOM(3, 4) MONSTER(row, col) The procedure MONSTER draws the monster in a 5x5 grid, where the first parameter represents which horizontal row to draw it in, and the second parameter represents which vertical column to draw it in. The rows and columns are both numbered 1 through 5. Which of these represents the possible spawn squares for the monster?
1 2 3 4 5 6 1 . . 2 . . 3 . . 4 5
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
Which of the following is a benefit of procedures in programming?
Programmers can write more organized programs by using procedures for repetitive code.
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).
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
Aarush is writing a program to help him calculate how much exercise he does at the gym. The procedure calcSwimYards returns the number of yards swum for a given number of laps in a pool of a given length. PROCEDURE calcSwimYards(poolLength, numLaps) { lapLength ← poolLength * 2 RETURN lapLength * numLaps } Aarush then runs this line of code: yardsSwum ← calcSwimYards(25, 10) What value is stored in yardsSwum?
500
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
Eliott is working with a game designer on a video game. The designer sends them this flow chart: 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 }
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 ← true } ELSE { canRide ← false } IF (riderHeight < 48) { canRide ← false } ELSE { canRide ← true }
Laquan is writing a program to calculate the perimeter of a rectangle, based on this formula: P = 2l + 2wP=2l+2wP, equals, 2, l, plus, 2, w The program starts with this code: length ← 120 width ← 13 Which lines of code successfully calculate the perimeter? 👁️Note that there may be multiple answers to this question.
perimeter ← 2 * length + 2 * width perimeter ← (2 * length) + (2 * width)
The following expression is from the data loading logic of a website. NOT ( state = "loading" OR result = "error" ) Which of these expressions are logically equivalent?
state ≠ "loading" AND result ≠ "error"
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
Barry is making a program to process user birthdays. The program uses the following procedure for string slicing: Name Description 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. 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))
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
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
A visual artist is programming an 8x8 LED display: 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?
Right Triangle with corner in Top Left
Seth is writing a dialogue engine for an emergency preparedness game. The program relies on multiple string operations: Pseudocode Description CONCAT(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!"
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 sold Certification 500,000 gold 1,000,000 platinum 10,000,000 diamond 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?
≥
Consider the following code snippet: DISPLAY (":") DISPLAY ("-") DISPLAY ("O") After the code runs, what is displayed?
: - O
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
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((m1m2)/r^2) 1 PROCEDURE calcGravForce (mass1, mass2, radius) 2 { 3 \,\,\,\,space, space, space, spaceG ← 6.674 * POWER(10, −11) 4 \,\,\,\,space, space, space, spacemasses ← mass1 * mass2 5 \,\,\,\,space, space, space, spaceforce ← 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?
After line 5 RETURN force
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 may be multiple answers to this question.
teaCost ← calcYearlyCost(5, 2.00) bobaCost ← calcYearlyCost(2, 6.00) totalCost ← teaCost + bobaCost totalCost ← calcYearlyCost(2, 6.00) + calcYearlyCost(5, 2.00)
The following code segment uses lists to store and update the seven natural wonders of the world: sevenWonders ← ["Aurora", "Grand Canyon", "Great Barrier Reef", "Guanabara Bay", "Mount Everest", "Parícutin", "Victoria Falls"] sevenWonders[4] ← "Komodo" sevenWonders[6] ← "Table Mountain" After running that code, what does the sevenWonders list store?
"Aurora", "Grand Canyon", "Great Barrier Reef", "Komodo", "Mount Everest", "Table Mountain", "Victoria Falls"
The video sharing site YouTube originally stored the number of video views in a 32-bit signed integer. Then the viral hit "Gangnam Style" received more than 2,147,483,647 views (more than any other video at that time), and YouTube could not display an accurate number of views until they changed their code. What is the best explanation of what happened?
Integer overflow error
A programmer is creating a simulation of a city where natural disasters can randomly occur. This incomplete code segment simulates a Godzilla disaster: IF (<MISSING CONDITION>) { cityHealth ← cityHealth - 30 disasterMode ← "godzilla" } The code should only give Godzilla a 2% chance of storming the city. Which of these can replace <MISSING CONDITION> so that the code works as intended? 👁️Note that there may be multiple answers to this question.
RANDOM(1, 100) <= 2
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 "C" and motherAllele is "s" When fatherAllele is "s" and motherAllele is "C"
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
Joo-won is writing code to calculate the volume of a cone based on this formula: Volume=(Pi(r)^2)(h/3) He's testing his code on this cone: 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 Which expression correctly calculates the volume?
PI * (radius * radius) * (height / 3)
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)
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.
This program attempts to automate the process of giving fluids to a hospital patient to stabilize their blood pressure: ivFluid ← 0 meanPressure ← measureBP() REPEAT UNTIL (meanPressure > 65 OR ivFluid > 2000) { injectFluid(500) ivFluid ← ivFluid + 500 meanPressure ← measureBP() } The program relies on two methods built-in to the IV machine: Name Description injectFluid(amountML) Injects the given amount of fluid (in milliliters). measureBP() Returns a number representing the patient's mean arterial pressure. Part 1: When will the computer stop executing the code inside the REPEAT loop? 👁️Note that there may be multiple answers to this question.
When meanPressure is greater than 65 When ivFluid is greater than 2000 The computer wouldn't execute the code more than 5 times.
A gardener is writing a program to detect whether the soils for their citrus trees are the optimal level of acidity. IF (measuredPH > 6.5) { soilState ← "high" } ELSE { IF (measuredPH < 5.5) { soilState ← "low" } ELSE { soilState ← "optimal" } } Which of these tables shows the expected values of soilState for the given values of measuredPH?
measuredPH soilState 4.7 "low" 5.4 "low" 5.5 "optimal" 6.2 "optimal" 6.5 "optimal" 6.7 "high" 7.2 "high"
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
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?
today activity "Sunday" "none" "Monday" "swimming" "Tuesday" "jogging" "Wednesday" "none" "Thursday" "juggling" "Friday" "none" "Saturday" "gardening"
MouseyBot is a programmable robot that can be programmed using the following procedures: Name Description walkForward(numSpaces) Walks forward the given number of spaces in the grid. turnLeft() Rotates left 90 degrees (without moving forward). turnRight() Rotates right 90 degrees (without moving forward). facingWall() Returns true if robot is facing a wall (in the space in front). canTakeCheese() Returns true if robot is on a space with cheese. MouseyBot is currently positioned inside a grid environment, facing 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()
Allyson is making an online store. Her code needs to calculate the final cost of an $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 - couponAmount finalCost ← itemCost + (-1 * couponAmount) finalCost ← (itemCost - couponAmount)
Jack is creating a text-based card game. He starts off with this code that deals 3 cards: DISPLAY ("Ace of clubs\n") DISPLAY (" ___ \n") DISPLAY ("|A |\n") DISPLAY ("| O |\n") DISPLAY ("|OxO|\n") DISPLAY ("7 of diamonds\n") DISPLAY (" ___ \n") DISPLAY ("|7 |\n") DISPLAY ("| /\|\n") DISPLAY ("|_\/|\n") DISPLAY ("5 of clubs\n") DISPLAY (" ___ \n") DISPLAY ("|5 |\n") DISPLAY ("| O |\n") DISPLAY ("|OxO|\n") After writing that code, Jack decides to use a different way to draw the bottom line of the clubs cards: DISPLAY ("|O,O|\n") Part 1: How many lines will Jack need to update in his code? Now imagine that Jack 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 Jack 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 Jack having to update code in multiple places?
2 1 If he has to update multiple places in the code, the program will run slower.
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
A digital artist is writing a program to draw a landscape with a randomly generated mountain range. This code draws a single mountain: xPos ← RANDOM(4, 240) height ← RANDOM(70, 120) drawMountain(xPos, 80, height) The code relies on the drawMountain() procedure, which accepts three parameters for the mountain's x position, y position, and height. Here's what's drawn from one run of the program: Which of these describes mountains that might be drawn from this program? 👁️Note that there may be multiple answers to this question.
A mountain at an x position of 4 and a height of 120 A mountain at an x position of 180 and a height of 110
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? 👁️Note that there may be multiple answers to this question.
APPEND(bestAmounts, mgAmount)
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.
What is a benefit to using pseudocode?
Pseudocode can represent coding concepts common to all programming languages.
KittyBot is a programmable robot that obeys the following commands: Name Description walkForward() Walks forward one space in the grid. turnLeft() Rotates left 90 degrees (without moving forward). turnRight() Rotates right 90 degrees (without moving forward). KittyBot is currently positioned in the second row and third column of the grid, and is facing the bottom edge of the grid. 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() }
Elsie is looking through her classmate's program and sees a procedure called heightenEmotions: PROCEDURE heightenEmotions(myEmotion) { moreEnergy ← CONCAT(myEmotion, "!!!") moreVolume ← UPPER(moreEnergy) RETURN moreVolume } That procedure manipulates strings using two built-in procedures, CONCAT for concatenating two strings together, and UPPER for converting a string to uppercase. Elsie then sees this line of code: heightenEmotions("im mad") After that line of code runs, what will be displayed on the screen?
Nothing will be displayed
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: Average Speed = Total Distance/Total Time Which of these is the best procedure for calculating and displaying average speed?
PROCEDURE calcAvgSpeed (distance, time) { DISPLAY (distance/time) }
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(θ) The environment provides these built-in procedures: Name Description sin(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)
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"
A computer uses 5 bits to represent positive and negative integers, using 1 bit for the sign and 4 bits for the actual value. Which of the following operations would result in integer overflow? 👁️Note that there may be multiple answers to this question.
1 + 15 8 * 2
Damien is writing a program to teach Elvish languages: DISPLAY ("Mae govannen!") DISPLAY ("=") DISPLAY ("Well met!") The following paragraph describes how the program works. Fill in the blanks: This is a computer program with ___ statements. Each statement calls a ___ named DISPLAY. The string inside the parenthesis is a ___, which tells the computer what to display on the screen.
3 procedure parameter
This list represents the top runners in a marathon, using their bib numbers as identifiers: frontRunners ← [308, 147, 93, 125, 412, 219, 73, 34, 252, 78] This code snippet updates the list: tempRunner ← frontRunners[3] frontRunners[3] ← frontRunners[2] frontRunners[2] ← tempRunner What does the frontRunners variable store after that code runs?
308, 93, 147, 125, 412, 219, 73, 34, 252, 78
This 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
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.
A scientist is running a program to calculate the volume of a cone: radius ← 17.24 height ← 5.24 volume ← PI * (radius * radius) * (height / 3) The code relies on the built-in constant PI. After running the code, the variable volume stores 1630.9266447568566. Their supervisor checks their results by running the same calculation on their own computer. Their program results in a volume of 1630.9266447564448. The two values are very close, but not quite the same. Which of these is the most likely explanation for the difference?
The two computers represent the constant PI with a different level of precision, due to their rounding strategy or size limitations.
Neriah is writing code for a website that publishes attention-grabbing news articles. The code relies on multiple string operations: Pseudocode Description CONCATENATE(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 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?
ironLevel diagnosis 4.5 "anemic" 8.2 "anemic" 9.9 "anemic" 10.0 "normal" 22.5 "normal"
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] 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)
Darian 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
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
The following code snippet processes a list of strings with a loop and conditionals: words ← ["cab", "lab", "cable", "cables", "bales", "bale"] wordScore ← 0 FOR EACH word IN words { IF (LEN(word) ≥ 5) { wordScore ← wordScore + 3 } ELSE { IF (LEN(word) ≥ 4) { wordScore ← wordScore + 2 } ELSE { IF (LEN(word) ≥ 3) { wordScore ← wordScore + 1 } } } } DISPLAY(wordScore) The code relies on one string procedure, LEN(string), which returns the number of characters in the string. What value will this program display?
13
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: Name Description min(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
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)) }
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"
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.
category ← "japanese" searchQuery ← "sushi" searchNear ← "94701" state ← "CA" sortBy ← "closest"
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)
Malcolm is writing code to calculate the volume of a sphere, based on this formula: \text{Volume} = \dfrac43 \pi r^3Volume= 3 4 πr 3 V, o, l, u, m, e, equals, start fraction, 4, divided by, 3, end fraction, pi, r, start superscript, 3, end superscript 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: Name Description add(n, m) Returns the addition of n to m. sqrt(n) Returns the square root of nnn. square(n) Returns the value of n^2n 2 n, start superscript, 2, end superscript. cube(n) Returns the value of n^3n 3 n, start superscript, 3, end superscript. pow(n, m) Returns the value of n^mn m n, 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)