How does this loop work in C #

I read this code recently in a book. Can you determine the means of this code and how this code works.

int i = 0; for (; i != 10; ) { Console.WriteLine(i); i++; } 
+7
c #
source share
8 answers

These are loops.

Since you already set i=0 above, they skipped this section of the for loop. Also, as you increment the variable at the end, they also skipped this.

They basically just turned the for loop into a while loop.

Perhaps this would be more elegant since:

 int i = 0; while( i != 10 ) { Console.WriteLine(i); i++; } 
+13
source share

The for statement is defined in the C # specification as

for (for-initializer; for-condition; for-iterator) embedded-statement

All three for-initializer, for-condition, and for-iterator parameters are optional. The code works because these parts are not required.

For the curious: if the for condition is omitted, the loop behaves as if there was a condition that yields true. Thus, it will act as an infinite loop, requiring the transition operator (break, goto, throw or return).

+2
source share

If it is easier to see in normal form, it is almost the equivalent of this:

 for (int i = 0; i != 10; i++) { Console.WriteLine(i); } 

Except that it leaves i available to the user after the loop completes, it is not tied to the for loop.

+1
source share

This is the same as this loop:

 for (int i = 0; i != 10; i++) { Console.WriteLine(i); } 

In addition, the variable i declared outside the loop, so the scale is larger.

In the for loop, the first parameter is initialization, the second is a condition, and the third is an increment (in fact, it can be anything). The book shows how initialization and increment are moved to the place in the code where they are actually executed. The loop can also be shown as an equivalent while :

 int i = 0; while (i != 10) { Console.WriteLine(i); i++; } 

Here the variable i also declared outside the loop, so the scope is larger.

+1
source share

You use "for", for example, "bye"

+1
source share

This code can be rewritten (in the context of a piece of code - it is not equivalent, as indicated.) As:

 for (int i = 0; i != 10; i++) Console.WriteLine(i); 

Basically, the initialization expression and the increment expression were taken from the for loop expression, which are optional.

+1
source share

This is the same as:

 for (int i = 0; i != 10; i++) { Console.WriteLine(i); } 

Please do not write such code. It is just ugly and defeats the for-loops goal.

0
source share

Like int i was declared on top, so it was not in a for loop. it is very similar to

 for(int i = 0; i!=10; i++) { /// do your code } 
0
source share

All Articles