Reputation: 247
I want a code that counts the number of occurrences of letters in an array. I have looked at various codes that do the exact, but they all use strings. My issue here is to strictly use arrays.
I have created a code, but it returns: : 0 : 1 : 2 : 3 : 4 : 5 : 6 : 7 : ...
one correct example: input:
The quick brown fox jumps over the lazy dog.
output:
A: 1
B: 1
C: 1
D: 1
E: 3
F: 1 ...
The following is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int i = 0;
int c;
char counts[26] = {0};
c = getchar();
while (c != EOF && i < 26) {
counts[i] = c;
i += 1;
c = getchar();
}
for (i = 0; i < 26; i++) {
if (counts[i] !=0 )
printf("%c: %d", toupper(c), i);
}
return EXIT_SUCCESS;
}
Upvotes: 3
Views: 202
Reputation: 16243
Using your code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int c;
int counts['Z' - 'A'] = {0};
c = getchar();
while (c != EOF)
{
if (isalpha(c))
counts[(toupper(c)-'A')]++;
c = getchar();
}
for (unsigned int i = 0; i < sizeof(counts)/sizeof(counts[0]); i++)
{
if (counts[i] !=0 )
printf("%c: %d\n", 'A'+i, counts[i]);
}
return EXIT_SUCCESS;
}
(toupper(c)-'A')
that makes the value of entered char 0 based index. if (isalpha(c))
do that.Upvotes: 11