+ 1

What's wrong with the C code?

Original question: https://www.sololearn.com/coach/54?ref=app Basically, I'm trying to find how many times a character occurs in a string. So my approach was to, loop through the string, set 'i' to the variable 'ch', then loop through the string again (nest loop), comparing if 'ch' is == 'i', and if it is, increment 'count' varible, otherwise do nothing. Then after everything is done, check if 'count' variable > 1, if it is, output "Deja Vu", else "Output". But my code isn't working well because it outputs "Deja Vu" on every test case. Hope y'all understand what exactly am trying to say šŸ˜”. My C CODE: #include <stdio.h> #include <string.h> int main() { char str[1000]; scanf("%s", str); int i, j, count = 0; char ch; for (i = 0; i < strlen(str); i++) { ch = i; for (j = 0; j < strlen(str); j++) { if (ch == j) { count++; } } } if (count > 1) { printf("Deja Vu"); } else { printf("Unique"); } return 0; }

30th Aug 2021, 3:33 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
1 Answer
+ 3
There is no need of nesting of loop, you just have to check whether a character is repeating it self, and you can go with: for(i = 0; i<strlen (str); i++){ if (str[i] == str [i+1]){ count++; break; } } if(count > 1) printf ("Deja Vu"); else printf ("Unique");
30th Aug 2021, 3:42 PM
Rupali Haldiya
Rupali Haldiya - avatar