Declare loop control variable inside the for
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Declare loop control variable inside the for.
using System;
public class ForVar {
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);
}
}
Related examples in the same category