It appears that you really don't understand the purpose of the count array. This array will hold the number of times a letter appears in the string with count of the letter 'a' being in count[0], letter 'b' in count[1] and so on.
The code worked after a few changes, if this still not what the question is asking?
Almost, the problem is that you will be accessing your count array out of bounds. Remember your array starts at zero and ends at 25. What is the ASCII value of 'a', hint: it's much larger than 25.
Oh yea a=97, and I'm saying that it should output count[97], so its out of bound... hmm... so in this case is it just my for function in main wrong, or is it the countalpha function?
Did you run the program with your debugger? The debugger should be able to tell you exactly where it detects the problem, and should allow you to view the variables at the time of the crash.
What are you trying to do in that last set of loops in your function?
#include <iostream>
#include <cctype>
#include <cstring>
usingnamespace std;
void countalpha(char str[], int count[]);
void main()
{
int count[26] = { 0 }, j = 0;
char str[100];
cout << "Enter a sentence = ";
cin.getline(str, 100);
countalpha(str, count);
for (char i = 'a'; i <= 'z'; i++)
{
cout << i << " = " << count[i-97] << endl;
}
}
void countalpha(char str[], int count[])
{
for (int i = 0; i < strlen(str); i++)
{
str[i] = tolower(str[i]);
}
for (char letter = 'a'; letter <= 'z'; letter++)
{
for (int i = 0; i < strlen(str); i++)
{
if (letter == str[i])
count[letter-97]++;
}
}
}
I tried editing my first program again, with the count[letter-97] in the function and count[i-97] in the main, does it then answer the question and meet the bound of count[26]? The program itself works