Declare loop control variable inside the for in CSharp
Description
The following code shows how to declare loop control variable inside the for.
Example
using System; //from w w w. j a va 2 s . c o m
public class MainClass {
public static void Main() {
int sum = 0;
int fact = 1;
// compute the factorial of the numbers through 5
for(int i = 1; i <= 5; i++) {
sum += i; // i is known throughout the loop
fact *= i;
}
// but, i is not known here.
Console.WriteLine("Sum is " + sum);
Console.WriteLine("Factorial is " + fact);
}
}
The code above generates the following result.