C++, Chapter 6

Ace your homework & exams now with Quizwiz!

24. Consider the following algorithm for collecting all matches in an array: int matches_size = 0; for (int i = 0; i < size of values; i++) { if (values[i] fulfills the condition) { matches[matches_size] = values[i]; matches_size++; } } How can this algorithm help you with Self Check 23?

24. Use the algorithm to collect all positive values in an array, then use the algorithm in Section 6.2.5 to print the array of matches. cfe2_ch06_p249_306.indd 304 10/26/10 7:48 PM answers to self-Check Questions 305

25. Walk through the algorithm that we developed in this section, using two paper clips to indicate the positions for i and j. Explain why there are no bounds errors in the pseudocode.

25. The paperclip for i assumes positions 0, 1, 2, 3. When i is incremented to 4, the con dition i < size / 2 becomes false, and the loop ends. Similarly, the paperclip for j assumes positions 4, 5, 6, 7, which are the valid positions for the second half of the array.

26. Take out some coins and simulate the following pseudocode, using two paper clips to indicate the positions for i and j: i = 0 j = size - 1 while (i < j) swap elements at positions i and j i++ j-- What does the algorithm do?

26. It reverses the elements in the array.

27. Consider the task of rearranging all values in an array so that the even numbers come first. Other wise, the order doesn't matter. For example, the array 1 4 14 2 1 3 5 6 23 could be rearranged to 4 2 14 6 1 5 3 23 1 Using coins and paperclips, discover an algorithm that solves this task by swapping elements, then describe it in pseudocode.

27. Here is one solution. The basic idea is to move all odd elements to the end. Put one paper clip at the beginning of the array and one at the end. If the element at the first paper clip is odd, swap it with the one at the other paper clip and move that paper clip to the left. Otherwise, move the first paper clip to the right. Stop when the two paper clips meet. Here is the pseudocode: i = 0 j = size - 1 While (i < j) If (a[i] is odd) Swap elements at positions i and j. j-- Else i++

28. Discover an algorithm for the task of Self Check 27 that uses removal and insertion of elements instead of swapping.

28. Here is one solution. The idea is to remove all odd elements and move them to the end. The trick is to know when to stop. Nothing is gained by moving odd elements into the area that already contains moved elements, so we want to mark that area with another paper clip. i = 0 moved = size While (i < moved) If (a[i] is odd) Remove the element at position i and add it at the end. moved--

29. Consider the algorithm in Section 4.7.4 that finds the largest element in a sequence of inputs—not the largest element in an array. Why is this algorithm better visualized by picking playing cards from a deck rather than arranging toy soldiers in a sequence?

29. When you read inputs, you get to see values one at a time, and you can't peek ahead. Picking cards one at a time from a deck of cards simulates this process better than looking at a sequence of items, all of whom are revealed.

3. Assume the array primes has been initialized as described in Self Check 1. What is its contents after executing the following loop? for (int i = 0; i < 5; i++) { primes[i]++; }

3. 3, 4, 6, 8, 12

30. What results do you get if you total the columns in our sample data?

30. You get the total number of gold, silver, and bronze medals in the competition. In our example, there are four of each.

31. Consider an 8 × 8 array for a board game: int board[8][8]; Using two nested loops, initialize the board so that zeroes and ones alternate, as on a checkerboard: 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 ... 1 0 1 0 1 0 1 0 Hint: Check whether i + j is even.

31. for (int i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { board[i][j] = (i + j) % 2; } }

32. Define a two-dimensional array for representing a tic-tac-toe board. The board has three rows and columns and contains strings "x", "o", and " ".

32. string board[3][3];

33. Write an assignment statement to place an "x" in the upper-right corner of the tic-tac-toe board.

33. board[0][2] = "x"; cfe2_ch06_p249_306.indd 305 10/26/10 7:48 PM 306 Chapter 6 arrays and Vectors

34. Which elements are on the diagonal joining the upper-left and the lower-right corners of the tic-tac-toe board?

34. board[0][0], board[1][1], board[2][2]

35. Define a vector of integers that contains the first five prime numbers (2, 3, 5, 7, and 11). Use push_back to add the elements.

35. vector<int> primes; primes.push_back(2); primes.push_back(3); primes.push_back(5); primes.push_back(7); primes.push_back(11);

36. Answer Self Check 35 without using push_back.

36. vector<int> primes(5); primes[0] = 2; primes[1] = 3; primes[2] = 5; primes[3] = 7; primes[4] = 11; .

38. Suppose you want to store a set of temperature measurements that is taken every five minutes. Should you use a vector or an array?

38. The problem doesn't state how many measurements are taken. If the measurements go on for many months or years (which could well be the case in a scientific or industrial application), a vector is the better choice. If you know that the measurements are stored for a fixed period (say, one day), then an array will work equally well.

39. Suppose you want to store the names of the weekdays. Should you use a vector or an array of seven strings?

39. Because the numbers of weekdays doesn't change, there is no disadvantage to using an array.

Given the definition const int CAPACITY = 10; double values[CAPACITY]; write statements to put a zero into the elements of the array values with the lowest and the highest valid index.

4. values[0] = 0; values[CAPACITY - 1] = 0;

40. Write the header for a function that appends two vectors, yielding a third vector. Do not implement the function

40. vector<double> append(vector<double> first, vector<double> second) Contrast this with the answer to Self Check 19.

41. Consider this partially completed function that appends the elements of one vector to another. void append(vector<double>__ target, vector<double>__ source) { for (int i = 0; i < source.size(); i++) { target.push_back(source[i]); } } Specify whether the parameters should be value or reference parameters.

41. target must be a reference parameter, source should be a value parameter

Given the array defined in Self Check 4, write a loop to print the elements of the array values in reverse order, starting with the last element.

5. for (int i = SIZE - 1; i >= 0; i--) { cout << values[i] << endl; }

Define an array called words that can hold ten values of type string.

6. string words[10];

7. Define an array containing two strings, "Yes", and "No".

7. string words[] = { "Yes", "No" };

8. What is the output of the largest.cpp program with the following inputs? 20 10 20 Q

8. 20 <== largest value 10 20 <== largest value

Write a loop that counts how many elements in an array are equal to zero.

9. int count = 0; for (int i = 0; i < size; i++) { if (values[i] == 0) { count++; } }

37. What is the contents of the vector names after the following statements? vector<string> names; names.push_back("Ann"); names.push_back("Bob"); names.pop_back(); names.push_back("Cal");

Ann, Cal

Define an array of integers containing the first five prime numbers

1. int primes[] = { 2, 3, 5, 7, 11 };

Consider the algorithm to find the largest element in an array. Why don't we initialize largest and i with zero, like this? double largest = 0; for (int i = 0; i < size of values; i++) { if (values[i] > largest) { largest = values[i]; } }

10. If all elements of values are negative, then the result is incorrectly computed as 0.

When printing separators, we skipped the separator before the initial element. Rewrite the loop so that the separator is printed after each element, except for the last element.

11. for (int i = 0; i < size; i++) { cout << values[i]; if (i < size - 1) { cout << " | "; } } Now you know why we set up the loop the other way.

What is wrong with these statements for printing an array with separators? cout << values[0]; for (int i = 1; i < size of values; i++) { cout << ", " << values[i]; }

12. If the sequence has no elements, then a random value is printed.

When searching for a match, we used a while loop, not a for loop. What is wrong with using this loop instead? for (pos = 0; pos < size of values && !found; pos++) { if (values[pos] == 100) { found = true; } }

13. If there is a match, then pos is incremented before the loop exits.

When inserting an element into an array, we moved the elements with larger index values, starting at the end. Why is it wrong to start at the insertion location, like this: for (int i = pos; i < size of values - 1; i++) { values[i + 1] = values[i]; }

14. This loop sets all elements to values[pos].

15. What happens if you call the sum function and you lie about the size? For example, calling double result = sum(values, 1000); even though values has size 100.

15. The sum function will add up all the numbers in the values array and the next 900 numbers, yielding a random result. (Actually, there is the chance that the program doesn't have the right to access all those numbers, in which case the operating sys tem will terminate it.)

How do you call the squares function to compute the first five squares and store the result in an array numbers?

16. int numbers[5]; squares(5, numbers);

Write a function that returns the first position of an element in an array, or -1 if the element is not present. Use the linear search algorithm of Section 6.2.6.

17. int find_first(double values[], int size, double searched_value) { for (int pos = 0; pos < size; pos++) { if (values[pos] == searched_value) { return pos; a n s W ers to s e l F -Che C k Q U est I ons cfe2_ch06_p249_306.indd 303 10/26/10 7:48 PM 304 Chapter 6 arrays and Vectors } } return -1; } Note that the loop is simpler than that in Section 6.2.6 since we can simply return the position when a match is found.

8. Rewrite the read_inputs function so that the array size is a reference parameter, not a return value.

18. void read_inputs(double inputs[], int capacity, int& size) { size = 0; double input; while (cin >> input) { if (size < capacity) { inputs[size] = input; size++; } } }

19. Write the header for a function that appends two arrays into another array. Do not implement the function.

19. int append(double first[], int first_size, double second[], int second_size, double target[], int target_capacity) Note the following: • You must pass the sizes of the first and second arrays, so that the function knows how many elements to copy. • You must pass the capacity of the target, so that the function won't write past the end. • The target array is a parameter variable—functions cannot return arrays. • The return type is int, so that the function can return the size of the target. (Alternatively, you could use a reference parameter int& target_size.)

2. Assume the array primes has been initialized as described in Self Check 1. What is its contents after executing the following loop? for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; }

2. 2, 3, 5, 3, 2

20. Section 6.2.7 has two algorithms for removing an element. Which of the two should be used to solve the task described in this section?

20. Use the first algorithm. The order of elements does not matter when computing the sum.

21. It isn't actually necessary to remove the minimum in order to compute the total score. Describe an alternative

21. Find the minimum value. Calculate the sum. Subtract the minimum value.

22. How can you print the number of positive and negative values in a given array, using one or more of the algorithms in Section 4.7?

22. Use the algorithm for counting matches (Section 4.7.2) twice, once for counting the positive values and once for counting the negative values.

23. How can you print all positive values in an array, separated by commas?

23. You need to modify the algorithm in Section 6.2.5. bool first = true; for (int i = 0; i < size of values; i++) { if (values[i] > 0)) { if (first) { first = false; } else { cout << ", "; } } cout << values[i]; } Note that you can no longer use i > 0 as the criterion for printing a separator.


Related study sets

COM 231 Chapter 17 Review Questions.

View Set

I. ABDOMINAL REVIEW - 13. The Male Pelvis

View Set

Accounting I - Chapter 4: the Income Statement

View Set

Chapters 40-44 Exam 4 Review BINGO

View Set

PSY 2012 GENERAL PSYCHOLOGY QUIZ 7

View Set

Cross-Cultural Psychology Exam 3

View Set