Midterm Practice Problems

What follows is a list of exercises, categorized into different types of problem
(debugging, writing code, reading code).

Solutions to some of the problems are available here.

Important: When solving these problems remember that you will not have a computer with you
   at the midterm. If you can't solve a problem without using the computer, that means you 
   should study that subject more tonight.
    (For the code-writing exercises I recommend working in notepad. You can always check your
     code in visual studio once you're finished.)

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

1. Fixing broken code
The following programs contain errors. Some of the errors are compilation errors
(the program will not build). Other errors are logic errors (the program will
build and run, but won't do what we want it to do). Your job is to find both
kinds of errors and correct them.

Try to spot the errors before you try compiling and running the code.

--------------------------------------------------------------------------------
A. 1 error.
--------------------------------------------------------------------------------
#include <iostream>

using namespace std;

int mian() {
    cout << "Hlelo Wrold!" << endl;
    return 0;
}

--------------------------------------------------------------------------------
B. 2 errors.
--------------------------------------------------------------------------------
#include <iostream>

using namespace std;

int main() {
    double height = 0;
    double mass = 0;
    const double gravity = 6.674e-11; // 6.674*10^{-11} N(m/kg)^2
    const double earth_radius = 6.371e6; // 6371 km
    const double earth_mass = 5.9736e24;
    double gravitational_potential = gravity * earth_mass * mass / (earth_radius + height) * (earth_radius + height); // E = G*m*M / R^2

    cout << "What is the mass of the object?" << endl;
    cin >> mass;
    cout << "How far above the ground is it?" << endl;
    cin >> height;

    cout << "The thing has " << gravitational_potential << " N of energy." << endl;

    return 0;
}



--------------------------------------------------------------------------------
C. 5 errors
--------------------------------------------------------------------------------
#include <iostream>

using namespace std;

int main() {
    int month;
    cout << "What month is it? (1-12)" << endl;
    cin >> month;
    cout << "The current season is ";
    if ( 1 <= month <= 3 ) {
        cout << "winter";
    }
    else if ( 4 <= month <= 6 ) {
        cout << "spring";
    }
    else if ( 7 <= month <= 9 ) {
        cout << "summer";
    }
    else if ( 10 <= month <= 12 ) {
        cout << autumn;
    }
    else {
        cout << "unknown because you didn't enter a real month";
    }
    cout << "!" << endl;

    return 0;
}

--------------------------------------------------------------------------------
D. 3 errors
--------------------------------------------------------------------------------
#include <iostream>
#include <string>

int main() {
    string response;

    cout << "Ennyn Durin Aran Moria. Pedo mellon a Minno. Im Narvi hain echant. Celebrimbor o Eregion tethant. I thiw hin." << endl;
    cout << "The Doors of Durin, Lord of Moria. Speak friend and enter. I Narvi made them. Celebrimbor of Hollin drew these signs." << endl;
    
    cin >> response

    if ( response == "mellon" ) {
        cout << "The star shines out briefly and fades again. Silently, a great "
             << "doorway is outlined, though not a crack or joint was visible "
             << "before. Slowly it divides in the middle and swings outward "
             << "inch by inch, until both doors lie back against the wall. "
             << "Through the opening a shadowy stair can be seen climbing steeply "
             << "up; but beyond the lower steps the darkness is deeper than the night."
             << endl;
        cout << endl << "Moria lies before you. << endl;
    }
    else if ( response == "open sesame" ) {
        cout << "The side of the mountain shakes with mighty force, and a cave "
             << "opens itself before you. Within lie the riches of the forty "
             << "theives, treasures beyond your wildest dreams." << endl;
    }
    else {
        cout << "Nothing happens..." << endl;
    }

    return 0;
}

--------------------------------------------------------------------------------
E. 1 error
--------------------------------------------------------------------------------
#include <iostream>

using namespace std;

int main() {
    int x;
    int y;
    cout << "What is x?" << endl;
    cin >> x;
    cout << "What is y?" << endl;
    cin >> y;

    if ( x < y )
        cout << "x should not be less than y.";
        int temp = x;
        x = y;
        y = temp;
        cout << " Swapped x and y." << endl;

    cout << y <<  " <= " << x << endl;
    return 0;
}

--------------------------------------------------------------------------------
F. 1 error
--------------------------------------------------------------------------------
#include <iostream>
using namespace std;

int main() {
    cout << "Guess my secret number! It's between 1 and 100\n";
    int guess;
    cin >> guess;
    if (guess = 16)
        cout << "Wow! You got it right!\n";
    else
        cout << "Nope. Better luck next time.\n";
    return 0;
}

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

2. Writing code
Write code to solve the following problems. Sample inputs and outputs have been
provided. Burnt ochre text represents things typed by the user, while azure text
represents things the program should print.

--------------------------------------------------------------------------------
A.
--------------------------------------------------------------------------------
Write a program that computes the user's GPA for the quarter. Assume the user is
taking four classes, and the only possible grades are:
        A (=4.0), B (=3.0), C (=2.0), D (=1.0), and F (=0.0).

Sample Input/Output:
Grade for class #1: 4
Grade for class #2: 2
Grade for class #3: 4
Grade for class #4: 4
GPA is 3.5

--------------------------------------------------------------------------------
B.
--------------------------------------------------------------------------------
Write a program that inputs a number from the user, and outputs a pyramid of stars
with height equal to the input number.

Sample Input/Output
Please input a number: 4
*
**
***
****


This problem builds off of the printing stars problems from last time.
So if you find this difficult, look at those problems (and maybe the solutions) and see if you can use those ideas.

--------------------------------------------------------------------------------
C.
--------------------------------------------------------------------------------
Write a program that prints solutions to the quadratic equation ax^2+bx+c=0,
after asking the user for a, b, and c. If there are no solutions, display a
message informing the user that this is the case. Remember that there is a sqrt
function in the <cmath> library.
E.g.,
Coefficient of x^2: 0.5
Coefficient of x: 0.5
Constant coefficient: -1
The roots of 0.5 * x^2 + 0.5 * x + -1 are -2.0 and 1.0.

Coefficient of x^2: 2
Coefficient of x: 2
Constant coefficient: 1
2 * x^2 + 2 * x + 1 has no roots!

Coefficient of x^2: 5
Coefficient of x: 0
Constant coefficient: 0
The only root of 5 * x^2 + 0 * x + 0 is 0.

Some hints:
I don't want you guys to worry about the math part of the problem, so I'll do
that for you.
The solutions to the equation (from the quadratic formula) are
  (-b + sqrt(b^2 - 4ac))/(2a)
  (-b - sqrt(b^2 - 4ac))/(2a)

How many roots we get depends on the b^2-4ac part.
It it's negative, then there are no roots (can't sqrt a negative number)
If it's zero, then there is only one root (the + and - roots will be equal)
If it's positive, then there are two roots (given above)

Your job:
Input a, b, c from the user.
Do the necessary calculations.
Put together a reasonable set of if statements to produce the correct
   output in each of the above cases.

--------------------------------------------------------------------------------
D.
--------------------------------------------------------------------------------
Ask the user for two numbers. Print a '(' at the column on screen indicated by
the first, and a ')' at the column indicated by the second. If the numbers are the same, print an 'O' there instead.

Sample Output:
Given 3 and 6, you should produce the following:
  (  )
Given 10 and 11:
        ()
Given 8 and 4:
   )   (
Given 7 and 7:
      O

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

3. Reading code
Try to figure out what the following code does without running it. Afterwards,
run the code to check your answer.

--------------------------------------------------------------------------------
A.
--------------------------------------------------------------------------------
#include <iostream>

using namespace std;

int main() {
    int x = 4;

    cout << "x = " << x << endl;
    if ( x < 10 ) {
        x = x + 100;
        cout << "Increasing x!" << endl;
    }
    if ( x > 20 ) {
        x = x - 1000;
        cout << "x is far too big. Decreasing." << endl;
    }
    cout << "x = " << x << endl;

    x = 4;
    cout << "x = " << x << endl;
    if ( x < 10 ) {
        x = x + 100;
        cout << "Increasing x!" << endl;
    }
    else if ( x > 20 ) {
        x = x - 1000;
        cout << "x is far too big. Decreasing." << endl;
    }
    cout << "x = " << x << endl;

    return 0;
}

--------------------------------------------------------------------------------
B.
--------------------------------------------------------------------------------
#include <iostream>

using namespace std;

int main() {
    int x = 4;
    int y = 5;

    x = x + y;
    y = x - y;
    x = x - y;

    cout << "x = " << x << ", y = " << y << endl;

    return 0;
}

--------------------------------------------------------------------------------
C.
--------------------------------------------------------------------------------
#include <iostream>
#include <string>

using namespace std;

int main() {
    const string p = "swordfish";
    string i;

    cout << "Tell me something..." << endl;
    getline( cin, i );

    int x = i.find( p );
    if ( x == string::npos ) {
        cout << "ACCESS DENIED." << endl;
    }
    else if ( p == i ) {
        cout << "ACCESS GRANTED." << endl;
    }
    else {
        i.erase(i.find(p), p.length());
        cout << "\"" + i + "\" is a better way to say that." << endl;
    }

    return 0;
}

--------------------------------------------------------------------------------
D.
--------------------------------------------------------------------------------
#include <iostream>

using namespace std;

int main() {
    int month;
    int day;

    cout << "What is m?\n";
    cin >> month;
    if ( month <= 0 || month > 12 ) {
        cout << "INVALID!\n";
        return -1;
    }
    cout << "What is d?\n";
    cin >> day;
    if ( day < 1 || day > 31 ) {
        cout << "INVALID!\n";
        return -1;
    }
    else if ( day > 29 && month == 2 ) {
        cout << "INVALID!\n";
        return -1;
    }
    else if ( day == 29 && month == 2 ) {
        cout << "INVALID!\n";
        return -1;
    }
    else if ( day == 31 && (month == 9 || month == 4 || month == 6 || month == 11) ) {
        cout << "INVALID!\n";
        return -1;
    }
    
    cout << "VALID!\n";
    return 0;
}

--------------------------------------------------------------------------------
Challenge Problem
--------------------------------------------------------------------------------

The purpose of this problem is to give you something to do if you finish the other stuff early.


    Write a program that inputs a string, then applies a right-shift cipher to that string.
    In other words, take each character in the string, and change it to the next char in the
    alphabet.

    Example input and output:
    If I input "hello", the program should output "ifmmp"
    If I input "abcde", the program should output "bcdef"
    If I input "xyz", the program should output "yza"
    If I input "i like programming" the program should output "j mklf qsphsbnnjoh"
    If I input "aBcDE!!fg" the program should output "bCdEF!!gh"
    
    Start by writing a simple version of the program that doesn't handle all cases. For example,
    you can first make sure your program works when the string has no spaces and only lower-case
    letters (no special characters). Then maybe you can make it handle capital letters. After that
    you can worry about special characters and spaces. This is generally a good idea when solving
    longer problems. Writing the entire thing at once is hard. It's better to break it up into
    smaller tasks.

    Suggestions: Google how to add characters. For example, find out what 'A'+1 means in C++.
         Look up the 'isalpha' function. This will help you differentiate between
            letters and special characters.
            There are a lot of similar methods. isupper, islower, toupper, etc.
            Depending on how you solve this problem, you might need them.