Finding most common char in a string.

Dec 9, 2015 at 5:26am
I have worked on this without asking for help and figured out most of what to do. Unfortunately, this code keeps outputting the last letter in the string instead of the most common and I can't figure out why. Any suggestions?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
char mostPopular(const string & s){
	char ret;
	int max = 0;
	int count = 0;
	for (unsigned pos = 0; pos < s.size(); pos++) {
		for (unsigned pos1 = 0; pos1 < s.size(); pos1++) {
			if (s[pos] == s[pos1]) {
				count++;
			}
			if (count > max) {
				max = count;
				ret = s[pos];
			}
		}
	}
	return ret;
}
Last edited on Dec 9, 2015 at 5:27am
Dec 9, 2015 at 5:28am
You forgot to reset count before entering the inner loop.
Dec 9, 2015 at 5:36am
You are a lifesaver, helios!

Going to need to lock it into my brain as to why it needed to be reset.

Do the inner loop variables hold a value even when the loop finishes?
Dec 9, 2015 at 12:01pm
Do the inner loop variables hold a value even when the loop finishes?
count isn't an "inner loop variable". You declare it outside both loops, at line 4, so it's in scope for the entire function.

pos1 is only in scope within the inner loop.

pos is in scope for the entire outer loop.
Topic archived. No new replies allowed.