Your program should read a word from the input and then sort the letters of the word alphabetically (by their ASCII codes). Next, your program should iterate through the letters of the word and compare each letter with the one following it. If these equal each other, you increase a counter by 1, making sure to then skip ahead far enough so that letters that occur more than twice are not counted again. You may assume that the word you read from the input has no more than 50 letters, and that the word is all lowercase.
I wrote a program and get these results:
apple
gives me 1erroneousnesses
gives 5,- but
taylor
should give me 0 however it gives 1.
How can I make yup
, taylor
and other words with non-repeating alphabets give me 0?
Here is my code:
#include <stdio.h>
int main(void) {
char string[51];
int c = 0, count[26] = { 0 }, x = 0;
scanf("%s", string);
while (string[c] != '\0') {
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] - 'a';
count[x] ;
}
c ;
}
printf("%d", count[x]);
return 0;
}
CodePudding user response:
There are multiple problems in your code:
scanf("%s", string);
may cause a buffer overflow if the input is longer than 50 bytes.- Furthermore, you do not test the return value to check for invalid or missing input.
- counting the number of occurrences of each letter is an alternative approach to the stated problem, and OK if you are only graded based on the program output. However be aware that the program does not implement what the assignment explicitly mandates and the value you output is incorrect anyway.
- the output value should be the number of counts that are
>= 2
. Printing the value ofcount[x]
is meaningless.
Here is a modified version:
#include <stdio.h>
int main() {
char str[51];
int dup = 0;
int count['z' - 'a' 1] = { 0 };
if (scanf(" P[a-z]", str) == 1) {
for (int i = 0; str[i] != '\0'; i ) {
if ( count[str[i] - 'a'] == 2)
dup ;
}
printf("%d\n", dup);
}
return 0;
}
CodePudding user response:
to answer your specifc question
printf("%d", count[x]);
prints the count of number of appearances of the last letter.
taylor => 1 (r occurs 1 time)
apple => 1 (e once)
erroneousnesses => 5 (s count)
you need to loop over count array adding all counts > 1