Moh'd H
Moh'd H

Reputation: 247

counting the number of letter occurences in an Array

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

Answers (1)

LPs
LPs

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;
}
  1. Your array is designed to store occurencies of each letter. So the idex of an array must be the latter entered. As you can see I used (toupper(c)-'A') that makes the value of entered char 0 based index.
  2. You must check that entered char is an alphabet char. if (isalpha(c)) do that.
  3. The printout must print characters using the index of array and array content

Upvotes: 11

Related Questions