Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Exercises 8.15 Coding Practice

1.

Write the function rectangleInfo which prompts the user for the width and height of a rectangle. Then rectangleInfo prints out the area and perimeter of the rectangle.
Solution.
Below is one way to implement the program. We prompt the user for input using cin before printing the area and perimeter.
#include <iostream>
using namespace std;

void rectangleInfo() {
    int height, width;
    cout << "Please enter the height and width of a rectangle separated by spaces: ";
    cin >> height >> width;
    cout << "The area of the rectangle is " << height * width << endl;
    cout << "The perimeter of the rectangle is " << 2 * (height + width) << endl;
}

int main() {
    rectangleInfo();
}

2.

Write a simple function called greetUser which prompts the user for their full name. Then the function outputs “Hello fullName!”. Check the hint below for help with the construction of the code.
Hint.

Activity 8.15.1.

Write a simple function called greetUser which prompts the user for their full name. Then the function outputs “Hello fullName!”. Use the lines to construct the code, then go back to complete the Activecode.

3.

In the not so distant future, robots have replaced humans to do any kind of imaginable work or chore. Define the Robot structure, which has instance variables string name, string model, int serialNumber , int batteryLevelPercentage, and string task in that order. Then write the printRobotData function, which takes a Robot as a parameter and prints out the robot’s data in the following format: name (model serialNumber) has batteryLevelPercentage percent battery and is currently executing the task “task”.
Solution.
Below is one way to implement the program. First we declare the instance variables in the struct definition. Next, we use dot notation to access the instance variables and output them using cout.
#include <iostream>
using namespace std;

struct Robot {
    string name;
    string model;
    int serialNumber;
    int batteryLevelPercentage;
    string task;
};

void printRobotData (Robot r) {
     cout << r.name << " (" << r.model << " " << r.serialNumber
          << ") has " << r.batteryLevelPercentage
          << " percent battery and is currently executing the task \""
          << r.task << "\"" << endl;
}

int main() {
    Robot rob = { "Rob", "XLV", 9800, 45, "washing dishes" };
    cout << "Your output:" << endl;
    printRobotData (rob);
    cout << "Correct output:" << endl;
    cout << "Rob (XLV 9800) has 45 percent battery and is currently executing the task \"washing dishes\"";
}

4.

Robots will naturally deplete their charge as they carry out tasks. Write a function called chargeRobot which takes a Robot as a parameter and charges the robot to 100 percent. Then output the statement “Robot name is fully charged!”. Check the hint below for help with the construction of the code.
Hint.

Activity 8.15.2.

Robots will naturally deplete their charge as they carry out tasks. Write a function called chargeRobot which takes a Robot as a parameter and charges the robot to 100 percent. Then output the statement “Robot name is fully charged!”. Use the lines to construct the code, then go back to complete the Activecode.

5.

In case a robot malfunctions, let’s write the function resetRobot. resetRobot takes a Robot as a parameter and resets its name to “EnterAName”, recharges the battery to 100 percent, and resets the task to “Idle”.
Solution.
Below is one way to implement the program. We can create another Robot with the settings after being reset. Then we set r equal to the new Robot we created. Notice we use dot notation to ensure that the model and serialNumber are the same.
#include <iostream>
using namespace std;

struct Robot {
    string name;
    string model;
    int serialNumber;
    int batteryLevelPercentage;
    string task;
};

void printRobotData (Robot r);

void resetRobot(Robot& r) {
    Robot reset = { "EnterAName", r.model, r.serialNumber, 100, "Idle" };
    r = reset;
}

int main() {
    Robot a = { "Bot", "RSO", 1985, 32, "gardening" };
    resetRobot(a);
    cout << "Your output:" << endl;
    printRobotData (a);
    cout << "Correct output:" << endl;
    cout << "EnterAName (RSO 1985) has 100 percent battery and is currently executing the task \"Idle\"";
}

6.

Write the Pokemon structure, which has instance variables string pokeName, string type, int level, and int healthPercentage in that order. Next, write the function printPokeInfo, which takes a Pokemon as a parameter and outputs the Pokemon’s info in the following format: pokeName (Lv. level, healthPercentage% HP). Check the hint below for help with the construction of the code.
Hint.

Activity 8.15.3.

Write the Pokemon structure, which has instance variables string pokeName, string type, int level, and int healthPercentage in that order. Next, write the function printPokeInfo, which takes a Pokemon as a parameter and outputs the Pokemon’s info in the following format: pokeName (Lv. level , healthPercentage% HP). Use the lines to construct the code, then go back to complete the Activecode.

7.

Now write the Trainer structure, which has instance variables string trainerName, char gender, int numBadges, and six Pokemon objects named first, second, etc., in that order. Then, write the function printTrainerInfo, which takes a Trainer as a parameter and outputs the trainer’s info. For example, the code below should print:
Solution.
Below is one way to implement the program. First we declare the instance variables in the struct definition. Next, we call printPokeInfo on each Pokemon in Trainer and output the trainer’s info in the correct format.
#include <iostream>
using namespace std;

struct Pokemon {
    string pokeName;
    string type;
    int level;
    int healthPercentage;
};

struct Trainer {
    string trainerName;
    char gender;
    int numBadges;
    Pokemon first, second, third, fourth, fifth, sixth;
};

void printPokeInfo(Pokemon p);

void printTrainerInfo(Trainer t) {
    cout << "Trainer " << t.trainerName << " has " << t.numBadges
         << " badges and " << t.trainerName << "'s team consists of " << endl;
    printPokeInfo(t.first);
    printPokeInfo(t.second);
    printPokeInfo(t.third);
    printPokeInfo(t.fourth);
    printPokeInfo(t.fifth);
    printPokeInfo(t.sixth);
}

int main() {
    Pokemon pikachu = { "Pikachu", "Electric", 81, 100 };
    Pokemon espeon = { "Espeon", "Psychic", 72, 100 };
    Pokemon snorlax = { "Snorlax", "Normal", 75, 100 };
    Pokemon venusaur = { "Venusaur", "Grass & Poison", 77, 100 };
    Pokemon charizard = { "Charizard", "Fire & Flying", 77, 100 };
    Pokemon blastoise = { "Blastoise", "Water", 77, 100 };
    Trainer red = { "Red", 'M', 8, pikachu, espeon, snorlax, venusaur, charizard, blastoise };
    printTrainerInfo(red);
}

8.

When Pokemon are injured, they can be healed up at the Pokemon Center. Write the function healPokemon, which takes a Trainer as a parameter and heals the Trainer’s Pokemon to 100 percent health. Check the hint below for help with the construction of the code.
Hint.

Activity 8.15.4.

When Pokemon are injured, they can be healed up at the Pokemon Center. Write the function healPokemon, which takes a Trainer as a parameter and heals the Trainer’s Pokemon to 100 percent health. Use the lines to construct the code, then go back to complete the Activecode.

9.

Now write the function pokeCenter which takes a Trainer as a parameter and prompts the user if they’d like to heal their Pokemon. Below are the possible outputs (y, n, or an invalid input). If user inputs ‘y’, call healPokemon and output the correct dialogue. If user inputs ‘n’, don’t call healPokemon and output the correct dialogue. If user inputs an invalid character, output the error message.
Solution.
Below is one way to implement the program. We use conditionals to perform the correct output and operation depending on the user’s input.
#include <iostream>
using namespace std;

struct Pokemon {
    string pokeName;
    string type;
    int level;
    int healthPercentage;
};

struct Trainer {
    string trainerName;
    char gender;
    int numBadges;
    Pokemon first, second, third, fourth, fifth, sixth;
};

void printPokeInfo(Pokemon p);
void printTrainerInfo(Trainer t);
void healPokemon(Trainer& t);

void pokeCenter(Trainer& t) {
    char response;
    cout << "Welcome to the Pokémon Center. Would you like me to take your Pokémon? (y/n) ";
    cin >> response;
    if (response == 'y') {
        cout << "Okay, I'll take your Pokémon for a few seconds." << endl;
        healPokemon(t);
        cout << "Your Pokémon are now healed. We hope to see you again." << endl;
    }
    else if (response == 'n') {
        cout << "We hope to see you again." << endl;
    }
    else {
        cout << "Sorry, not a valid input." << endl;
    }
}

int main() {
    Pokemon exeggutor = {"Exeggutor", "Grass & Psychic", 58, 78};
    Pokemon alakazam = {"Alakazam", "Psychic", 54, 0};
    Pokemon arcanine = {"Arcanine", "Fire", 58, 24};
    Pokemon rhydon = {"Rhydon", "Ground & Rock", 56, 55};
    Pokemon gyarados = {"Gyarados", "Water & Flying", 58, 100};
    Pokemon pidgeot = {"Pidgeot", "Normal & Flying", 56, 35};
    Trainer blue = {"Blue", 'M', 8, exeggutor, alakazam, arcanine, rhydon, gyarados, pidgeot};
    printTrainerInfo(blue);
    pokeCenter(blue);
    printTrainerInfo(blue);  // Pokemon should now all be healed to 100% health
}

10.

Ever wanted to know how much you’d weigh on each planet? Write the convertWeight function, which takes a double earthWeight and int planet as parameters. First, in main, prompt the user to enter their weight in pounds and a number corresponding to a planet (Mercury is 1, Venus is 2, etc.). Next, call the convertWeight function using the user’s input. Finally, print out their weight on that planet. If the user inputs an invalid planet, print out an error message. The weight conversion are as follows (multiply the number by earthWeight to get the weight on that planet): Mercury - 0.38, Venus - 0.91, Earth - 1.00, Mars - 0.38, Jupiter - 2.34, Saturn - 1.06, Uranus - 0.92, and Neptune - 1.19. Check the hint below for help with the construction of the code. Below are some examples.
Please enter your weight in pounds: 145.6
Please select a planet: 3
Your weight on Earth is 145.6 pounds.

or

Please enter your weight in pounds: 170
Please select a planet: 1
Your weight on Mercury is 64.6 pounds.

or

Please enter your weight in pounds: 170
Please select a planet: 23
Error, not a valid planet.
Hint.

Activity 8.15.5.

Ever wanted to know how much you’d weigh on each planet? Write the convertWeight function, which takes a double earthWeight and int planet as parameters. First, in main, prompt the user to enter their weight in pounds and a number corresponding to a planet (Mercury is 1, Venus is 2, etc.). Next, call the convertWeight function using the user’s input. Finally, print out their weight on that planet. If the user inputs an invalid planet, print out an error message. The weight conversion are as follows (multiply the number by earthWeight to get the weight on that planet): Mercury - 0.38, Venus - 0.91, Earth - 1.00, Mars - 0.38, Jupiter - 2.34, Saturn - 1.06, Uranus - 0.92, and Neptune - 1.19. Use the lines to construct the code, then go back to complete the Activecode. Below are some examples.
Please enter your weight in pounds: 145.6
  Please select a planet: 3
  Your weight on Earth is 145.6 pounds.

  or

  Please enter your weight in pounds: 170
  Please select a planet: 1
  Your weight on Mercury is 64.6 pounds.

  or

  Please enter your weight in pounds: 170
  Please select a planet: 23
  Error, not a valid planet.
You have attempted 1 of 16 activities on this page.