+ 3
Code coach
All the cases are correct except case 3 which is hidden, am unable see the logical error that I might done please do help me. Here is my code: // Problem name : flowing words #include <stdio.h> #include <ctype.h> int main() { char s[500]; int i=0,r=0; fgets(s,500,stdin); while(s[i]!='\0') { if(isspace(s[i]) && s[i-1] == s[i+1]) r=1; if(isspace(s[i]) && s[i-1] != s[i+1]) r=0; i++; } if(r==1) printf("true"); else printf("false"); return 0; }
7 odpowiedzi
+ 7
Let <r> be 1 before the loop, assume all words flown.
Inside the loop...
Look for one point in the string where the last character of previous word does not match first character of the next word. As soon as you find it, modify <r> to zero (meaning a non-flown word was found), and exit the loop.
Remember to anticipate an event where...
1. The string contains only one word
2. The string ends with a space, with no word following it, or it begins with a space, with no word preceding the space.
Give it a try!
+ 5
The moment the code detects that the sentence does not flow there should be a break statement so that it stops looking and keeps r as 0.
if(isspace(s[i] && s[i] != s[i+1]) {
r=0;
break;
}
+ 3
Ipang thank you very much
But I'm a little confused as to why it didn't work when I initialised r=0 initially, might be because it didn't satisfy the case like you mentioned in point 1 and 2, which was solved by initialising r=1 ?
+ 3
Hi @Sanjana,
I'm guessing it was not working as expected due to how <r> value may be changed multiple times within the loop. But it is only the last <r> value that we care about after the loop.
Take "abc def fed" as an example...
First we find space between "abc" and "def". Last character of "abc" does not match first character of "def" - which means the two words are not flown, and thus we set <r> to 0.
And then we find another space between "def" and "fed", but this time last character of "def" matches the first letter of "fed", and so we set <r> to 1.
Now, since last <r> value was 1, code execution enter the `if(r == 1)` block, unintentionally. But we have found non-flown words in the string earlier :(
About <r> initial value, I only suggested to initialize <r> with 1 because we only need to find whether any adjacent words we non-flown. If we find one, we simply change <r> to 0 (zero) and then exit the loop because we have the verdict at hand :)
Feel free to confirm for an inclarity, anyone here can and would help clear the doubt :)
+ 2
Ipang right makes sense, thank you very much!!
+ 2
Brian thank you
0
is it the ! in != supposed to be a = so it is ==