series [mode number]

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

//	Philipp Siedler
//	Bjarne Stroustrup's PP
//	Chapter 4 Exercise 16

#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 << "The Mode of numSeries is: " << seriesNum[indexHighest] << " counted " << countHighest+1 << " times\n";

	keep_window_open(".");
}

catch (runtime_error e) {
	cout << e.what() << "\n";
	keep_window_open(".");
}
catch(...) {
	cout << "Exiting!\n";
	keep_window_open(".");
}
Output:
Enter a series of numbers equal or larger to 1, enter 0 to end the series
Enter number for series
2
Enter number for series
4
Enter number for series
5
Enter number for series
3
Enter number for series
4
Enter number for series
4
Enter number for series
3
Enter number for series
2
Enter number for series
0
2 2 3 3 4 4 4 5 The Mode of numSeries is: 4 counted 3 times
Please enter . to exit

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.