1

I try to do this, but the loop doesn't work for some reason, it just skips it.

I need to do if the i variable is greater than 10 then check the g condition and if it is equal to 1 complete the loop

until two conditions are met the loop should not end

int main() { for (int i = 0, g = 12; i < 10 ? g == 1 : false; i++, g--) { std::cout << i << " | " << g << std::endl; } return 0; } 

2 Answers 2

1

I need to do if the i variable is greater than 10 then check the g condition and if it is equal to 1 complete the loop...

Your usage to Conditional operator there is wrong.

Instead, you should be simply using logical && operator there

for (int i = 0, g = 12; /*first condition*/ && /* second condition */ ; i++, g--) // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

Therefore, you need:

for (int i = 0, g = 12; i < 10 && g >= 1 ; i++, g--) // ^^^^^^^^^^^^^^^^ 

The above loop will first check whether the i is less than 10, if true will check the next condition which is g is grater than or equal to 1: if that is also true: do the iteration!

Sign up to request clarification or add additional context in comments.

9 Comments

I read it as g != 1. (Complete, i.e. stop the loop when g is 1). Who's correct?
@Bathsheba I think this one is direct translation of OP's code, but not what they want, because the loop will never be entered. If i < 10 then the result is g == 1
for (int i = 0, g = 12; i < 10 && g >= 1 ; i++, g--) does not work g is equal to 3 at this moment
@fox As per what you asked in the question, the above will do the job. The g >= 1 is true for all the cases when g==12, 11, 10, 9, 8,.....,3, 2, 1.
Nicked your conditional on g which must be correct as the OP has accepted. Have an upvote for good feelings (and this is a good answer).
|
0

Just use AND operator as for (int i = 0, g = 12; i < 10 && g > 1; i++, g--) and don't try to use something more complex when the simple solution works.

Why use lot word when few word do trick?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.