-1

So, I just want to know if its possible to slip in any code or a ternary operator inside the termination bit of a for loop. If it is possible, could you provide an example of a ternary operator in a for loop? Thanks!

for (initialization; termination; increment) {
   statement(s)
}
nextDouble
  • 43
  • 4

4 Answers4

6

The termination clause in the for statement (if supplied - it's actually optional) can be any expression you want so long as it evaluates to a boolean.

It must be an expression, not an arbitrary code block.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
2

Yes you can since only thing here is termination should be a boolean

for (int i=0; i==10?i<5:i<6; i++) {


}

But what is the point of this?

Things to remember. Termination condition of a for loop should be a boolean

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
2

Absolutely, it is possible:

for (int i = 0 ; i < someCondition ? first : second ; i++) {
    ...
}

you can use ternary operators or any expressions in all three parts of the loop header:

for (int i = flag ? a : -a ; i != (flag ? 2*b : -2*b) ; i += flag ? 1 : -1 ) {
    ...
}

If you need to insert more complex logic into the termination condition, a good approach would be to define a method: it usually improves readability of your loop:

boolean checkCondition(int i) {
    ...
}

...

for (int i = 0 ; checkCondition(i) ; i++) {
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

The termination part of the for loop requires a boolean condition. You can pass anything that gives a boolean value for the termination part.

For ex:

for (int i = 0; i<5?true:false; i++) 
{

}
Rahul Bobhate
  • 4,892
  • 3
  • 25
  • 48