#include<stdio.h>
void main()
{
int t,i=0;
scanf("%d",&t);
while(t--)
{
char c;
scanf("%c",&c);
char s[10]="codeforces";
while(s[i]!='\0')
{
if(s[i]==c)
printf("YES\n");
else
printf("NO\n");
i ;
}
}
}
I tried 10 test cases but the output is 10 times NO
CodePudding user response:
For starters according to the C Standard the function main
without parameters shall be declared like
int main( void )
After this call of scanf
scanf("%d",&t);
the input buffer stores the new line character '\n'
that corresponds to the pressed key Enter.
So the next call of scanf
scanf("%c",&c);
automatically reads this new line character '\n'
.
To skip white space characters in the input buffer you need to place a leading space character in the format string like
scanf(" %c",&c);
^^^^
Also the inner while loop should be interrupted as soon as the inputted character is found in the string. The messages should be outputted after the while loop. And the variable i
is not set to 0
within the outer while loop. So the code has a logical array. You should declare variables in minimum scopes where they are used.
Remove the declaration of i
in this line
int t,i=0;
And rewrite the while loop the following way
size_t i = 0;
while ( s[i] !='\0' && s[i] != c ) i;
if ( s[i] != '\0' )
{
printf("YES\n");
}
else
{
printf("NO\n");
}
In whole the program can look for example the following way.
#include <stdio.h>
int main( void )
{
unsigned int t;
if ( scanf( "%u", &t ) == 1 )
{
while ( t-- )
{
const char *s = "codeforces";
char c;
scanf( " %c", &c );
size_t i = 0;
while ( s[i] != '\0' && s[i] != c ) i;
if ( s[i] != '\0' )
{
puts( "YES" );
}
else
{
puts( "NO" );
}
}
}
}
CodePudding user response:
#include<stdio.h>
void main() {
int t,i=0;
scanf("%d",&t);
while(t--)
{
char c;
scanf(" %c",&c); // note the addition of a space character before the %c format specifier
char s[10]="codeforces";
while(s[i]!='\0')
{
if(s[i]==c)
printf("YES\n");
else
printf("NO\n");
i ;
}
}
} check this one