How do you use an existing variable within one or more for loops?
The issue is one of scoping. Read here for some details on how variable scoping works in C#.
If a variable is declared outside a loop, you can't re-declare it inside:
BAD:
int c = 0;
for(int c = 0; c < list.Count; c++) // Error!
{
}
OK:
Declared outside, used inside:
int c = 0;
for(c = 0; c < list1.Count; c++)
{
}
for(c = 0; c < list2.Count; c++)
{
}
Declared inside two loops:
for(int c = 0; c < list1.Count; c++)
{
}
for(int c = 0; c < list2.Count; c++)
{
}
You can either do
int i;
for (i = 0; i < 3; i++)
foo(i);
for (i = 0; i < 5; i++)
bar(i);
or
for (int i = 0; i < 3; i++)
foo(i);
for (int i = 0; i < 5; i++)
bar(i);
but not
int i;
for (int i = 0; i < 3; i++) //error
foo(i);
for (int i = 0; i < 5; i++)
bar(i);