Pages

Friday, 1 July 2016

Chapter 4 Drill // 4.1 + 4.2 + 4.3 + 4.4 - 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.


4.1 - Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.

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



int main()
{
int one;
int two;

cout << "Please enter two integers: \n";


while (cin >> one >> two)
cout << one << '\n' << two << '\n' << "\nPlease enter two integers: \n";

keep_window_open();

return 0;
}

I'll be honest. At first this through me for a loop (pun intended), and searching the internet it seemed to throw other new users for loop because instead of actually just pressing '|' and hitting enter to close the program I thought he meant to create code that when '|' was entered the program would end....I know I'll wear my dunce hat. However I didn't actually know that '|' would terminate a program if pressed. Sometimes I wish Bjarne would make his instructions clearer.

4.2 - Change the program to write out 'the smaller value is: ' followed by the smaller of the numbers and 'the larger value is: ' followed by the larger value.


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


int main()
{
int one;
int two;

cout << "Please enter two integers: \n";


while (cin >> one >> two)

{
if (one > two)
{
cout << "\nThe smaller value is: " << two << endl;
cout << "\nThe larger value is : " << one << endl;
}
else
{
cout << "\nThe smaller value is: " << one << endl;
cout << "\nThe larger value is : " << two << endl;
}

cout << "\nPlease enter two integers: \n";

}

}

keep_window_open();

return 0;

}

4.3 - Augment the program so that it writes the line 'the numbers are equal ' (only) if they are equal.

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


int main()
{
int one;
int two;

cout << "Please enter two integers: \n";


while (cin >> one >> two)

{
if (one > two)
{
cout << "\nThe smaller value is: " << two << endl;
cout << "\nThe larger value is : " << one << endl;
}
else if (one < two)
{
cout << "\nThe smaller value is: " << one << endl;
cout << "\nThe larger value is : " << two << endl;
}
else
cout << "\nThe numbers are equal." << endl;

cout << "\nPlease enter two integers: \n";

}

}

keep_window_open();

return 0;

}

4.4 - Change the program so it uses doubles instead of ints.

I'm not going to bother showing code for this one because you simply just replace 'int' with 'double'. That's it.

No comments:

Post a Comment