10.18. Activecode Exercises

Answer the following Activecode questions to assess what you have learned in this chapter.

Fix the code below so that it creates a vector with 5 elements initialized to 1, and changes the third element of that vector to a 2.

Below is one way to fix the program. You must always include the <vector> header when dealing with vectors. Furthermore, to initialize a vector’s elements to a certain value, you must include that value as a second argument to the size. Finally, vectors are zero-indexed.

Loading a dynamic question ...
Selecting from: vectors_a2, vectors_a2_pp

Fix the function below so that it creates a vector of all of the words in words that end with the passed character.

Below is one way to fix the function. You must initialize count to zero. You also must initialize last as an integer. To access a string inside of vec, we use vec[i]. To get the last character, we must index the string to the last index, which is one less than the length of the string.

Loading a dynamic question ...
Selecting from: vectors_a4, vectors_a4_pp

Finish the code below so that it creates removes elements from the end of the vector until it ends with "stop".

Below is one way to finish the program. We just use the pop_back function until the last element of the vector is "stop".

Loading a dynamic question ...
Selecting from: vectors_a6, vectors_a6_pp

Write a function called has_char that returns a boolean of whether every string in the vector vec contains the character let. It should return true if all strings contain the let.

Below is one way to finish the program. We loop through the vector, and we loop through each string inside it. If the string has the character, it is added to count. We then check whether count is equal to the number of elements in vec and return a boolean.

Loading a dynamic question ...
Selecting from: vectors_a8, vectors_a8_pp

Write the function mean which returns the average of a vector of numbers.

Below is one way to finish the program. First we take the sum, then divide the sum by the number of elements in nums.

Loading a dynamic question ...
Selecting from: vectors_a10, vectors_a10_pp

Write the function make_odd which subtracts 1 from every even number in a vector of integers. We don’t want any negative values so don’t subtract 1 from 0. ( remember to take in the vector by reference to make changes to the actual vector! )

Below is one way to finish the program. We us the modulus operator to check for even numbers and decrement them. we keep an extra check for 0 to make sure wew are not decrementing 0.

Loading a dynamic question ...
Selecting from: vectors_a12, vectors_a12_pp

You have attempted of activities on this page