Why doesn't ternary work inside of loops? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why doesn't ternary work inside of loops?

I was working on the Crypto-Cube challenge and I decided to use classes and ternaries (new things for me). They worked fine, but I wasn't able to use the ternary inside a loop, however as soon as I created a variable and set that equal to the ternary, it worked like a charm and I was wondering why we can't use ternary inside loops.

27th Jun 2018, 8:36 PM
Alexandru Turculet
Alexandru Turculet - avatar
6 Answers
+ 2
wrap the ternary with parentheses like this: #include <iostream> using namespace std; int main() { int n = 9; for(int i =0; i<n; i++){ for(int j=0; j< (( i == n - 1 ) ? 5 : 8); j++) cout<<"No "<<j<<endl; } return 0; }
27th Jun 2018, 9:14 PM
MO ELomari
+ 3
Androidus i think it gets evaluated like this (j<(i==n-1))?5:8, when i instead use brackets like this: j<((i==n-1)?5:8) it terminates
27th Jun 2018, 9:14 PM
Max
Max - avatar
+ 2
could you share your code?
27th Jun 2018, 9:00 PM
MO ELomari
+ 2
You can use ternary inside of loops. Can you give us some example code for context?
27th Jun 2018, 9:02 PM
ODLNT
ODLNT - avatar
+ 2
Thanks for the explanation
27th Jun 2018, 9:20 PM
Alexandru Turculet
Alexandru Turculet - avatar
+ 1
Mohamed ELomari ODLNT I can't provide the exact code I had because I have changed it since it gave me the error, but this is some sort of example where it causes an infinite loop: https://code.sololearn.com/cbpMabfOEcHU/?ref=app
27th Jun 2018, 9:07 PM
Alexandru Turculet
Alexandru Turculet - avatar