Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

for-loop

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.

like image 666
Dimitris Iliadis Avatar asked Sep 14 '13 08:09

Dimitris Iliadis


People also ask

Can we use == conditions in for loop?

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.

Can we give 2 conditions in for loop?

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.

Why while loop is not working?

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).


1 Answers

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.

like image 89
Darin Dimitrov Avatar answered Oct 16 '22 03:10

Darin Dimitrov