I don't know if that's been asked before, but I haven't been able to find an answer, nonetheless. My question is this; in For loops, this is acceptable.
int k = 0;
for (int i = 0; i <= 10; i++)
k++;
But this is NOT:
int k = 0;
for (int i = 0; i == 10; i++)
k++;
Why is it that I cannot use '==' to determine whether the condition has been met? I mean, both expressions return true or false depending on the situation and the latter would be appropriate for, say, an If loop.
int k = 10;
if (k == 10)
{
// Do stuff.
}
The answer to this question has been bothering me for a good while now during my time as a hobbyist programmer, but I hadn't searched for it till now.
If you put the && operator in it, it means that both conditions before and after the && have to be met. Otherwise the loop terminates. So if i == 3 the left part evaluates to false and your loop ends.
It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.
The while loop is not run because the condition is not met. After the running the for loop the value of variable i is 5, which is greater than three. To fix this you should reassign the value before running the while loop (simply add var i=1; between the for loop and the while loop).
A for
loop will run while the condition is satisfied. At the beginning i = 0
, so your test i == 10
is never satisfied and thus the body of the loop is never executed.
On the other hand you could have used i == 0
condition and the loop would have executed only once:
for (int i = 0; i == 0; i++)
k++;
That's the reason why if you want a for loop to execute more than once, you need to provide a condition for the iterator variable that is <
or >
so that it can be satisfied more than once while this iterator variable increments/decrements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With