Strings & For-Each Loop Review¶


Q) Which of the following is a primary advantage of the for-each loop?¶

a) Able to give more descriptive variable name to the index variable.
b) It is the only way to loop through characters in a string.
c) Does not need an index variable, so unable for the loop to go out of bounds.
d) It is the only way to iterate through the values in a vector.


Q) Consider the following code which is adding up numbers in a vector:¶

In [ ]:
// Return the sum of all elements in the vector `data`
int sumVector(vector<int> data) {
    int sum = 0;
    XXXXXX
        sum += val;
    }
    return sum;
}

Which of the following lines of code is best to replaces the line XXXXXX above?

a) for (int val : data) {
b) for (unsigned int val = 0; val < data.size(); val++) {
c) for (data : int val) {
d) for (vector val : data) {


Q) Which of the following is the best description of what this code does?¶

In [ ]:
string foo(string s) 
{
    string r;
    for (char ch : s) {
        r += toupper(ch);
    }
    return r;
}

a) Prints a string in all uppercase.
b) Counts the number of uppercase characters.
c) Adds up the ascii values of all the characters in the string.
d) Returns a copy of the input string s in all upper case.


Answers¶

c) Does not need an index variable, so unable for the loop to go out of bounds.
a) for (int val : data) {
d) Returns a copy of the input string s in all upper case.