473,387 Members | 1,705 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Accelerated C++: Exercise 3-2

Hi,

This is my first post here, so please be gentle. I've been studying c+
+ by mostly using the book Accelerated C++ by Andrew Koenig and
Barbara E. Moo.

So far, I've been picking things up all right, and I've come to an
exercise 3-2 that requires the following:
3-2. Write a program to compute and print the quartiles (that is, the
quarter of the numbers with the largest values, the next highest
quarter, and so on) of a set of integers.

After researching what quartiles are, and using the method defined
here: http://www.statcan.ca/english/edu/power/ch12/range.htm (as from
what I've read, there are different methods used for computing lower
and upper quartiles) I've been able to write a console program that
seems to calculate correctly. However, I would like advice, from a
programming perspective, on what I could improve.

For those who haven't read the above book, it has a unique way of
introducing C++, as the first chapter jumps straight into the use of
strings, so a lot of basics, like use of functions and so on, have not
been covered as yet.

My code is as below:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
std::cout << "Enter a range of integers followed by 'end': ";

std::vector<doubleintegerSet;

int x;
while (std::cin >x)
integerSet.push_back(x);

sort(integerSet.begin(), integerSet.end());

typedef std::vector<double>::size_type vector_Size;

vector_Size size = integerSet.size();
vector_Size mid = size / 2;
double median;
double lowerQuartile;
double upperQuartile;

median = size % 2 == 0 ? (integerSet[mid] + integerSet[mid-1]) / 2
: integerSet[mid];

vector_Size midlq = mid / 2;
lowerQuartile = mid % 2 == 0 ? (integerSet[midlq] +
integerSet[midlq - 1]) / 2
: integerSet[midlq];

vector_Size miduq = size - midlq;
upperQuartile = mid % 2 == 0 ? (integerSet[miduq] +
integerSet[miduq - 1]) / 2
: integerSet[miduq - 1];

int unsigned i = 0;
std::cout << "Ordered Data: ";
while (i != size)
{
std::cout << integerSet[i] << " ";
i++;
}
std::cout << std::endl;
std::cout << "Median: " << median << std::endl;
std::cout << "Lower Quartile: " << lowerQuartile << std::endl;
std::cout << "Upper Quartile: " << upperQuartile << std::endl;

return 0;
}

Thanks

Apr 12 '07 #1
10 3231
Xernoth wrote:
For those who haven't read the above book, it has a unique way of
introducing C++, as the first chapter jumps straight into the use of
strings, so a lot of basics, like use of functions and so on, have not
been covered as yet.
The program seems well written! Just a note: it's useless to typedef the
std::vector<double>::size_type: use directly std::size_t.

And, of course you'll have noticed, your program performs three times
the same action, as the quartiles can be viewed as the medians for the
upper and lower half of the distribution. Once you'll start studying the
function, it would be interesting for you to try implementing a
function that do this job and calling it three times.

Regards,

Zeppe
Apr 12 '07 #2

"Xernoth" <Jo********@googlemail.comwrote in message
news:11**********************@d57g2000hsg.googlegr oups.com...
Hi,

This is my first post here, so please be gentle. I've been studying c+
+ by mostly using the book Accelerated C++ by Andrew Koenig and
Barbara E. Moo.

So far, I've been picking things up all right, and I've come to an
exercise 3-2 that requires the following:
3-2. Write a program to compute and print the quartiles (that is, the
quarter of the numbers with the largest values, the next highest
quarter, and so on) of a set of integers.

After researching what quartiles are, and using the method defined
here: http://www.statcan.ca/english/edu/power/ch12/range.htm (as from
what I've read, there are different methods used for computing lower
and upper quartiles) I've been able to write a console program that
seems to calculate correctly. However, I would like advice, from a
programming perspective, on what I could improve.

For those who haven't read the above book, it has a unique way of
introducing C++, as the first chapter jumps straight into the use of
strings, so a lot of basics, like use of functions and so on, have not
been covered as yet.

My code is as below:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
std::cout << "Enter a range of integers followed by 'end': ";

std::vector<doubleintegerSet;
A vector of double called integerSet...? Better

std::vector<intintegerSet;
>
int x;
while (std::cin >x)
integerSet.push_back(x);

sort(integerSet.begin(), integerSet.end());

typedef std::vector<double>::size_type vector_Size;
Use std::size_t instead.

>
vector_Size size = integerSet.size();
vector_Size mid = size / 2;
double median;
double lowerQuartile;
double upperQuartile;

median = size % 2 == 0 ? (integerSet[mid] + integerSet[mid-1]) / 2
: integerSet[mid];
If you changed the declaration of integerSet to vector<intabove, you need
to divide by 2.0 instead of 2 to get floating point division:

median = size % 2 == 0 ? (integerSet[mid] + integerSet[mid-1]) / 2.0 :
integerSet[mid];

The same applies below.
>
vector_Size midlq = mid / 2;
lowerQuartile = mid % 2 == 0 ? (integerSet[midlq] +
integerSet[midlq - 1]) / 2
: integerSet[midlq];

vector_Size miduq = size - midlq;
upperQuartile = mid % 2 == 0 ? (integerSet[miduq] +
integerSet[miduq - 1]) / 2
: integerSet[miduq - 1];

int unsigned i = 0;
std::cout << "Ordered Data: ";
while (i != size)
{
std::cout << integerSet[i] << " ";
i++;
}
While the above loop works, a more idiomatic way would be

for (std::size_t i = 0; i < size; i++) {
std::cout << integerSet[i] << " ";
}

Or, using an iterator:

for (std::vector<int>::iterator iter = integerSet.begin(); iter !=
integerSet.end(); iter++) {
std::cout << *iter << " ";
}

std::cout << std::endl;
std::cout << "Median: " << median << std::endl;
std::cout << "Lower Quartile: " << lowerQuartile << std::endl;
std::cout << "Upper Quartile: " << upperQuartile << std::endl;

return 0;
}

Apart from that, looking good :)

--
Jonas
Apr 12 '07 #3
On Apr 12, 11:44 pm, zeppe <z...@nospam.remove.all.this.email.it>
wrote:
The program seems well written! Just a note: it's useless to typedef the
std::vector<double>::size_type: use directly std::size_t.
Thanks for that, I'm not very familiar with the uses of std::size_t,
but I'll review and see how it can be implemented in the current
code.

Apr 13 '07 #4
Jonas wrote:
A vector of double called integerSet...? Better

std::vector<intintegerSet;
I thought about this, and I believe initially I had it set to <int>,
but for some reason changed it to double at one point because
something wasn't calculating correctly; though I doubt that would of
been the cause of an incorrect calculation.
I've not been great with naming conventions for variables, so I can
see that integerSet can be misleading if set to <double>.

Thanks to both for your comments and suggestions.
Apr 13 '07 #5

"Xernoth" <Jo********@googlemail.comwrote in message
news:11*********************@q75g2000hsh.googlegro ups.com...
Jonas wrote:
>A vector of double called integerSet...? Better

std::vector<intintegerSet;

I thought about this, and I believe initially I had it set to <int>,
but for some reason changed it to double at one point because
something wasn't calculating correctly; though I doubt that would of
been the cause of an incorrect calculation.
It was probably not incorrect, just the result of an unexpected integer
division. Example: After the execution of

double result = 5 / 2;

the variable "result" holds the value 2.0, not 2.5 as one might think. This
is because you perform an integer division, which yields an integeger that
is then converted to a double. In your code, you divide an element from
integerSet with 2, which is an integer division. If one of the operands is a
floating point type, then the operation becomes a floating point operation.
So

double result = 5 / 2.0;

yields the result 2.5.

--
Jonas
Apr 13 '07 #6
On Apr 13, 4:23 pm, "Jonas" <spamhereple...@gmail.comwrote:
If one of the operands is a
floating point type, then the operation becomes a floating point operation.
So

double result = 5 / 2.0;

yields the result 2.5.
Ah, thanks for clarifying that. I only had a quick read in regard to
floating point arithmetic. I'll need to review that more in-depth, as
that could be causing inaccuracies with future calculations.
Apr 13 '07 #7
My 2 cents..

Throw your book into some trash-can and never look back.

You first need to understand why std::size_t and the one you defined
are same. There is nothing like reviewing it. Second, learn floating
point arithmetic before trying a double variable.

Better yet, please, first learn the language before you code using
that. I think longer term, it will be very helpful.

Apr 15 '07 #8
"zeppe" <ze***@nospam.remove.all.this.email.itwrote in message
news:46**********@x-privat.org...
The program seems well written! Just a note: it's useless to typedef the
std::vector<double>::size_type: use directly std::size_t.
Useless? Why? std::vector<double>::size_type is an unsigned type that has
room to hold the number of elements in any vector<double>. It is not
difficult for me to imagine machine architectures in which thie type differs
from std::size_t, and I can see no obvious reason why std::size_t would be
preferable on such architectures.

I think that using an object of std::vector<double>::size_type to represent
an index of a std::vector<doubleobject is an example of saying what you
mean.
Apr 15 '07 #9
On Apr 15, 7:55 am, "Andrew Koenig" <a...@acm.orgwrote:
"zeppe" <z...@nospam.remove.all.this.email.itwrote in message
news:46**********@x-privat.org...
The program seems well written! Just a note: it's useless to typedef the
std::vector<double>::size_type: use directly std::size_t.
Useless? Why? std::vector<double>::size_type is an unsigned type that has
room to hold the number of elements in any vector<double>. It is not
difficult for me to imagine machine architectures in which thie type differs
from std::size_t, and I can see no obvious reason why std::size_t would be
preferable on such architectures.
The standard says that vector<>::size_type comes from the
allocator, and that in the default allocator, it must be a
size_t. IMHO, whether to use std::vector<double>::size_type or
simply size_t is largely a matter of style.

If you're using typedef's, the issue becomes a little less
subjective: if I've something like:

typedef std::vector< double VectDbl ;

then VectDbl::size_type will automatically adjust if I change
the typedef to use a user defined allocator; size_t won't (and
could be wrong).
I think that using an object of std::vector<double>::size_type to represent
an index of a std::vector<doubleobject is an example of saying what you
mean.
A very verbose way:-). That's why I say it is a matter of
style. It is certainly more explicit; you're not just using
size_t, you're using a specific type because it is the size_type
of std::vector.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Apr 15 '07 #10
On Apr 15, 7:16 am, "Amit Gupta" <emaila...@gmail.comwrote:
My 2 cents..
Throw your book into some trash-can and never look back.
The book he's using (Koenig's "Accelerated C++") is generally
recognized as one of the best for beginners. I'm pretty sure
that the book didn't tell him to switch to double anytime he's
unsure of a result.
You first need to understand why std::size_t and the one you defined
are same.
And you need to understand why in most cases, one might prefer
what he defined. It's a question of style, but some styles are
preferred over others.
There is nothing like reviewing it. Second, learn floating
point arithmetic before trying a double variable.
That, of course, is very good advice. Rarely taken, but very
good anyway.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 15 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Martin | last post by:
I am reading through Koenig and Moo's "Accelerated C++" and attempting the exercises. Are there any sample solutions somewhere? It's all very well me doing a solution, which seems to work, but for...
3
by: Frankie Montenegro | last post by:
Hi everyone, I must say that, even though I think that Accelerated C++ by Koenig and Moo is an awesome text, the wording of exercises is very poor. I spend half the time just trying to figure...
14
by: Pete | last post by:
Is anyone familiar with this book? Exercise 6-1 of Accelerated C++ asks us to reimplement the frame() and hcat() operations using iterators. I've posted my answers below, but I'm wondering if...
1
by: utab | last post by:
Hi there, I have been reading Accelerated C++ by Andrew Koenig which is an excellent way of learning C++ from even the first pages by using the standard library. One drawback is that no...
3
by: utab | last post by:
Exercise 5.10 from Accelerated C++ by Andrew Koenig Palindromes are words that are spelled the same right to left as left to right. Write a program to find all the palindromes in a dictionary....
8
by: utab | last post by:
Dear all, in a container example, this question is asked in exercises in Accelerated C++ page 154, 8.8? why dont we use (begin+end)/2 instead of begin + (end - begin) / 2 is that someting related...
0
by: Lambda | last post by:
I'm trying to complete all the exercises of Accelerated C++. I'm not sure what does the exercise 5-5 mean. And how about 5-9? Thanks
0
by: Lambda | last post by:
It's from the Accelerated C++ exercise 8-1 The old version is based on pointer to function: double analysis(const std::vector<Student_info>& students, double analysis_grade(const Student_info&...
8
by: utab | last post by:
Dear all, In a question in the highly recommended book Accelerated C++, it is asked to change a const function into a plain function. After on the reader is expected to find which function(s)...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.