C++ Primer Plus Chapter 4 Exercise 9

c plus plusExercise 9 is a remake of exercise 6, a common theme in this chapter. Only a few things need to be swapped in order to meet the requirements.  We initially declare a single structure candyBar, then we create a dynamic array candyBar[3].  *bar points to the first element of candyBar[3], and we can access candyBar by calling bar. Here is my solution:

Do Programming Exercise 6, but, instead of declaring an array of three CandyBar structures,
use new to allocate the array dynamically.

#include <iostream>
#include <string>

using namespace std;

// Candy bar structure
struct candyBar
{
string brand;
double weight;
int calories;
};

int main()
{
// create three members, but use new to allocate
candyBar * bar = new candyBar[3];

bar[0].brand = "Crunch";
bar[0].weight = 1.7;
bar[0].calories = 275;

bar[1].brand = "Heath";
bar[1].weight = 2.3;
bar[1].calories = 400;

bar[2].brand = "Rolo";
bar[2].weight = 2.5;
bar[2].calories = 350;

// Ouput bars
cout << "The first bar variable holds: \n";
cout << bar[0].brand << "\n";
cout << bar[0].weight << " ounces \n";
cout << bar[0].calories << " calories \n";
cout << endl;

cout << "The second bar variable holds: \n";
cout << bar[1].brand << "\n";
cout << bar[1].weight << " ounces \n";
cout << bar[1].calories << " calories \n";
cout << endl;

cout << "The third bar variable holds: \n";
cout << bar[2].brand << "\n";
cout << bar[2].weight << " ounces \n";
cout << bar[2].calories << " calories \n";

delete [] bar; // free memory
cin.get();
return 0;
}

C++ Primer Plus Chapter 4 Exercise 8

c plus plus

Exercise 8 took a little finagling to make it ask for diameter first while outputting it second in order as the last program, without skipping over the name input. If you use some other methods for pointing to structs at the diameter input, you will see what I mean. I provided a few different methods of pointing to structs in this exercise. The “new” keyword was used as per directions to allocate memory for our structure. Alas, here is my solution:

Do Programming Exercise 7, but use new to allocate a structure instead of declaring a
structure variable. Also, have the program request the pizza diameter before it requests
the pizza company name.

#include <iostream>
#include <string>

using namespace std;

// pizza struct
struct pizza
{
string pizzaCompanyName;
int pizzaDiameter;
int pizzaWeight;
};

int main()
{

// "New" keyword used to allocate memory for the structure
pizza * pie = new pizza;

// Gather info
cout << "Enter the diameter of the pizza in inches: ";
(cin >> pie->pizzaDiameter).get(); // manipulate cin
cout << "Enter the name of the Pizza Company: ";
getline(cin, pie->pizzaCompanyName);
cout << "Enter the weight of the pizza in ounces: ";
cin >> (*pie).pizzaWeight; // Another method of pointing to a structure
cout << "\n";

// Output info
cout << "The pizza company name is: " << pie->pizzaCompanyName << endl;
cout << "The Diameter inches is: " << pie->pizzaDiameter << endl;
cout << "The weight in ounces is: " << pie->pizzaWeight << endl;

// Free memory used by our structure, important.
delete pie;

cin.get();
return 0;
}

C++ Primer Plus Chapter 4 Exercise 7

c plus plusExercise 7 is fairly straightforward. We are constructing another data structure modeled after a pizza. The only difference here is that we are making the structs member variables instead of hard coding them. Here is my solution:

William Wingate runs a pizza-analysis service. For each pizza, he needs to record the following
information:
• The name of the pizza company, which can consist of more than one word
• The diameter of the pizza
• The weight of the pizza
Devise a structure that can hold this information and write a program that uses a structure
variable of that type. The program should ask the user to enter each of the preceding
items of information, and then the program should display that information. Use cin
(or its methods) and cout.

#include <iostream>
#include <string>

using namespace std;

// pizza struct
struct pizza
{
string pizzaCompanyName;
int pizzaDiameter;
int pizzaWeight;
};

int main()
{

pizza pie = {pie.pizzaCompanyName, pie.pizzaDiameter, pie.pizzaWeight};

// Gather info
cout << "Enter the name of the Pizza Company: ";
getline(cin, pie.pizzaCompanyName);
cout << "Enter the diameter of the pizza in inches: ";
cin >> pie.pizzaDiameter;
cout << "Enter the weight of the pizza in ounces: ";
cin >> pie.pizzaWeight;
cout << "\n\n";

// Output info
cout << "The pizza company name is: " << pie.pizzaCompanyName << endl;
cout << "The Diameter inches is: " << pie.pizzaDiameter << endl;
cout << "The weight in ounces is: " << pie.pizzaWeight << endl;

cin.get();
return 0;
}

C++ Primer Plus Chapter 4 Exercise 6

c plus plusFor exercise six we can copy and paste our previous code and simply make some minor adjustments to the source to complete exercise six. This time we declare our snack variable as an array of three, and initialize the member within braces. I went with my three favorite candy bars fir this one 🙂 I think the goal of this exercise was to show that we can have either one thing with relevant variables or we can create structs with many relevant member search their own variables. Here is my solution:

6. The CandyBar structure contains three members, as described in Programming Exercise
5. Write a program that creates an array of three CandyBar structures, initializes them to
values of your choice, and then displays the contents of each structure.

#include <iostream>
#include <string>

using namespace std;

// structure
struct candyBar
{
string brand;
double weight;
int calories;
};

int main()
{
// create three members to our struct
candyBar bar[3] =
{
{"Crunch",1.7,275},
{"Heath",2.3,400},
{"Rolo",2.5,350}
};

cout << "The first bar variable holds: \n";
cout << bar[0].brand << "\n";
cout << bar[0].weight << " ounces \n";
cout << bar[0].calories << " calories \n";
cout << endl;

cout << "The second bar variable holds: \n";
cout << bar[1].brand << "\n";
cout << bar[1].weight << " ounces \n";
cout << bar[1].calories << " calories \n";
cout << endl;

cout << "The third bar variable holds: \n";
cout << bar[2].brand << "\n";
cout << bar[2].weight << " ounces \n";
cout << bar[2].calories << " calories \n";

cin.get();
return 0;
}

C++ Primer Plus Chapter 4 Exercise 5

c plus plusExercise five requires us to make a basic struct. Structs are useful for when you want to hold relevant information about an object. With structs we are getting closer to OOP programming.  Here is my solution to the problem:

5. The CandyBar structure contains three members. The first member holds the brand
name of a candy bar. The second member holds the weight (which may have a fractional
part) of the candy bar, and the third member holds the number of calories (an integer
value) in the candy bar. Write a program that declares such a structure and creates a
CandyBar variable called snack, initializing its members to “Mocha Munch”, 2.3, and
350, respectively. The initialization should be part of the declaration for snack. Finally,
the program should display the contents of the snack variable.

#include <iostream>
#include <string>

using namespace std;

struct candyBar
{
string brand;
float weight;
int calories;
};

int main()
{
candyBar snack = {"Mocha Munch", 2.3, 350};
cout << "The snack variable holds: \n";
cout << snack.brand << "\n";
cout << snack.weight << " ounces \n";
cout << snack.calories << " calories \n";

cin.get();
return 0;
}

C++ Primer Plus Chapter 4 Exercise 4

c plus plusWith some minor adjustments, we can use the C++ string class to accomplish our goal.  We will use the C++ member function ‘append’ from the string class. My solution if fairly clean and simple. Here is the source:

4. Write a program that asks the user to enter his or her first name and then last name, and
that then constructs, stores, and displays a third string consisting of the user’s last name
174 C++ PRIMER PLUS, FIFTH EDITION
followed by a comma, a space, and first name. Use string objects and methods from the
string header file. A sample run could look like this:
Enter your first name: Flip
Enter your last name: Fleming
Here’s the information in a single string: Fleming, Flip

#include <iostream>
#include <string>

using namespace std;

int main()
{
string firstName;
string lastName;
string str;

// Gather input, could use cin.getline here.
cout << "Enter your first name: ";
cin >> firstName;
cin.ignore();
cout << "Enter your last name: ";
cin >> lastName;

// Using C++ string member functions
str.append(lastName);
str.append(" , ");
str.append(firstName);

cout << "Here's the information in a single string: " << str << endl;

cin.get();
return 0;
}

C++ Primer Plus Chapter 4 Exercise 3

c plus plusExercise 3 of chapter 4 wants us to do some specific things with cstrings. We can use strcpy and strcat member functions from the cstring class to make our third string adhere to the requirements.  Here is my solution :

3. Write a program that asks the user to enter his or her first name and then last name, and
that then constructs, stores, and displays a third string, consisting of the user’s last name
followed by a comma, a space, and first name. Use char arrays and functions from the
cstring header file. A sample run could look like this:
Enter your first name: Flip
Enter your last name: Fleming
Here’s the information in a single string: Fleming, Flip

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main()
{
char firstName[20];
char lastName[20];
char str[50];

// Gather input
cout << "Enter your first name: ";
cin >> firstName;
cin.ignore();
cout << "Enter your last name: ";
cin >> lastName;

// C string member functions
strcpy_s(str, lastName);
strcat_s(str, " , ");
strcat_s(str, firstName);

cout << "Here's the information in a single string: " << str << endl;

cin.get();
return 0;
}

C++ Primer Plus Chapter 4 Exercise 2

c plus plusExercise 2 requires us to make some minor adjustments to allow for the C++ string class.  By simply deleting any reference to an array and adjusting our getline statement, we have listing 4-4 working for the C++ string class:

2. Rewrite Listing 4.4, using the C++ string class instead of char arrays.

#include <iostream>
#include <string>

using namespace std;

int main()
 {
 string name;
 string dessert;

cout << "Enter your name: ";
 getline(cin, name);

cout << "Enter your favorite dessert: ";
 getline(cin, dessert);

cout << "I have some delicious " << dessert
 << " for you, " << name << endl;

return 0;
 }

C++ Primer Plus Chapter 4 Exercise 1

c plus plusThe problem with this exercise is that there isn’t really way to complete it without using a method that you have not yet learned in the book. In saying that, there certainly are a few other ways to do this exercise including switch statements and incrementing the ASCII value of a letter grade. But if you are going chapter by chapter in the book, you will not have learned how to do that. I did use cin.getline to store the input sequence to firstName[], allowing for multiple first-names as required.  I posted a simple solution that works for our purposes, and acts as an intro to if statements. Take a look:

1. Write a C++ program that requests and displays information as shown in the following example of output:
What is your first name? Betty Sue
What is your last name? Yew
What letter grade do you deserve? B
What is your age? 22
Name: Yew, Betty Sue
Grade: C
Age: 22
Note that the program should be able to accept first names that comprise more than one word. Also note that the program adjusts the grade downward—that is, up one letter. Assume that the user requests an A, a B, or a C so that you don’t have to worry about the gap between a D and an F.

#include <iostream>

using namespace std;

int main()
{
char firstName[20];
char lastName[20];
char grade;
char newGrade;
int age;

// Gather input
cout << "What is your first name? ";
cin.getline(firstName, 20);
cout << "What is your last name? ";
cin >> lastName;
cout << "What is the letter grade you deserve? ";
cin >> grade;
cout << "What is your age? ";
cin >> age;

// Increment grade and recognize upper and lowercase input.
if (grade == 'A' || grade == 'a')
{
newGrade = 'B';
}
else if (grade == 'B' || grade == 'b')
{
newGrade = 'C';
}
else if (grade == 'C' || grade == 'c')
{
newGrade = 'D';
}

cout << "name: " << firstName << " " << lastName << endl;
cout << "grade: " << char (newGrade) << endl;
cout << "age: " << age << endl;

cin.get();
return 0;
}

C++ Primer Plus Chapter 3 Exercise 6

c plus plusThis one could have been harder than it was, but I happen to know the magic number to make this easy, 235.  Here is why 235 is the magic number:

US MPG = 100/E [km/L] x 0.621 [mi/km] x 3.785 [L/US gal] = 235 ÷ E

Where E is Liters per 100km. My solution to exercise 6 is below:

6. Write a program that asks you to enter an automobile gasoline consumption figure in the
European style (liters per 100 kilometers) and converts to the U.S. style of miles per gallon.
Note that in addition to using different units of measurement, the U.S approach
(distance / fuel) is the inverse of the European approach (fuel / distance). Note that 100
kilometers is 62.14 miles, and 1 gallon is 3.875 liters. Thus, 19 mpg is about 12.4 l/100
km, and 27 mpg is about 8.7 l/100 km.

#include <iostream>

using namespace std;

int main()
{
float liters;
int mpg;

cout << "Enter the number of European liters per 100 kilometers to convert: ";
cin >> liters;

// Convert to US mpg
mpg = 235 / liters;
cout << liters << " liters " << " is equal to " <<  mpg << " miles per gallon " << endl;

cin.get();
return 0;
}