Recently I came back to the C language and decided that HackerRank would be good to begin with. There is this problem : https://www.hackerrank.com/challenges/for-loop-in-c.
I tried this :
int main()
{
int a, b;
scanf("%d\n%d", &a, &b);
char rep[9][5] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
for(int i = a; i <= b; i++)
{
if(i <= 9 && i >= 1)
{
printf("%s\n", rep[i - 1]);
}
else
{
printf((i % 2 == 0) ? "even\n" : "odd\n");
}
}
return 0;
}
and got this output:
eightnine
nine
even
odd
I know that the preffered way to do this is to use the const char * array, but shouldn't this work too? Why does it print an extra "nine"?
A string literal like that
"three"contains 6 characaters including the terminating zero character'\0'.So you need to declare the array
repat least likeOtherwise the conversion specifier
%sused in this call ofprintfwill try to output all characters until the terminating zero character
'\0'will be encountered.Though it would be better to declare the array like
In the if statement of the for loop you can write
Pay attention to that in C++ the compiler will issue an error message because the declaration
is invalid in C++.
C++ does not allow to ignore the terminating zero character of string literals used as initializers of character aarrays.