khan academy programming unit test

studied byStudied by 4912 people
5.0(2)
Get a hint
Hint

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?

1 / 179

encourage image

There's no tags or description

Looks like no one added any tags here yet for you.

180 Terms

1

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)

New cards
2

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

New cards
3

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

New cards
4

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" }

New cards
5

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

New cards
6

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"

New cards
7

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

New cards
8

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)

New cards
9

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"

New cards
10

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))

New cards
11

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

New cards
12

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

New cards
13

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

New cards
14

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

New cards
15

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

New cards
16

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"

New cards
17

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.

New cards
18

What is a benefit to using pseudocode?

Pseudocode can represent coding concepts common to all programming languages.

New cards
19

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)

New cards
20

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).

New cards
21

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"

New cards
22

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.

New cards
23

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

New cards
24

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"

New cards
25

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=CurrentVoltage​start 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) }

New cards
26

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

New cards
27

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

New cards
28

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

New cards
29

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

New cards
30

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?

>

New cards
31

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

New cards
32

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))

New cards
33

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.

New cards
34

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.

New cards
35

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

New cards
36

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

New cards
37

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)) }

New cards
38

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 }

New cards
39

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"

New cards
40

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.

New cards
41

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), "!!!")

New cards
42

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

New cards
43

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"

New cards
44

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)

New cards
45

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)

New cards
46

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

New cards
47

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.

New cards
48

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

New cards
49

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)

New cards
50

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

New cards
51

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.

New cards
52

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()

New cards
53

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​)2​d, 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

New cards
54

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() }

New cards
55

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

New cards
56

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

New cards
57

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"

New cards
58

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)

New cards
59

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

New cards
60

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

New cards
61

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"

New cards
62

Consider the following code snippet:

DISPLAY (">") DISPLAY ("_") DISPLAY ("<")

After the code runs, what is displayed?

> _ < (has space between the characters)

New cards
63

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)

New cards
64

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"

New cards
65

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

New cards
66

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"

New cards
67

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.

New cards
68

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)

New cards
69

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

New cards
70

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 }

New cards
71

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)

New cards
72

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

New cards
73

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)

New cards
74

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"

New cards
75

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

New cards
76

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)

New cards
77

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

New cards
78

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)

New cards
79

Consider the following code snippet:

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

After the code runs, what is displayed?

: - O (has space)

New cards
80

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.

New cards
81

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"

New cards
82

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?

New cards
83

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

New cards
84

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

New cards
85

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"

New cards
86

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))

New cards
87

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

New cards
88

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)

New cards
89

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=MassForce​start 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) }

New cards
90

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)

New cards
91

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

New cards
92

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.

New cards
93

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

New cards
94

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

New cards
95

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)

New cards
96

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)) }

New cards
97

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.

New cards
98

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.

New cards
99

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, "!"))

New cards
100

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 }

New cards

Explore top notes

note Note
studied byStudied by 20 people
... ago
5.0(1)
note Note
studied byStudied by 304 people
... ago
5.0(2)
note Note
studied byStudied by 13 people
... ago
5.0(1)
note Note
studied byStudied by 11 people
... ago
5.0(1)
note Note
studied byStudied by 40 people
... ago
5.0(1)
note Note
studied byStudied by 10 people
... ago
5.0(1)
note Note
studied byStudied by 267 people
... ago
5.0(6)

Explore top flashcards

flashcards Flashcard (160)
studied byStudied by 85 people
... ago
5.0(2)
flashcards Flashcard (96)
studied byStudied by 28 people
... ago
5.0(1)
flashcards Flashcard (30)
studied byStudied by 2 people
... ago
5.0(1)
flashcards Flashcard (38)
studied byStudied by 12 people
... ago
5.0(1)
flashcards Flashcard (104)
studied byStudied by 10 people
... ago
5.0(1)
flashcards Flashcard (53)
studied byStudied by 2 people
... ago
5.0(1)
flashcards Flashcard (23)
studied byStudied by 46 people
... ago
5.0(2)
robot