- 1

What is the problem here?

int x=9; while (x<19) { x= (x%3!=0) ? Console.Write(x) : Console.Write("*"); x++; }

23rd Aug 2022, 10:04 AM
TheMasterBee
TheMasterBee - avatar
7 Answers
+ 1
In Javascript, x is undefined after the first ternary evaluation, and NaN after x++. NaN compared with a number is false, hence the loop breaks.
23rd Aug 2022, 10:29 AM
Lisa
Lisa - avatar
+ 1
I was trying to explain it in my initial comment. x = (x%3 != 0) ? A: B; x will be reassigned by the end of the statement, it will either be A or B depending on the result of the evaluation. If A is console.log(), x becomes undefined as console.log() doesn't return what it prints (undefined in Javascript) In C# it will raise an error as Console.Write doesn't return either and "void" cannot be assigned to an integer variable.
23rd Aug 2022, 10:38 AM
Lisa
Lisa - avatar
+ 1
I think, it's just not the intended usage of the ternary operator. You could just use a regular if-else statement or functions with return values. https://code.sololearn.com/c2ttAt6aEHR0/?ref=app
23rd Aug 2022, 10:58 AM
Lisa
Lisa - avatar
0
In ternary operations, the result.of the comparison is assigned to the the variable (here x). However, ConsoleWrite() does not return an integer (it doesn't return at all). That's why an error occurs.
23rd Aug 2022, 10:19 AM
Lisa
Lisa - avatar
0
If your code is JavaScript, then: var x=9; while (x<19) { x=(x%3!=0) ? console.log(x) : console.log("*"); x++; }
23rd Aug 2022, 10:23 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
0
yep, that's the problem. now it is clear why the cycle does not work. but why is x undefined? it is also set to 9 before the cycle.
23rd Aug 2022, 10:33 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
0
excellent knowledge of the subtleties of language! what in this case needs to be done to avoid this phenomenon and the cycle has worked?
23rd Aug 2022, 10:48 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar