Quiz 4 Solutions

You have up to 25 minutes. Please write your answers on this page, and your name at the top. You may not use the computer, notes, or books.

This program contains a loop. What does it output?

#include <iostream>
using namespace std;
int main()
{
    int k = 9;
    while(1)
    {
        if(k % 2 == 0)
        {
            cout << k*k << "\n";
        }
        if(k % 5 == 0)
        {
            break;
        }
        k--;
    }
    cout << k << "\n";
    return 0;
}

64
36
5

Here is another program with a loop. What does it output?

#include <iostream>
using namespace std;
int main()
{
    int x = 0;
    for(int i = 1; i < 8; i+=2)
    {
        cout << i << "\n";
        x += i;
    }
    cout << x << "\n";
    return 0;
}

1
3
5
7
16

Here is a program that does some string manipulation within a loop. What does it output?

#include <iostream>
using namespace std;
int main()
{
    string name = "grace hopper";
    for(unsigned int i = 1; i < name.size(); )
    {
        switch(name.at(i))
        {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            name.erase(i,1);
            break;
        case 'g': case 'h':
            name.at(i) = 'Z';
        default:
            i++;
        }
    }
    cout << name << endl;
}

grc Zppr