for in C#

Have a problem to understand for command.
Have a example here
What is line 2 and 3?

  1. int i, somme, n=10;
  2. for (i = 1, somme = 0; i <= n; i = i + 1)
  3. somme = somme + i;
  4. for (i = 1, somme = 0; i <= n; somme = somme + i, i = i + 1) ;
  5. i = 1; somme = 0;
  6. while (i <= n) { somme += i; i++; }
  7. i = 1; somme = 0;
  8. do somme += i++;
  9. while (i <= n);

Line 2 is doing a C-style for-loop with the syntax:

for( <initializers>; <loop-condition>; <loop-incrementer> )
{
    <loop-body>
}

is a comma-separated list of variables (99.9% of the time should be only one but in your example there are two) and their initial value.

In line #2, we have i set to 1 and somme set to 0.

is a boolean expression that gets evaluated after the end of each loop iteration. If it evaluates to true, the loop continues. In line number 2 the test is that i must be less than or equal to n.

Finally, the . This is a statement that is executed after the end of each loop iteration, before the test.

In line #2 it says at the end of each loop iteration, increment i by 1.

In line #5 it says to increment i by 1 and somme by 1, also.

To sum up execution:

<initializers> -> <loop-condition> -> (if true) -> <loop-body> -> <loop-increment> -> (back to loop condition)

Hope that helps!

thanks.

What is somme = 0; doing in all this?

You don’t often see this, but you can actually have more than one initialising expression in a for loop if you separate the expressions with commas.