Have a problem to understand for command.
Have a example here
What is line 2 and 3?
- int i, somme, n=10;
- for (i = 1, somme = 0; i <= n; i = i + 1)
- somme = somme + i;
- for (i = 1, somme = 0; i <= n; somme = somme + i, i = i + 1) ;
- i = 1; somme = 0;
- while (i <= n) { somme += i; i++; }
- i = 1; somme = 0;
- do somme += i++;
- 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.