Monday, 15 August 2016

Chapter 5 // Exercise 7 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 5 // Exercise 7

Quadratic equations are of the form:

 To solve these, one uses the quadratic formula:

There is a problem though: is b(2)-4ac is less than zero, then it will fail. Write a program that can calculate x for a quadratic equation. Create a function that prints out the roots of a quadratic equations, given a, b, c. When the program detects an equations with no real roots, have it print out a message. How do you know that your results are plausible? Can you check that they are correct?

Ok, in chapter 4, exercise 18 I already covered this and converted negative numbers into "imaginary numbers" ie. I made them positive since you can't square root a negative. I guess here, he just wants us to display a message when the number is negative instead of changing it.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

double a;
double b;
double c;

double get_xPos()
{
double x = ((-b + sqrt((b*b) - (4 * a*c))) / (2 * a));

if ((b*b) - (4 * a*c) < 0)
{
cout << b << "*" << b << "-4*" << a << "*" << c << "= " << ((b*b) - (4 * a*c)) << '\n';
error("This is a negative number and cannot be rooted.\n");
}
return x;
}

double get_xNeg()
{
double x = ((-b - sqrt((b*b) - (4 * a*c))) / (2 * a));

if ((b*b) - (4 * a*c) < 0) 
{
cout << b << "*" << b << "-4*" << a << "*" << c << "= " << ((b*b) - (4 * a*c)) << '\n';
error("This is a negative number and cannot be rooted.\n");
}
return x;
}

int main()
try
{
cout << "Let's solve some quadratic equations.\n";
cout << "What is a?: \n";
cin >> a;
cout << "What is b?: \n";
cin >> b;
cout << "What is c?: \n";
cin >> c;

double x1 = get_xPos();
double x2 = get_xNeg();

cout << "\nX is: " << x1 << " and " << x2 << "\n";

cout << '\n';
keep_window_open();

return 0;
}


catch (exception& e)
{
cerr << "Error: " << e.what() << '\n';
keep_window_open();
return 1;

}

You can check to see if your results are plausible by plotting x1 and x2 on a graph. They should intersect with the x axis creating a curve. If they don't intersect the x axis, you are using imaginary numbers.

Saturday, 13 August 2016

Chapter 5 // Exercise 2, 3, 4, 5, 6 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 5 // Exercise 2

The following program takes in a temperature value in Celsius and converts it to kelvin. This code has many errors in it. Find the errors, list them and correct the code.

double ctok(double c)
{
int k = c + 273.15;
return int
}

int main()
{
double c = 0;
cin >> d;
double k = ctok("c");
Cout << k << '\n';
}

1. return int has no ;
2. return has nothing to return
3. int k will truncate floating point
3. 'd' is unidentified
4. trying to convert "c" string to a double
5. capital C on cout
6. return 0 missing on int main

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

double ctok(double c)
{
double k = c + 273.15;
return k;
}

int main()
{
double c = 0;
cin >> c;
double k = ctok(c);
cout << k << '\n';

keep_window_open();

return 0;

}

Chapter 5 // Exercise 3

Absolute zero is the lowest temperature that can be reached; it is -273.15C, or 0K. The above program, even when corrected, will produce erroneus results when given a temperature below this. Place a check in the main program that will produce an error is a temperature is given below -273.15C.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

double ctok(double c)
{
double k = c + 273.15;
return k;
}

int main()
try
{
double c = 0;
cin >> c;

if (c < -273.15)
error("This is below absolute zero.");

double k = ctok(c);
cout << k << '\n';

keep_window_open();

return 0;
}

catch (exception& e)
{
cerr << "Error: " << e.what() << '\n';
keep_window_open();
return 1;

}

Chapter 5 // Exercise 4

Do exercise 3 again, but this time handle the error inside ctok().

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

double ctok(double c)
{
double k = c + 273.15;
if (c < -273.15)
error("This is below absolute zero.");
return k;
}

int main()
try
{
double c = 0;
cin >> c;
double k = ctok(c);
cout << k << '\n';

keep_window_open();

return 0;
}

catch (exception& e)
{
cerr << "Error: " << e.what() << '\n';
keep_window_open();
return 1;

}

Chapter 5 // Exercise 5

Add to the program so that it can also convert from Kelvin to Celsius.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

double ctok(double c)
{
double k = c + 273.15;
if (c < -273.15)
error("This is below absolute zero.");
return k;
}

double kToC(double c)
{
double k = c - 273.15;
if (c < 0)
error("This is below absolute zero.");
return k;
}

char getkc()
{
char t;
cin >> t;
if (t != 'k' && t != 'c')
error("please use either k or c (lower case)");
return t;

}

double getTemp()
{
cout << "Enter Temperature: \n";
double c = 0;
cin >> c;
return c;
}

int main()
try
{
cout << "This converts Kelvin to Celsius and vice versa.\n";
cout << "What do you want to convert? k or c: \n";
char temp = getkc();

switch (temp)
{
case 'k':
{
double k = getTemp();
k = kToC(k);
cout << k << '\n';
break;
}

case 'c':
{
double c = getTemp();
c = ctok(c);
cout << c << '\'n';
break;
}
}

keep_window_open();

return 0;
}

catch (exception& e)
{
cerr << "Error: " << e.what() << '\n';
keep_window_open();
return 1;

}


Chapter 5 // Exercise 6

Write a program that converts from Celsius to Fahrenheit and from Fahrenheit to Celsius. Use estimation to see if your results are plausible.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

double cToF(double t)
{
double c = ((t * (9.0/5.0)) + 32);
return c;
}

double fToC(double t)
{
double f = ((t - 32) * (5.0/9.0));
return f;
}

char getfc()
{
char t;
cin >> t;
if (t != 'f' && t != 'c')
error("please use either f or c (lower case)");
return t;

}

double getTemp()
{
cout << "Enter Temperature: \n";
double c = 0;
cin >> c;
return c;
}

int main()
try
{
cout << "This converts Fahrenheit to Celsius and vice versa.\n";
cout << "What do you want to convert? f or c: \n";
char temp = getfc();

switch (temp)
{
case 'f':
{
double f = getTemp();
f = fToC(f);
cout << f << '\n';
break;
}

case 'c':
{
double c = getTemp();
c = cToF(c);
cout << c << '\n';
break;
}
}

keep_window_open();

return 0;
}

catch (exception& e)
{
cerr << "Error: " << e.what() << '\n';
keep_window_open();
return 1;

}

Thursday, 11 August 2016

Chapter 4 // Exercise 19, 20, 21 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 4 Exercise // 4.19

Write a program where you first enter a set if name-and-value pairs, such as Joe 17 and Barbara 22. For each pair, add the name to a vector called names and the  number to a vector called scores (in corresponding positions, so that if names[7]=="Joe" then scores[7]=="17"). Terminate input with NoName 0. Check that each name is unique and terminate with an error message if a name is entered twice. Write out all the (name,score) pairs, one per line.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

int main()
{
vector<string> names;
vector<int> scores;

string inputName;
int inputScores;
char loop = 'y';

cout << "Please enter a name followed by the score. To stop input enter 'NoName' in name and 0 in scores.\n";

//get names and scores
while (loop == 'y')
{
cout << "Name: ";
cin >> inputName;
cout << "Score: ";
cin >> inputScores;

for (int i = 0; i < names.size(); ++i)
{
if (names[i] == inputName)
{
cout << "Sorry, that name has already been entered. Please Re-Name it: \n" << endl;
cin >> inputName;
}
}

if (inputName == "NoName" && inputScores == 0)
{
loop = 'n';
}

names.push_back(inputName);
scores.push_back(inputScores);
}

cout << '\n';

//print them out
for (int x = 0; x < names.size()-1; ++x)
{
cout << names[x] << '\t' << scores[x] << '\n';
}

keep_window_open();

return 0;
}


Chapter 4 Exercise // 4.20

Modify the program from exercise 19 so that when you enter a name, the program will output the corresponding score or name not found.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

int main()
{
vector<string> names;
vector<int> scores;

string inputName;
int inputScores;
char loop = 'y';

cout << "Please enter a name followed by the score. To stop input enter 'NoName' in name and 0 in scores.\n";

//get names and scores
while (loop == 'y')
{
cout << "Name: ";
cin >> inputName;
cout << "Score: ";
cin >> inputScores;

for (int i = 0; i < names.size(); ++i)
{
if (names[i] == inputName)
{
cout << "Sorry, that name has already been entered. Please Re-Name it: \n" << endl;
cin >> inputName;
}
}

if (inputName == "NoName" && inputScores == 0)
{
loop = 'n';
}

names.push_back(inputName);
scores.push_back(inputScores);
}

cout << '\n';

string findName;
loop = 'y';
char nameFound = 's';

while (loop == 'y')
{
cout << "Whose score do you want to find?: \n";
cin >> findName;

for (int x = 0; x < names.size() - 1; ++x)
{
if (names[x] == findName)
{
cout << names[x] << '\t' << scores[x] << '\n';
nameFound = 'y';
}
}

loop = 'n';

if (nameFound != 'y')
{
cout << "Sorry, name not found. Do you what to try again? y/n: \n";
cin >> loop;
}

}

keep_window_open();

return 0;
}



Chapter 4 Exercise // 4.21

Modify the program from exercise 19 so that when you enter an integer, the program will output all the names with that score or score not found.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

int main()
{
vector<string> names;
vector<int> scores;

string inputName;
int inputScores;
char loop = 'y';

cout << "Please enter a name followed by the score. To stop input enter 'NoName' in name and 0 in scores.\n";

//get names and scores
while (loop == 'y')
{
cout << "Name: ";
cin >> inputName;
cout << "Score: ";
cin >> inputScores;

for (int i = 0; i < names.size(); ++i)
{
if (names[i] == inputName)
{
cout << "Sorry, that name has already been entered. Please Re-Name it: \n" << endl;
cin >> inputName;
}
}

if (inputName == "NoName" && inputScores == 0)
{
loop = 'n';
}

names.push_back(inputName);
scores.push_back(inputScores);
}

cout << '\n';

int findScore;
loop = 'y';
char scoreFound = 's';

while (loop == 'y')
{
cout << "Please enter a score to find: \n";
cin >> findScore;

for (int x = 0; x < scores.size() - 1; ++x)
{
if (scores[x] == findScore)
{
cout << names[x] << '\t' << scores[x] << '\n';
scoreFound = 'y';
}
}

loop = 'n';

if ( scoreFound != 'y')
{
cout << "Sorry, no scores found. Do you what to try again? y/n: \n";
cin >> loop;
}

}

keep_window_open();

return 0;
}

And so the chapter 4 exercises were rounded out by some nice easy questions. I'll be honest, when I first read them I honestly didn't think I'd be able to solve them. I just thought they were too hard and impossible to do at my level. When I started exercise 1 I still didn't understand vectors all that well or loops. I didn't even know how to print a vector or compare them, now I can do all those things. It's taken me around 2 months to fully work through this chapter but I work full time and some of these exercises would take me around 6 hours to solve.

It feels good though,when you do solve them. And it's amazing to see just how far I've come in 2 months.

Tuesday, 9 August 2016

Chapter 4 // Exercise 18 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 4 Exercise // 4.18

Write a program to solve quadratic equations. A quadratic equation is of the form:



Use doubles for the user inputs for a, b and c. Since there are two solutions to a quadratic equation, output both x1 and x2.

For those of you (like me) who haven't touched the quadratic formula in almost ten years, I found this site useful as a refresher.


#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

double get_xPos();
double get_xNeg();
double a;
double b;
double c;

int main()
{
cout << "Let's solve some quadratic equations.\n";
cout << "What is a?: \n";
cin >> a;
cout << "What is b?: \n";
cin >> b;
cout << "What is c?: \n";
cin >> c;

double x1 = get_xPos();
double x2 = get_xNeg();

cout << "\nX is: " << x1 << " and " << x2 << "\n";

cout << '\n';
keep_window_open();

return 0;
}

double get_xPos() 
{
double x = ((-b + sqrt((b*b) - (4 *a*c))) / (2 * a));

if ((b*b) - (4 *a*c) < 0) //cannot square root negative, this turns it to positive
{
double q = ((b*b) - (4 * a*c))*-1;
x = (-b + sqrt(q))/(2*a);
}

return x;
}

double get_xNeg()
{
double x = ((-b - sqrt((b*b) - (4 *a*c))) / (2 * a));

if ((b*b) - (4 *a*c) < 0) //cannot square root negative, this turns it to positive
{
double q = ((b*b) - (4 * a*c))*-1;
x = (-b - sqrt(q)) / (2 * a);
}

return x;

}


Ok, I found this one really easy however Bjarne doesn't mention if he wants us to include imaginary numbers. For example you can't square root a negative number, so I created an if statement which changes it to a positive and then continues. It may give a different answer but otherwise it just kept showing invalid.

I also created separate functions for this one as I'm trying to get into the habit of removing as much as possible from int main. Here, I just forward declare the functions as the beginning by ending the function with a ';'. The computer then knows to look elsewhere for the declaration