just a quick question, do you know why the code below would the give the following answers ive given, i understand why they input on the 4 separate lines but the amount of times it prints the letter 'x' is confusing me.
Why would this give the answer: Generate 5 letters 'x' on 4 separate lines.
printf("%c", i%6 ==0 ? '\n' : 'x');
Why do you expect something different ?
Originally Posted by mattio87
Yes, i would have thought it would have printed 4 x's not five.
1 % 6 = 1 -> 'x'
2 % 6 = 2 -> 'x'
3 % 6 = 3 -> 'x'
4 % 6 = 4 -> 'x'
5 % 6 = 5 -> 'x'
6 % 6 = 0 -> '\n'
7 % 6 = 1 -> 'x'
I still dont understand it Kurt, it says i=1 i<=24, so it uses 1 -> 24.
24/6 = 4, giving the amount of separate lines.
I have no idea where the 5 letters of X still come from though :(
I hope that we agree that your code prints a total of 24 chars.
24/6 = 4 '\n' and 20 'x'
If so, why does the answer say that it prints 5 letters 'x'?
Am i just being stupid? lol
If the answer says that it prints only 5 x's then the answer is wrong.
It prints 4 times 5 x's.
Well, as you can see in Kurt's post, all the values between two different multiples of 6 print an x. So you can do the following to find how many 'x' are printed between two consecutive multiples:
((k+1) * 6) - ((k * 6) + 1) = 5
k*6 is a multiple of 6 and will result in a linebreak.
k*6 + 1 is the first character that will result in an x being printed
(k+1)*6 is the next multiple of 6
The difference of the two clearly results in 5.
And yes, the output is:
Thanks very much, i understand it now.