CSCI 159: exam practice sample solutions

Question 1: Nested loops

Assuming ROWS and COLUMNS are positive integer values, describe the pattern the following code segment produces:
for (int r = 1; r <= ROWS; r++) {
    for (int c = 1; c <= COLUMNS; c++) {
        if ((r == 1) || (c == 1)) {
           cout << "*";
        } else if (c == COLUMNS) {
           cout << "*" << endl;
        } else if (r == ROWS) {
           cout << "*";
        } else if (c == r) {
           cout << "\";
        } else {
           cout << " ";
        }
    }
}
(Tip: try working through it on paper with small values for rows and columns, e.g. 5 and 6.)
Sample answer:
A rectangle with asterisks as the boundaries and slashes running more or less diagonally
across it, e.g. for 5 rows and 6 columns:
******
*\   *
* \  *
*  \ *
******

Question 2: loops and character arrays

Suppose we have a character array defined and filled in as shown below, where SIZE is some integer constant:
int main()
{
   char mytext[SIZE];
   cout << "Enter a line of text: ";
   cin.getline(mytext, SIZE);
}
Add a loop to the main routine to print each of the alphabetic characters from their line of text, but not the nonalphabetic ones (e.g. if their text was "I took 159 and it drove me crazy!" then the output would be "Itookanditdrovemecrazy").

Tip 1: strlen(mytext) will tell you how many characters they entered
Tip 2: isalpha(ch) takes a single character as a parameter and returns true if the character was alphabetic, false otherwise
Sample answer:
int len = strlen(mytext);
for (int i = 0; i < len; i++) {
    if (isalpha(mytext[i])) {
       cout << mytext[i]
    }
}