C++ Primer Plus Chapter 6 Exercise 1

c plus plusChapter 6 brings us to branching statements, also know as if and else statements.  We are also introduced to the cctype library which makes light work of some basic character operations. Exercise 1 ask us to accept keyboard input to @, not to display numbers, convert uppercase to lowercase and vice versa. One other thing you will notice this time is I have not pulled in the entire standard library, I except use it in a case by case basis. This can help solve non-obvious ambiguity errors in our later problems. See my source below for a simple solution:

1. Write a program that reads keyboard input to the @ symbol and that echoes the input
except for digits, converting each uppercase character to lowercase, and vice versa.
(Don’t forget the cctype family.)

#include <iostream>
#include <cctype>

int main()
{
char ch;

std::cout << "Enter your characters: ";

while(std::cin.get(ch) && ch != '@') // While inputting and not an '@'
{
if(isdigit(ch))
continue; // Ignore digits
if(isalpha(ch)) // Is it in the alphabet?
if(islower(ch))
std::cout << char(toupper(ch));
else
std::cout << char(tolower(ch));
else
std::cout << ch;
}
return 0;
}

C++ Primer Plus Chapter 5 Exercise 9

c plus plusThis is an interesting program that takes a second to think about. The issue here is logic.  Basically, we gather the number of rows we want and compare it in our first for statement. It’s going to be greater then zero so we enter our loop and see another for statement.  If ‘d” is still less than rows – less, we output a decimal point. we then enter out next for statement which looks at integer “a” and compares our “less” value against it. The resulting number is how many asterisk are outputted after out decimal points. We then increment “less” until we reach our rows value, as checked in our first for statement.

9. Write a program using nested loops that asks the user to enter a value for the number of
rows to display. It should then display that many rows of asterisks, with one asterisk in
the first row, two in the second row, and so on. For each row, the asterisks are preceded
by the number of periods needed to make all the rows display a total number of characters
equal to the number of rows. A sample run would look like this:
Enter number of rows: 5
….*
…**
..***
.****
*****

#include <iostream>

using namespace std;

int main()
{
int rows = 0;
int less = 1;

cout << "Enter number of rows: ";
cin >> rows;

for(int i=0; i < rows; i++)
{
for(int d=0; d < (rows - less); d++)
cout << ".";
for(int a=0; a < less; a++)
cout << "*";

cout << endl;
less++;
}
return 0;
}

C++ Primer Plus Chapter 5 Exercise 8

c plus plusWith some slight modifications we can breeze through exercise 8. The instructions require us to use the natural <string> header for C++ string class objects. The key point here is that using string is simply just easier. Why you ask? Because we can now use ‘!=’  and other comparative operators to make our comparisons.  See my solution below:

8. Write a program that matches the description of the program in Programming Exercise 7, but use a string class object instead of an array. Include the string header file and use a relational operator to make the comparison test.

#include <iostream>
#include <string>

using namespace std;

int main()
{
string input;
int words = 0;
string compare= "done";

cout << "Enter words (to stop, type the word done):" << endl;
cin >> input;

while(input != compare)
{
cin >> input;
words++;
};

cout << "You entered a total of " << words << " words " << endl;

cin.get();
return 0;
}

C++ Primer Plus Chapter 5 Exercise 7

c plus plusThe trick to exercise 7 is that we must setup and use C’s strcmp function correctly. The problem with C++ is that when using C++’s string compare functions, you are really just comparing address’s, not the string’s themselves. To get around this we use <cstring> along with strcmp() to compare to strings.  If two string arguments in strcmp() are  identical, strcmp() returns a 0. So, we look for an instance when it is not zero. You could technically still use <string> here and get a good solution, but you may run into issues in other scenarios . Here is my solution below:

7. Write a program that uses an array of char and a loop to read one word at a time until the word done is entered. The program should then report the number of words entered (not counting done). A sample run could look like this:
Enter words (to stop, type the word done): anteater birthday category dumpster envy finagle geometry done for sure You entered a total of 7 words. You should include the cstring header file and use the strcmp() function to make the comparison test.

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
char input[100];
int words = 0;
char compare[] = "done";

cout << "Enter words (to stop, type the word done):" << endl;
cin >> input;

while(strcmp(input,compare)!=0)
{
cin >> input;
words++;
};

cout << "You entered a total of " << words << " words " << endl;

cin.get();
return 0;
}

C++ Primer Plus Chapter 5 Exercise 6

c plus plusExercise 6 ask us to create a struct. We have already made structs that are very similar to this (see ch4 exercise 9). We employ the new keyword and create a point to a dynamic array. This way, we recycle the same struct, but change the data within it for different cars. See my solution below:

6. Design a structure called car that holds the following information about an automobile: its make, as a string in a character array or in a string object, and the year it was built, as an integer. Write a program that asks the user how many cars to catalog. The program should then use new to create a dynamic array of that many car structures. Next, it should prompt the user to input the make (which might consist of more than one word) and year information for each structure. Note that this requires some care because it alternates reading strings with numeric data (see Chapter 4). Finally, it should display the contents of each structure. A sample run should look something like the following:

How many cars do you wish to catalog? 2
Car #1:
Please enter the make: Hudson Hornet
Please enter the year made: 1952
Car #2:
Please enter the make: Kaiser
Please enter the year made: 1951
Here is your collection:
1952 Hudson Hornet
1951 Kaiser

#include <iostream>
#include <string>

using namespace std;

// create car struct
struct car
{
string make;
int yearBuilt;
};

int main()
{
int cars;

cout << "How many cars do you wish to catalog? ";
cin >> cars;
cout << "\n";

// create dynmaic array with new
car * dynamicArray = new car[cars];

// iterate through our dynamic array
for(int i = 0; i < cars; i++)
{
cout << "For car #" << i+1 << endl;
cout << "Please enter the make: ";
cin >> dynamicArray[i].make;
cout << "Please enter the year made: ";
cin >> dynamicArray[i].yearBuilt;
}

// output our collection
cout << "Here is what is in your collection:" << endl;
for(int i = 0; i < cars; i++)
cout << dynamicArray[i].yearBuilt << " " << dynamicArray[i].make << endl;

// clean
delete [] dynamicArray;

return 0;
}

C++ Primer Plus Chapter 5 Exercise 5

c plus plusExercise 5 is a remake of exercise 4, except this time we introduce a two dimensional array into our loops. The purpose of this is to fill it first with years then months. This way, the program will iterate through 12 months for 3 years. See the source below for the solution.

5. Do Programming Exercise 4, but use a two-dimensional array to store input for 3 years
of monthly sales. Report the total sales for each individual year and for the combined
years.

#include <iostream>
#include <string>

using namespace std;

int main()
{
string month[12] = {"January","February ","March ","April ","May","June","July","August","September","October","November","December"};
int sales[3][12];
int yearTotal;
int sum = 0;
int total = 0;
int everything = 0;

cout << "Enter sales for the month: " << endl;

for(int y = 0; y < 3; y++)
{
for(int m = 0; m < 12; m++)
{
cout << month[m] << ": ";
cin >> sales[y][m];
sum=sum+sales[y][m];
total=sum;

}

}

for(int y = 0; y < 3; y++)
{
yearTotal = 0;
for(int m =0; m < 12; m++)
{
cout << month[m] << sales[y][m] << endl;
yearTotal+=sales[y][m];
everything+=sales[y][m];
}

cout << "Sales for this year: " << yearTotal << endl;
}

cout << "The data for all years: " << everything << endl;

return 0;
}

C++ Primer Plus Chapter 5 Exercise 4

c plus plusExercise 4 wants us to loop through the months in a year and ask how many books we sold for a each month, then sum the total. I went with a string array initialized to the months. A simple for loop takes us through the year. Here is my solution:

4. You sell the book C++ for Fools. Write a program that has you enter a year’s worth of
monthly sales (in terms of number of books, not of money). The program should use a
loop to prompt you by month, using an array of char * (or an array of string objects, if
you prefer) initialized to the month strings and storing the input data in an array of int.
Then, the program should find the sum of the array contents and report the total sales
for the year.

#include <iostream>
#include <string>

using namespace std;

int main()
{
string month[12] = {"January","February ","March ","April ","May","June","July","August","September","October","November","December"};
int sales[12];
int sum = 0;

cout << "Enter sales for the month: " << endl;

for(int i = 0; i < 12; i++)
{
cout << month[i] << ": ";
cin >> sales[i];
sum=sum+sales[i];
};

cout << "Total sales for the year: " << sum << endl;

return 0;
}

C++ Primer Plus Chapter 5 Exercise 3

c plus plusIf you love word problems, then you’ll love this one. And if you hate them, well then…Exercise 3 has some wordiness you must get through in order to understand what is going on. Overall, it’s not too bad. We use a while loop to keep track of some simple interest calculations, when one is bigger then the other, we break out of the loop and display our current values.  Here is my solution:

3. Daphne invests $100 at 10% simple interest. That is, every year, the investment earns
10% of the original investment, or $10 each and every year:
interest = 0.10 × original balance
At the same time, Cleo invests $100 at 5% compound interest. That is, interest is 5% of
the current balance, including previous additions of interest:
interest = 0.05 × current balance
Cleo earns 5% of $100 the first year, giving her $105. The next year she earns 5% of
$105, or $5.25, and so on. Write a program that finds how many years it takes for the
value of Cleo’s investment to exceed the value of Daphne’s investment and then displays
the value of both investments at that time.


#include <iostream>

using namespace std;

int main()
{
int years = 1;
double DaphneInvestment = 0;
double CleoInvestment = 0;

DaphneInvestment = 100 + (100 * 0.10);
CleoInvestment = 100 + (100 * 0.05);

while(CleoInvestment < DaphneInvestment)
{
DaphneInvestment+=10; // Daphne gets 10 dollars a year.
CleoInvestment = CleoInvestment + (CleoInvestment * 0.05); // Cleo gets her investment, plus 5%
years+=1; // increment the year.
}

cout << "Daphne's investment value is: " << DaphneInvestment << endl;
cout << "Cleo's investment value is: " << CleoInvestment << endl;
cout << "It took " << years << " years for Cleo's investment to exceed Daphne's investment" << endl;

return 0;
}

C++ Primer Plus Chapter 5 Exercise 2

c plus plusExercise 2 ask us to write a loop that does not terminate until it sees a zero. A Do-While loop will best serve our interest for this exercise. The loop will sum all user inputted integers until a zero is inputted. Here is my solution:

2. Write a program that asks the user to type in numbers. After each entry, the program
should report the cumulative sum of the entries to date. The program should terminate
when the user enters 0.

#include <iostream>

using namespace std;

int main()
{
int number;
int sum = 0;

do
{
cout << "Enter numbers: ";
cin >> number;

sum = sum + number;
cout << "Current sum is: " << sum << endl;
}
while (number != 0);

return 0;
}

C++ Primer Plus Chapter 5 Exercise 1

c plus plusThe beginning of chapter 5 switches gears and finally officially introduces us to loops. Exercise 1 requires we write a loop to sum all numbers between two user supplied variables. Here is my solution:

1. Write a program that requests the user to enter two integers. The program should then
calculate and report the sum of all the integers between and including the two integers. At this point, assume that the smaller integer is entered first. For example, if the user enters 2 and 9, the program should report that the sum of all the integers from 2 through 9 is 44.

#include <iostream>;

using namespace std;

int main()
{
int a, b;
int c = 0;

cout << "Enter 1st integer, lower:" ;
cin >> a;
cout >> "Enter 2nd integer, higher: ";
cin >> b;

for(int n = a; n = b; n++)
c = c+n;

cout << "The sum of all numbers between: " << a << "and" << b << "is" << c << endl;

cin.get();
return 0;
}