Why can't I use == in a For loop?

I do not know if this was asked before, but nevertheless I could not find the answer. My question is this; in For loops this is acceptable.

int k = 0; for (int i = 0; i <= 10; i++) k++; 

But it is not:

 int k = 0; for (int i = 0; i == 10; i++) k++; 

Why can't I use '==' to determine if a condition is met? I mean that both expressions return true or false depending on the situation, and the latter is suitable for, say, an If loop.

 int k = 10; if (k == 10) { // Do stuff. } 

The answer to this question has long bothered me when I was an amateur programmer, but I still have not looked for it.

+4
source share
4 answers

A for loop will be executed during the execution of the condition. At the beginning i = 0 , so your test i == 10 never executed and therefore the loop body is never executed.

On the other hand, you could use the condition i == 0 , and the loop would execute only once:

 for (int i = 0; i == 0; i++) k++; 

That is why, if you want the for loop to be executed more than once, you need to provide a condition for the iterator variable, which is < or > , so that it can be executed more than once, while this iterator is increment / decrement variables.

+15
source

For a loop, it works until the condition is true, so you can write

 for (int i = 0; i <= 10; i++) k++; 
+7
source

When you put i == 10, then it checks the condition for i, whether it is equal to 10 or not. and obviously i = 0 initially, so the loop breaks out

therefore, if you want to break the loop in some state, it is advisable to use

 for (int i = 0; i <= 10; i++) { if(i==5) // test with your condition break; k++; } 
+5
source

You absolutely can write such a condition.

It just doesn't make sense.

Here's the broken syntax for loop:

for(<initial statement>;<boolean expression - keep going while true>;<statement performed after each iteration>)

So, in a typical scenario that you described

 for (int i = 0; i <= 10; i++) k++; 

the initial statement is declaration i . The loop will work until i remains 10 or less , and after each iteration i will increase by one.

To summarize - you can write i == 10 , it just won’t make much sense, because the loop will not work, since i already 0. If you replaced the initial condition with int i = 10 then it will only start once . You could also write i != 10 as a condition, and then the loop will execute 10 times.

+1
source

Source: https://habr.com/ru/post/1502161/


All Articles