Hey, so I need to calculate and display the mode (most frequently occuring number) from a vector of ints. I already have the vector, and it can have any number of elements in it. So now i need to figure out a way to loop through my vector to figure out the number that occurs most. I also need a message that says "No Mode" if there is an equal number of every number.

This is what I have so far but it doesn't work very well. Could any1 help me out? Vector is called "v"

double previous = 0;
	double current = 0;
	double mode = 0;
	for (int i = 0; i < v.size(); i++)
	{
		for (int j = 0; j < v.size(); j++)
		{
		if (v[j] == v[i])	
			current++;
		}
		if (current > previous) {
			mode = v[i];
			previous = current;
			current = 0;
		}
	}
		cout << "Mode = " << mode << endl;

Recommended Answers

All 3 Replies

You are very close. You should set current to zero every time i changes, not just when it's big enough to become the current mode count.

EDIT: You were closer than I initially thought...

You are very close. You just need to fix two things.

(1) You should set current to zero every time i changes, not just when it's big enough to become the current mode count.
(2) It's not useful to compare the current count with the previous one. It would be better to compare it with the current mode count.

Wow thanks alot, that did the trick.

You might consider sorting then evaluating it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.