series [min max mode]

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 4 Exercise 17
Using std_lib_facilities.h by Bjarne Stroustrup.

[code language=”cpp”]
// Philipp Siedler
// Bjarne Stroustrup’s PP
// Chapter 4 Exercise 17

#include "std_lib_facilities.h"

int main()
try
{
vector<int> seriesNum;
int singleNum;
int counterTemp = 0;
int countHighest = 0;
int indexHighest = 0;

string noNum = " ";
bool check1 = true;

cout << "Enter a series of numbers equal or larger to one, enter 0 to end the series" << "\n";

while (check1 == true) {
cout << "Enter number for series\n";
cin.clear();

if (cin >> singleNum) {
if (singleNum > 0) {
seriesNum.push_back(singleNum);
}
else if (singleNum == 0) {
check1 = false;
break;
cout << "test";
}

}
else {
cin.clear();
cin >> noNum;
error("Entry was not a number", noNum);
}
}

sort(seriesNum);

for (int i = 0; i < seriesNum.size(); i++) {
cout << seriesNum[i] << " ";
}

for (int i = 1; i < seriesNum.size(); i++) {
if (seriesNum[i] == seriesNum[i – 1]) {
counterTemp++;
}
else {
counterTemp = 0;
}
if (counterTemp > countHighest) {
indexHighest = i – 1;
countHighest = counterTemp;
}
}

cout << "\nThe mode of numSeries is: " << seriesNum[indexHighest] << " counted " << countHighest + 1 << " times\n";
cout << "The min value of numSeries is: " << seriesNum[0] << "\n";
cout << "The max value of numSeries is: " << seriesNum[seriesNum.size()-1] << "\n";

keep_window_open(".");
}

catch (runtime_error e) {
cout << e.what() << "\n";
keep_window_open(".");
}
catch (…) {
cout << "Exiting!\n";
keep_window_open(".");
}
[/code]

Output:
Enter a series of numbers equal or larger to one, enter 0 to end the series
Enter number for series
2
Enter number for series
3
Enter number for series
3
Enter number for series
2
Enter number for series
2
Enter number for series
25
Enter number for series
4
Enter number for series
3
Enter number for series
0
2 2 2 3 3 3 4 25
The mode of numSeries is: 2 counted 3 times
The min value of numSeries is: 2
The max value of numSeries is: 25
Please enter . to exit

Leave a Reply