Friday, 5 August 2016

Chapter 4 // Exercise 16 - 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.


Chapter 4 Exercise // 4.16

In the drill you wrote a program that, given a series of numbers, found the max and min of that series. the number that appears the most times in a sequence is called the mode. Create a program that finds the mode of a set of positive integers.

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

int main()
{
vector<int> numbers;

cout << "Enter a set of numbers (press enter then ctrl+z when finished): \n";
int n;
while (cin >> n)
{
numbers.push_back(n);
}

sort(numbers);

int number = 0;
int mode = 0;
int highCount = 0;
int mostOccurring;
int count = 0;

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

for (int i = 0; i < numbers.size(); ++i)
{

if (i == 0) // get the ball rolling
{
number = numbers[i];
++count;
}

else 
{
if (number == numbers[i])
{
++count;
mode = numbers[i];
}
else
{
if (highCount == 0) 
{
highCount = count;
mostOccurring = mode;
}

if (count > highCount)
{
highCount = count;
mostOccurring = mode;
}
else
{
number = numbers[i];
count = 1;
}

}

}

}

cout << "\nThe mode is: " << mostOccurring;
cout << "\nAppearing " << highCount << " time(s)" << endl;


keep_window_open();

return 0;
}

This one took me a while but it was just a matter of getting the if statements to execute correctly. I mainly took inspiration from the exercise he mentions above and edited it.

Basically, it reads a set of integers into a vector. Sorts them, then on every loop checks if the current number was the same as the last. If it is, the count increases until it hits a different number. Then that number and count is stored, the comparing numbers are reset and it starts all over again. If it encounters a count higher than the one stored, the most occurring number and highest count is replaced by those. 

No comments:

Post a Comment