AP Principles, Programming

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

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"

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

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

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"

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"

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"

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?

"mango"-"goat" "watermelon"-"feta" "peach"-"burrata" "fig"-"goat" "pear"-"brie" "raspberry"-"goat" "strawberry"-"ricotta"

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=VnRT​start 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?

(ALL OF THEM) Own or have access to a working device that is compatible with D2L Read the syllabus to understand course policies and schedule Obtain necessary course software and technology Check D2L and your courses frequently to keep up-to-date with course happenings Budget time to work on your course(s) Check D2L Email Check myLoneStar email

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

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?

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

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? Choose 1 answer:Choose 1 answer:

1 0 3 3

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

1. 6 2. 3 3. If she has to update multiple places in the code, the program will run much slower.

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=VnRT​start 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?

1. After line 5 2. Return Pressure

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.

1. IF (percentGrade ≥ 70) { grade ← "PASS" } ELSE { grade ← "FAIL" } 2.IF (percentGrade < 70) { grade ← "FAIL" } ELSE { grade ← "PASS" }

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. Choose all answers that apply:Choose all answers that apply:

1. When sea food is mollusk and day frozen is 1 2.When sea food is mollusk and day froze is 9 3. When see food salmon and day frozen is 7

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?

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

The following variable assignments are from a family tree program. Identify which variables store numbers and which store strings: Variable assignmentData type?numSiblings ← 3data typefatherName ← "Godfrey"data typemotherName ← "Rosemarie"data typebirthYear ← 2003data typebirthMonth ← 6data type

1. number 2. string 3. string 4.number 5. number

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.

1. projectTitle ← "Jumpin' To Learn!" 2.queryNear ← "13078" 3.category ← "Special Needs" 4.query ← "sensory"

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. Choose 2 answers:Choose 2 answers:

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

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.

1.teaCost ← calcYearlyCost(5, 2.00) bobaCost ← calcYearlyCost(2, 6.00) totalCost ← teaCost + bobaCost 2.totalCost ← calcYearlyCost(2, 6.00) + calcYearlyCost(5, 2.00)

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?

1.totalFootprint ← calcFlightFootprint(2451, 118) + calcFlightFootprint(3442, 252) 2.laNyCarbon ← calcFlightFootprint(2451, 118) nyLondonCarbon ← calcFlightFootprint(3442, 252) totalFootprint ← laNyCarbon + nyLondonCarbon

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

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

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

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

This short program displays the winning result in a ship naming contest: DISPLAY ("Boaty") DISPLAY ("McBoatFace")

2 Boaty McBoatFace

Viktoria is writing a program to communicate with pirates: DISPLAY ("Ahoy") DISPLAY ("mateys!") The following paragraph describes how the program works.

2 procedure parameter

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

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

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

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

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?

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

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

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

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? Choose 1 answer:Choose 1 answer:

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

Evelyn is making a race car simulation program. She accidentally gave two of her variables the same name: t ← 0 t ← 60 What will be the value of t after this code runs?

60

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

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

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

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

Consider the following code snippet: DISPLAY (">") DISPLAY ("_") DISPLAY ("<") After the code runs, what is displayed?

> _ < (with space in between)

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)

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.

APPEND(bigWords, word)

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)

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.

After line 6 RETURN distance

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 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 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 day of the month ("31")?

DISPLAY (SUBSTRING (userBday, 4, 2))

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 }

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? Choose 1 answer:Choose 1 answer:

NOT(age < 35) AND NOT (residency < 14)

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? Choose 1 answer:Choose 1 answer:

Nothing will be displayed

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.

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=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? Choose 1 answer:Choose 1 answer:

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

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 Distance​start 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.

PROCEDURE calcDailyPushUps(numPushUps, numDays) { pushUpsPerDay ← numPushUps / numDays DISPLAY(CONCAT(numPushUps, CONCAT(" over ", numDays))) DISPLAY(CONCAT(" = ", pushUpsPerDay)) }

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 1: When numKernels is equal to 0, When elapsedSeconds is greater than 700 Part 2: The computer wouldn't execute the code more than 4 times

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.

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.

Which of the following is a benefit of procedures in programming?

Programmers can write more organized programs by using procedures for repetitive code.

What is a benefit to using pseudocode?

Pseudocode can represent coding concepts common to all programming languages.

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?

Pyramid, with one dot start on first row, fourth column

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

What will happen if you type pseudocode in another language's programming environment and try to run the program? Choose 1 answer:Choose 1 answer:

The program will not run, because programming environments only understand the language they're built for.

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

the code segment below uses a loop to repeatedly operate on a sequence of numbers. result ← 0 i ← 8 REPEAT 7 TIMES { result ← result + i i ← i - 1 } Which description best describes what this program does? Choose 1 answer:Choose 1 answer:

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

A program races four avatars against each other: Mr. Pink, Purple Pi, Hopper, and Spunky Sam. Here they are lined up at the start line: Each of the avatars is controlled by a different program. Mr. Pink: moveAmount ← 1 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount + 1 } Purple Pi: moveAmount ← 1 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount * 2 } Hopper: moveAmount ← 4 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount / 2 } Spunky Sam: moveAmount ← 4 REPEAT UNTIL ( reachedFinish() ) { moveForward(moveAmount) moveAmount ← moveAmount - 2 } After the first 3 repetitions of each loop, which avatar will be ahead?

Two avatars will be tied for the lead.

This program 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"

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 "August" and tuberSize is 2.1 When month is "July" and tuberSize is 2.5 When month is "July" and tuberSize is 1.5

Nikolas is writing a program to calculate the area of a triangle, based on this formula: A = \dfrac{bh}{2}A=2bh​A, 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

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? Choose 1 answer:Choose 1 answer:

carbonMonoxidestate52.6"normal"69.9"normal"70.0"elevated"71.4"elevated"122"elevated"

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)

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)

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

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. Choose all answers that apply:Choose all answers that apply:

hourlyRate ← salary / wksInYear / hrsInWeek hourlyRate ← (salary / wksInYear) / hrsInWeek

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

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

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

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.

searchQuery ← "90210" weather ← "Partly Cloudy" state ← "CA" city ← "Beverly Hills"

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. Choose 2 answers:Choose 2 answers:

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)

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 (4, 8, 2) trapezoidArea (8, 4, 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).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()

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

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?

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?


Ensembles d'études connexes

BIO Test 2, BIO 1406 Test 3, BIO 1406 TEST 4

View Set

PS 101: Introduction to Patient Safety

View Set

Science 6 Assignment 6 Periodic Table

View Set

HR Management DSST Sample Test 1

View Set

Chemistry 6.1 "Organizing the Elements"

View Set

aguda, grave, esdrujula, sobre esdrujula

View Set