LearnFrenzy
Sign in Take a free test

C Input / Output · Input/Output Programs · Question 4

Count letter frequency from input with getchar in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Read all input with getchar() and print how often each letter occurs (ignoring case), for letters that appear at least twice.

Solution
main.c
#include <ctype.h>
#include <stdio.h>

int main(void) {
    int freq[26] = {0};
    int ch;
    while ((ch = getchar()) != EOF)
        if (isalpha(ch))
            freq[tolower(ch) - 'a']++;
    for (int i = 0; i < 26; i++)
        if (freq[i] >= 2)
            printf("%c: %d\n", 'a' + i, freq[i]);
    return 0;
}

Output Verified by compiling and running

c: 2
l: 4
o: 4

The letters are counted in an array indexed by letter - 'a'. getchar's result is kept in an int so the loop can recognise EOF.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links