C++ Primer Plus Chapter 7 Exercise 1

c plus plusChapter 7 kicks off with a fairly painless reintroduction into functions. We computer harmonic mean for a number pair. There are probably a few ways to do this, but they should all be very similar. Take in two numbers, store them if you like as I did, check if they are zero’s, and if not compute the harmonic mean by way of a function. Check out my source below:

1. Write a program that repeatedly asks the user to enter pairs of numbers until at least one
of the pair is 0. For each pair, the program should use a function to calculate the har-
monic mean of the numbers. The function should return the answer to main(), which
should report the result. The harmonic mean of the numbers is the inverse of the aver-
age of the inverses and can be calculated as follows:
harmonic mean = 2.0 × x × y / (x + y)

#include <iostream>

using namespace std;

float Hmean(int x, int y);

int main()
int myArray[2];

cout << "Please enter pairs of numbers: " << endl;
cin >> myArray[0] >> myArray[1];

if(myArray[0] == 0 || myArray[1] == 0)
cout << "You have entered a pair matching zero" << endl;
cout << "Exiting..." << endl;
cout << "The Harmonic mean of " << myArray[0] << " and "
<< myArray[1] << " is " << Hmean(myArray[0],myArray[1]);
return 0;

float Hmean(int x, int y)
float calc = 2.0 * x * y / (x + y);

return calc;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s