Chapter 4: Loops: Participation Activities

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

randGen already exists. Which generates a random number in the range 18..30?

Answer: (rand() % (30 = 18 + 1)) + 18 Explanation: rand() % 13 yields a range of 0 to 12. Adding 18 yields a range of 18..30.

Complete the for loop to achieve the goal. Use prefix increment (++i) or decrement (--i) where appropriate. Iterate for i from 0 to 9. for (i = 0; i <= 9; ) { // Loop body }

Answer: ++i Explanation: This increment will be performed at the end of the loop body. i++ or i = i + 1 are allowable, but prefix increment was requested and preferred.

Replace the loop variable update statement by using the decrement operator. i = 9; while (i > 0) { // Loop body i = i - 1; }

Answer: --i Explanation: --i is the same as i = i - 1. i-- is correct but we recommend --i.

randGen already exists. What is the smallest possible value returned by rand() % 10?

Answer: 0 Explanation: The range of rand() starts with 0, and 0 % 10 is 0.

How many times will the loop body execute? Assume user would enter 'n', then 'n', then 'y'. // Get userChar from user here while (userChar != 'n') { // Do something // Get userChar from user here }

Answer: 0 Explanation: Upon reaching the loop, the expression userChar != 'n' is false (because userChar IS equal to 'n'). So the loop body is never entered.

Refer to the GCD code provided in the figure below. Assume user input of numA = 15 and numB = 10. #include <iostream> using namespace std; // Output GCD of user-input numA and numB int main() { int numA = 0; // User input int numB = 0; // User input cout << "Enter first positive integer: "; cin >> numA; cout << "Enter second positive integer: "; cin >> numB; while (numA != numB) { // Euclid's algorithm if (numB > numA) { numB = numB - numA; } else { numA = numA - numB; } } cout << "GCD is: " << numA << endl; return 0; } What is the value of numB after the first iteration of the while loop?

Answer: 10 Explanation: Because (10 > 15) is false, the else branch executes (numA = numA - numB). numA is assigned 15 - 10 or 5, but numB remains unchanged.

What will the following code output? (For an infinite loop, type "IL") int x = 5; int y = 18; while (y >= x) { cout << y << " "; y = y - x; }

Answer: 18 3 8 Explanation: As long as y is greater than or equal to 5, y's value will be printed, then decremented by 5. Note that there is a space after each number, including after the last number.

Refer to the GCD code provided in the figure below. Assume user input of numA = 15 and numB = 10. #include <iostream> using namespace std; // Output GCD of user-input numA and numB int main() { int numA = 0; // User input int numB = 0; // User input cout << "Enter first positive integer: "; cin >> numA; cout << "Enter second positive integer: "; cin >> numB; while (numA != numB) { // Euclid's algorithm if (numB > numA) { numB = numB - numA; } else { numA = numA - numB; } } cout << "GCD is: " << numA << endl; return 0; } How many loop iterations will the algorithm execute?

Answer: 2 Explanation: After the first iteration, numA is 5 and numB is 10. After the second iteration, numA = 5 and numB = 5. The loop does not execute a third iteration because (numA != numB) is false.

Below is a program that has a "conversation" with the user, asking the user to type something and then (randomly) printing one of four possible responses until the user enters "Goodbye": #include <iostream> #include <string> using namespace std; /* Program that has a conversation with the user. Uses a switch statement and a random number (sort of) to mix up the program's responses. */ int main() { int randNum0_3 = 0; // Random number 0 to 3 string userText; // User input cout << "Tell me something about yourself. "; cout << "You can type \"Goodbye\" at anytime to quit." << endl << endl; cout << "> "; getline(cin, userText); while (userText != "Goodbye") { randNum0_3 = userText.length() % 4; // "Random" num. %4 ensures 0-3 switch (randNum0_3) { case 0: cout << endl << "Please explain further." << endl << endl; cout << "> "; break; case 1: cout << endl << "Why do you say: \"" << userText << "\"?" << endl << endl; cout << "> "; break; case 2: cout << endl << "I don't think that's right." << endl << endl; cout << "> "; break; case 3: cout << endl << "What else can you share?" << endl << endl; cout << "> "; break; default: cout << endl << "Uh-oh, something went wrong. Try again." << endl << endl; } getline(cin, userText); } cout << endl << "It was nice talking with you. Goodbye." << endl; return 0; } How many loop iterations will execute if the user plans to type "I'm hungry", "You are weird", "Goodbye", and "I like you".

Answer: 2 Explanation: After the second iteration, the user typed "Goodbye". The while loop condition will be false, and so the third iteration will not execute.

What ist he final value of i? i = 0; ++i; ++i;

Answer: 2 Explanation: First ++i increments 0 to 1. Second ++i increments 1 to 2.

How many times will the loop body execute? Assume user would enter 'a', then 'b', then 'n'. // Get userChar from user here while (userChar != 'n') { // Do something //Get userChar from user here }

Answer: 2 Explanation: First check: 'a' != 'n' is true. Second: 'b' != 'n' is true. Third: 'n' != 'n' is false (before they ARE equal), so loop body is not entered a third time.

Consider the following loop: int count = 0; int num = 6; do { num = num - 1; count = count + 1; } while (num > 4); What is the value of count after the loop?

Answer: 2 Explanation: The first iteration decrements num to 5 and increments count to 1. The second iteration decrements num to 4 and increments count to 2.

What is output by the following code? int row = 0; int col = 0; for(row = 2; row <= 3; row = row + 1) { for(col = 0; col <= 1; col = col + 1) { cout << row << col << " "; } }

Answer: 20 21 30 31 Explanation: The outer loop ranges from 2 to 3, and the inner loop ranges from 0 to 1. The first outer loop iteration outputs 20 and 21. The second outer loop iteration outputs 30 and 31.

Given the following code, how many times will the inner loop body execute? char letter1 = '?'; char letter2 = '?'; letter1 = 'a'; while (letter1 <= 'f') { letter2 = 'c'; while (letter2 <= 'f') { // Inner loop body ++letter2; } ++letter1; }

Answer: 24 Explanation: The outer loop iterates 6 times (letter1 is a, b, c, d, e, f). The inner loop iterates 4 times (letter2 is c, d, e, f) for each outer loop execution. 6 * 4 is 24.

How many times will the loop body execute: x = 3; while (x >= 1) { // Do something x = x - 1; }

Answer: 3 Explanation: First check, x is 3, so x >= 1 is true. Second check, x is 2, still true. Third check, x is 1, still true. Fourth check, x is 0, so x >= 1 is false.

A dice-rolling program has a statement that seeds a pseudo-random number generator with the constant value 99. The program is run and prints 4, 3, 6, 0. An hour later, the program is run again. What is the first number printed? Type a number or "Unknown" if the solution is unknown.

Answer: 4 Explanation: The seed is 99 for both program runs. So the second run will print 4, 3, 6, and 0. So will every run after that.

Refer to the GCD code provided in the figure below. Assume user input of numA = 15 and numB = 10. #include <iostream> using namespace std; // Output GCD of user-input numA and numB int main() { int numA = 0; // User input int numB = 0; // User input cout << "Enter first positive integer: "; cin >> numA; cout << "Enter second positive integer: "; cin >> numB; while (numA != numB) { // Euclid's algorithm if (numB > numA) { numB = numB - numA; } else { numA = numA - numB; } } cout << "GCD is: " << numA << endl; return 0; } What is numB after the second iteration of the while loop?

Answer: 5 Explanation: Because (10 > 5) is true, the if branch executes (numB = numB - numA), thus assigning numB with 10 - 5, or 5).

Given the following code, how many times will the inner loop body execute? int row = 0; int col = 0; for(row = 0; row < 2; row = row + 1) { for(col = 0; col < 3; col = col + 1) { // Inner loop body } }

Answer: 6 Explanation: The outer loop executes 2 times (row is 0, then 1). The inner loop executes 3 times (col is 0, 1, 2) for every outer loop execution. 2 * 3 is 6.

randGen already exists. What is the largest possible value returned by rand() % 10?

Answer: 9 Explanation: num % 10 can range from 0 to 9.

Loop iterates from -100 to 31 (inclusive). i = -100; while (i 32) { /& Loop body statements go ere */ i = i + 1; }

Answer: < Explanation: Good practice is to compare explicitly with the value of most interest, in this case 31, so i <= 31 might be better. But < is commonly used by programmers too, so it is important to understand.

What will the following code output? (For an infinite loop, type "IL") int x = 0; while (x > 0) { cout << x << " "; x = x - 1; } cout << "Bye";

Answer: Bye Explanation: x = 0 so the loop is never entered.

True or False: Each of the for loop variations below yields a syntax error. // initialExpression not related to counting iterations; move r = rand() before loop for (i = 0, r = rand(); i < 5; ++i) { // Loop body } // updateExpression not related to counting iterations; move r = r + 2 into loop body for (i = 0; i < 5; ++i, r = r + 2) { // Loop body }

Answer: False Explanation: Each is valid code.

True or False: Expert programmers need not develop programs incrementally.

Answer: False Explanation: Even experts program incrementally. They may take slightly bigger steps than a novice, but expert programmers are continually compiling and running their programs as they write code.

True or False: Once a program is complete, one would expect to see several FIXME comments.

Answer: False Explanation: FIXME comments should have been replaced by actual code in a completed program.

True or False: A good programming process is to write the entire program, then incrementally remove bugs one at a time.

Answer: False Explanation: That's a terrible way to program, yet that's how many new programmers program. Better to first write a simple version of the program, test it, and then add more behavior incrementally.

True or False: Putting ++i at the end of a for loop body, in addition to in the updateExpression part, yields a syntax error.

Answer: False Explanation: The code is valid. The ++i in the loop body will execute, and then the ++i from the updateExpression part will also execute, thus incrementing i twice.

What loop condition achieves the given racetrack driving goal: Loop while the car's fuel tank is at least 20% full.

Answer: Fuel tank is 20% or more. Explanation:

What loop condition achieves the given racetrack driving goal: Loop while the car's fuel tank is at least 20% full.

Answer: Fuel tank is 20% or more. Explanation: The driver will loop for any fuel level of 20% or more. As soon as the level is 19% or less, the driver will stop looping.

What will the following code output? (For an infinite loop, type "IL") int z = 0; char c = 'y'; while (c = 'y') { cout << z << " "; cin >> c; z = z + 1; }

Answer: IL Explanation: Because the expression is c = 'y' rather than c == 'y', the expression always evaluates to true --- this is a common error. If == were used, and the user entered 'q', the output would be 0 followed by a space.

What will the following code output? (For an infinite loop, type "IL") int x = 0; while (x <= 5) { cout << x << " "; }

Answer: IL Explanation: Because x is not updated within the loop, x is always less than 5. Not updating is a common cause of an infinite loop.

What will the following code output? (For an infinite loop, type "IL") int x = 10; while (x != 3) { cout << x << " "; x = x / 2; }

Answer: IL Explanation: No matter how many times 10 is divided by 2, the result will never equal 3. The programmer perhaps should have used x >= 3.

What loop condition achieves the given racetrack driving goal: Loop as long as it is not raining.

Answer: It is not raining. Explanation: The driver continues looping as long as it is not raining.

What loop condition achieves the given racetrack driving goal: Loop as long as it is sunny.

Answer: It is sunny. Explanation: If it's sunny, drive a loop. After the loop, if it's still sunny, drive another loop.

Consider the following loop: int count = 0; int num = 6; do { num = num - 1; count = count + 1; } while (num > 4); What initial value of num would prevent count from being incremented?

Answer: No such value Explanation: By design, the do-while loop interates at least once, thus incrementing count at least once.

Below is a program that has a "conversation" with the user, asking the user to type something and then (randomly) printing one of four possible responses until the user enters "Goodbye": #include <iostream> #include <string> using namespace std; /* Program that has a conversation with the user. Uses a switch statement and a random number (sort of) to mix up the program's responses. */ int main() { int randNum0_3 = 0; // Random number 0 to 3 string userText; // User input cout << "Tell me something about yourself. "; cout << "You can type \"Goodbye\" at anytime to quit." << endl << endl; cout << "> "; getline(cin, userText); while (userText != "Goodbye") { randNum0_3 = userText.length() % 4; // "Random" num. %4 ensures 0-3 switch (randNum0_3) { case 0: cout << endl << "Please explain further." << endl << endl; cout << "> "; break; case 1: cout << endl << "Why do you say: \"" << userText << "\"?" << endl << endl; cout << "> "; break; case 2: cout << endl << "I don't think that's right." << endl << endl; cout << "> "; break; case 3: cout << endl << "What else can you share?" << endl << endl; cout << "> "; break; default: cout << endl << "Uh-oh, something went wrong. Try again." << endl << endl; } getline(cin, userText); } cout << endl << "It was nice talking with you. Goodbye." << endl; return 0; } Which switch branch will execute if the user types "Goodbye"? Valid answers are branch 0, 1, 2, 3, or none.

Answer: None Explanation: The while loop condition checks if the user typed "Goodbye". If so, the loop body will NOT be executed, and instead the "It was nice talking..." message gets printed.

What loop condition achieves the given racetrack driving goal: Lopp 3 times.

Answer: Number of completed laps is less than 3. Explanation: When the driver starts, number of completed laps is 0. After the first lap, it's 1, After the second, it's 2. After the third, it's 3. 3 is not less than 3, so the driver doesn't start a fourth lap.

Below is a program that has a "conversation" with the user, asking the user to type something and then (randomly) printing one of four possible responses until the user enters "Goodbye": #include <iostream> #include <string> using namespace std; /* Program that has a conversation with the user. Uses a switch statement and a random number (sort of) to mix up the program's responses. */ int main() { int randNum0_3 = 0; // Random number 0 to 3 string userText; // User input cout << "Tell me something about yourself. "; cout << "You can type \"Goodbye\" at anytime to quit." << endl << endl; cout << "> "; getline(cin, userText); while (userText != "Goodbye") { randNum0_3 = userText.length() % 4; // "Random" num. %4 ensures 0-3 switch (randNum0_3) { case 0: cout << endl << "Please explain further." << endl << endl; cout << "> "; break; case 1: cout << endl << "Why do you say: \"" << userText << "\"?" << endl << endl; cout << "> "; break; case 2: cout << endl << "I don't think that's right." << endl << endl; cout << "> "; break; case 3: cout << endl << "What else can you share?" << endl << endl; cout << "> "; break; default: cout << endl << "Uh-oh, something went wrong. Try again." << endl << endl; } getline(cin, userText); } cout << endl << "It was nice talking with you. Goodbye." << endl; return 0; } What will be printed if the user types "Ouch"?

Answer: Please explain further. Explanation: "Ouch" is four characters long. 4 % 4 is 0. The first switch branch executes.

True or False: FIXME comments provide a way for a programmer to remember what needs to be added.

Answer: True Explanation: FIXME comments help a programmer keep track of what hasn't been done yet.

True or False: Incremental programming may help reduce the number of errors in a program.

Answer: True Explanation: Incremental programming helps catch errors earlier, before they get lost inside bigger programs.

True or False: Even though these for loop variations mya execute correctly, they are generally considered bad style. // initialExpression not related to counting iterations; move r = rand() before loop for (i = 0, r = rand(); i < 5; ++i) { // Loop body } // updateExpression not related to counting iterations; move r = r + 2 into loop body for (i = 0; i < 5; ++i, r = r + 2) { // Loop body }

Answer: True Explanation: The for loop parts should be restricted to counting iterations. Knowing that the initialExpression executes before the loop doesn't justify pulling code down into that part. Likewise, knowing the updateExpression part executes at the end of each loop doesn't justify pulling code up into that part.

A dice-rolling program's pseudo-random number generator is seeded with a number based on the current time. The program is run and prints 3, 2, 1, 6. An hour later, the program is run again. What is the first number printed? Type a number or "Unknown" if the solution is unknown.

Answer: Unknown Explanation: The current time itself is essentially a random number. So the seeds will almost certainly be different, resulting in a different number sequence.

randGen already exists. If program is executing and rand() % 10 evaluates to 4, what will the next rand() % 10 return?

Answer: Unknown Explanation: The numbers are random, so we can't possibly know. That's what random means.

Below is a program that has a "conversation" with the user, asking the user to type something and then (randomly) printing one of four possible responses until the user enters "Goodbye": #include <iostream> #include <string> using namespace std; /* Program that has a conversation with the user. Uses a switch statement and a random number (sort of) to mix up the program's responses. */ int main() { int randNum0_3 = 0; // Random number 0 to 3 string userText; // User input cout << "Tell me something about yourself. "; cout << "You can type \"Goodbye\" at anytime to quit." << endl << endl; cout << "> "; getline(cin, userText); while (userText != "Goodbye") { randNum0_3 = userText.length() % 4; // "Random" num. %4 ensures 0-3 switch (randNum0_3) { case 0: cout << endl << "Please explain further." << endl << endl; cout << "> "; break; case 1: cout << endl << "Why do you say: \"" << userText << "\"?" << endl << endl; cout << "> "; break; case 2: cout << endl << "I don't think that's right." << endl << endl; cout << "> "; break; case 3: cout << endl << "What else can you share?" << endl << endl; cout << "> "; break; default: cout << endl << "Uh-oh, something went wrong. Try again." << endl << endl; } getline(cin, userText); } cout << endl << "It was nice talking with you. Goodbye." << endl; return 0; } What will be printed if the user types "Bye"?

Answer: What else can you share? Explanation: Because "Bye" is three characters long and 3 % 4 is 3, the third switch branch executes.

Use a single operator in each expression, and the most straightforward translation of the stated goal into an expression. Iterate while c is not equal to 'x'. while ( ) { /* Loop body statements go here */ }

Answer: c != 'x' Explanation: As long as c is not equal to 'x', the loop executes. When c equals 'x', the loop finishes.

Use a single operator in each expression, and the most straightforward translation of the stated goal into an expression. Iterate until c equals 'z' (trucky; think carefully). while ( ) { /* Loop body statements go here */ }

Answer: c != 'z' Explanation: c == 'z' is incorrect. Note the word "until", meaning to loop while c does not equal 'z'.

Use a single operator in each expression, and the most straightforward translation of the stated goal into an expression. Iterate while c equals 'g'. while ( ) { /* Loop body statements go here */ }

Answer: c == 'g' Explanation: As long as c is 'g', the loop executes. A common error is to use = rather than ==.

Choose the most appropriate loop type. Iterate 100 times.

Answer: for Explanation: The iterations are known before the loop, so use "for ( i=1 ; i<=100; ++i)".

Loop iterates with i being the odd integers from 0 to 9. i = 1; while (i <= 9) { // Loop body i = ; }

Answer: i + 2 Explanation: i will be 1, 3, 5, 7, and 9. When 11, the loop body is not entered.

Loop iterates with i being mltiples of 5 from 0 to 1000 (inclusive). i = 0; while (i <= 1000) { // Loop body i = ; }

Answer: i + 5 Explanation: A common error is using i = i * 5, which yields 0, 0, 0, ..., rather than 0, 5, 10, 15, ... Even if i was initialized 1, using i = i * 5 would yield 1, 5, 25, 125, ..., which are powers of 5, not multiples of 5.

Loop iterates from 212 to 32 (inclusive). i = 212; while (i > 32) { // Loop body i = ; }

Answer: i - 1 Explanation: Counting down is not as common as counting up, but still occurs.

Use <= in each loop expression. Loop iterates 10 times. i = 1; while ( ) { // Loop body i= i + 1; }

Answer: i <= 10 Explanation: The loop body will execute when i is 1, 2, ..., 9, 10. When 11, the loop body will not be executed.

Use <= in each loop expression. Loop iterates 2 times. i = 1; while ( ) { // Loop body i= i + 1; }

Answer: i <= 2 Explanation: The loop body will execute when i is 1 or 2. When i is 3, the loop body will not be executed.

Use <= in each loop expression. Loop iterates 8 times. (Note the initial value of i.) i = 0; while ( ) { // Loop body i= i + 1; }

Answer: i <= 7 Explanation: By starting with i = 0, the loop will execute when i is 0, 1, 2, 3, 4, 5, 6, and 7, which is a total of 8 iterations.

Complete the for loop to achieve the goal. Use prefix increment (++i) or decrement (--i) where appropriate. Iterate for i from -10 to 10. Compare with 10. for ( ) { // Loop body }

Answer: i = -10; i <= 10; ++i Explanation: Items are separated by ; The loop iterates for i of -10, -9, ..., -1, 0, 1, ..., 9, 10.

Complete the for loop to achieve the goal. Use prefix increment (++i) or decrement (--i) where appropriate. Iterate for i from 0 to 20 by 2s (0, 2, 4, ...). Use i = ??, NOT ++i. for (i = 0; i <= 20; ) { // Loop body }

Answer: i = i + 2 Explanation: The loop update need not just be increment or decrement.

Complete the for loop to achieve the goal. Use prefix increment (++i) or decrement (--i) where appropriate. Iterate for i from 99 down to 0. Compare with 0. for (i = 9; --i) { // Loop body }

Answer: i >= 0; Explanation: This expression is checked before each loop iteration. If true, the loop body executes.

Complete the for loop to achieve the goal. Use prefix increment (++i) or decrement (--i) where appropriate. Iterate for numCars from 1 to 500. Note the variable is numCars (not i). for ( numCars <= 500; ++numCars) { // Loop body }

Answer: numCars = 1; Explanation: This assignment is executed exactly once, before the looping really begins, just like a statement appearing before a while loop.

Choose the most appropriate loop type. Iterate until the values of x and y are equal, where x and y are changed in the loop body.

Answer: while Explanation: Iterate until the values of x and y are equal, where x and y are changed in the loop body.

Choose the most appropriate loop type. Iterate as long as user-entered char c is not 'q'.

Answer: while Explanation: The iterations are not known before the loop, so use "while (c != 'q')".

Use a single operator in each expression, and the most straightforward translation of the stated goal into an expression. Iterate while x is less than 100. while ( ) { /* Loop body statements go here */ }

Answer: x < 100 Explanation: 100 > x is also correct, but is not a straightforward translation of the stated goal (and slightly non-intuitive).

Use a single operator in each expression, and the most straightforward translation of the stated goal into an expression. Iterate while x is greater than or equal to 0. while ( ) { /* Loop body statements go here */ }

Answer: x >= 0 Explanation: Note that x => 0 is not OK because => is not an operator.

What is output by the following code? char letter1 = '?'; char letter2 = '?'; letter1 = 'y'; while (letter1 <= 'z') { letter2 = 'a'; while (letter2 <= 'c') { cout << letter1 << letter2 << " "; ++letter2; } ++letter1; }

Answer: ya yb yc za zb zc Explanation: The outer loop ranges from y to z, and the inner loop ranges from a to c. First outer loop iteration prints ya yb yc. Second prints za zb zc.

Refer to the GCD code provided in the figure below. Assume user input of numA = 15 and numB = 10. #include <iostream> using namespace std; // Output GCD of user-input numA and numB int main() { int numA = 0; // User input int numB = 0; // User input cout << "Enter first positive integer: "; cin >> numA; cout << "Enter second positive integer: "; cin >> numB; while (numA != numB) { // Euclid's algorithm if (numB > numA) { numB = numB - numA; } else { numA = numA - numB; } } cout << "GCD is: " << numA << endl; return 0; } For the GCD program, what is the value of numA before the first loop iteration?

Answer:15 Explanation: numA is 15, the original value assigned by the user. Because we have yet to perform a loop iteration; numA's value is still 15.


संबंधित स्टडी सेट्स

Managerial Accounting, 4e (Whitecotton) Chapter 6 testbank

View Set

Exam 3 Renal combined Suprapubic Pain and Hematuria

View Set