C # While Loop vs For Loop?

In C #, the question distorted me for a while, and this is what is the actual significant difference between While and For Loop. It is simply a purity of reading; everything you can do in a for loop can be done in a while loop, only in different places. So take these examples:

int num = 3;
while (num < 10)
{
    Console.WriteLine(num);
    num++;
} 

vs

for (int x = 3; x < 10; x++)
{
    Console.WriteLine(x);
}

Both code loops produce the same result and the only difference between them is that the for loop forces you to declare a new variable and also set the iteration value of each loop in the loop at the beginning? Maybe I missed something else in terms of any major differences, but it would be nice if someone could set me up right about this. Thanks.

+6
4

- , for , ?

for . .

for(;;)  // forever
{
  DoSomething();
}

3 :

for(initializer; loop-condition; update-expression)
{
  controlled-statements;
}

:

{
    initializer; 
    while(loop-condition)
    {
       controlled-statements;

    continue_target:  // goto here to emulate continue
       update-expression;
    }
}

{}, for(int i = 0; ...; ...) i for. .

, continue; , while, for-loop.

+9

, (, Assembly).

for, , ().

while , , , , - .

+2

, : for , , while . For , while For " " /, while . Java 0 99 . , for.

for(int i=0; i<100; i++) {
  System.out.println(i);
}

Java . , .

int [] intArray = {1, 3, 5, 7, 9}; 
int i=0;
while(i<intArray.length) {
  System.out.println(intArray[i++]);

}

+1

When you are sure what will be the final value or how much the loop should execute (to what value), use a for loop, otherwise use a while loop.

0
source

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


All Articles