Challenge: Letter Counts
Completed
Read one word of small letters. Use calloc to make 26 counters (all starting at 0), count each letter, and print every letter that appears, in alphabetical order, as letter:count, one per line.
Input
One word of small letters.
Output
One line per letter that appears.
Example
Input
banana
Output
a:3 b:1 n:2
Editor
C
Hints
word[i] - 'a' turns a letter into 0..25.
'a' + i turns it back into a letter.
Solution explanation
Each letter has its own counter, found by its distance from 'a'.
Show solution
#include <stdio.h>
#include <stdlib.h>
int main() {
char word[101];
scanf("%s", word);
int *counts = calloc(26, sizeof(int));
for (int i = 0; word[i] != '\0'; i++) {
counts[word[i] - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (counts[i] > 0) {
printf("%c:%d\n", 'a' + i, counts[i]);
}
}
free(counts);
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module