I'm writing a code that must identify the letter 't'
or 'T'
in a word, before or after the middle of it.
If the first half of the word does contain a 't'
or a 'T'
, the program should output a 1
. If the first half does not contain the letter 't'
or 'T'
, but the second half does, then the program should output a 2
. Otherwise, if there is no 't'
or 'T'
in the word at all, the program's output should be -1
. The word entered will not have more than 50 letters.
#include <stdio.h>
#include <string.h>
int main() {
char word[50];
int i = 0, length, t = 0, T = 0;
scanf("%s", word);
length = strlen(word);
t = word[i] == 't';
T = word[i] == 'T';
while(!t || !T) {
if((t || T) && i <= length / 2) {
printf("%d", '1');
} else if((t || T) && i > length / 2) {
printf("%d", '2');
}
i++;
}
return 0;
}
If I enter any word and press enter, nothing is printed. Another thing is that when I remove the comment slashes from the two lines at the bottom, the program goes through an infinite loop.
What makes the program go into an infinite loop?
t = word[i] == 't';
assigns a value tot
based on the valuei
has only at that moment. It does not bindt
to an expression that is reevaluated wheni
changes. This shows you have not learned how C works and are not ready for this problem. Go back to earlier lessons.t
orT
inside the loop, so your loop is going to either run not at all or run forever. Neither is what you intend, I assume. You should probably check for overruns ofi
in the loop control:while ((!t || !T) && i < length)
, and you probably need the assignments tot
andT
moved inside the loop.