Most Frequent Character Issues

Can't seem to get this to run properly. Can anyone see the issue(s)? Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
using namespace std;

void countChar( char *, int);
char again;

int main()
{
	do
	{
		const int SIZE = 100;
		char input[SIZE];

		cout << "Enter a string: " << endl;
		cin.getline(input, SIZE);

		countChar(input, (int) SIZE);
		cout << " appears the most times." << endl;
		cout << "Do you want to run this program again? Y/N: ";
		cin >> again;
		cout << endl;

	} while (again == 'y' || again == 'Y');

	return 0;
}

void countChar (char * character, int length)
{
	char input;
	int x = 0;
	int max = 0;
	int y, count;

	while(character[x] != '\0')
		x++;

	const char * first;
	const char * last  = character + x;

	for(first =  character; first != last; first++)
		y = 0;
	count = 0;

	while(character[y])
	{
		if(*first == character [y])
			y++;
	}

	if(count > max)
	{
		max = count;
		input = *first;
	}
}
Your countChar function is a bit of a mess. The first loop and x are completely useless; you can get the last character with just character + length - 1. But you don't even need that; you can just loop starting at i = 0, and run while i < length using a for loop. The for loop you do use does nothing but set first = last and set y = 0 a bunch of times, because you have no braces with it. Don't even know what that second while loop is doing.

Basically, I would suggest using a better for loop like I suggested to loop through each character. Then, have another array of ints with 26 elements, all initialized to 0, and whenever you get a certain character you increment the appropriate element of the int array (you can just subtract the ASCII value of 'a' from the character itself to get a number 0-25 to use for indexing the array). Once you've gone through all the letters, just find the largest value in the array of ints and you're done. Your function should probably return the char that occurs the most often, rather than nothing.
Topic archived. No new replies allowed.