Spring 2025 CS 31

Homework 2

Time due: 11:00 PM Thursday, April 17

Prepare your solutions to these homework problems as a single Word document named hw.docx or a plain text file named hw.txt. Turn in this file as described in the Project 2 specification.

  1. What is the output produced by the following program segment? Don't just run it — trace through it and figure it out by hand (which is a skill you'll need for the exams).

    	string grendel = "endl";
    	cout << "endl";
    	cout << grendel;
    	cout << endl;
    	cout << "grendel";
    
  2. Consider the following program:

    	#include <iostream>
    	using namespace std;
    
    	int main()
    	{
    	    int len;
    
    	    cout << "Enter a number: ";
    	    cin >> len;
    
    	    for (int i = 0; i < len; i++)
    	    {
    	        for (int j = i+1; j < len; j++)
    	        {
    	            cout << " ";
    	        }
    	        cout << "#" << endl;
    	    }
    	}
    

    In a brief, simple English sentence, state what this program does (e.g. "It prints a picture of a lantern fish.", not "First it does blah blah blah, then it yada yada yada, then ..."). Again, figure this out by hand.

  3. Copy the program in problem 2 and change it so that for any input number, the changed program produces exactly the same output as the original, but the changed program uses a while loop instead of a for loop for the inner loop.

  4. Assume month has been previously declared as an int and given a meaningful value. Write a switch statement that for any value of month, produces exactly the same output as the following if statement.
    	if (month == 6)
    	    cout << "summer solstice";
    	else if (month == 12)
    	    cout << "winter solstice";
    	else if (month == 3  ||  month == 9)
    	    cout << "equinox";
    	else
    	    cout << "nothing special";