Here's a fixed version of your code, with comments as to why I made the change:
class Program
{
static void Main(string[] args)
{
//fix the 'use of undefined' error
int average = 0;
int[] scores = new int[10];
Console.WriteLine("Enter 10 scores");
//it's better to scope loop iteration variables to the loop unless you specifically need them outside
for (int i = 0; i < 10; i++)
{
scores[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < 10; i++)
{
//your old code would crash here, and had the wrong algorithm for calculating an average; it didn't sum all the entered values, just the last two
average += scores[i];
}
average /= 10;
Console.WriteLine("Average of All the Scores: {0}", average);
Console.Read();
}
}
I was puzzled as to why the error occurred too because the second loop was clearly assigning a value and I knew that inner scopes could set values and the compiler would recognise them.. learning day for me too as I was formerly unaware that some loops are excluded even when they're set up so they look like they will definitely run. In simple terms it seems that when a loop is set up so that its running is conditional on a variable, the flow analysis considers that in some scenarios the loop might not run even though it's clear to the human reading the code that the loop will always run. Consider these:
//this is fine, flow analysis determines this loop will always run
int average;
while(true){
average = 0;
break;
}
average /= 10;
//this raises the same error even though we as a human can definitely see this loop will always run
int average;
int w = 0;
while(w<1){
average = 0;
}
average /= 10;
Making the loop conditional on a variable meant the compiler wa and longer sure the variable was assigned
As another more involved example, you could also fix your error with this bizarre construct as your first loop:
for (int i = 0; true; i++)
{
average = 0;
scores[i] = Convert.ToInt32(Console.ReadLine());
if(i >= 10)
break;
}
Again the compiler can be sure this loop will always run and your variable will be assigned
here's Peter's comment in case the other answer/the comment goes away:
the compiler doesn't implement any static flow analysis that would confirm that the average variable is set. According to the "definite assignment" rules of C#, loops are ignored because it's possible for a loop to not iterate even once. Thus, average is not definitely assigned, and thus the error. See marked duplicate, and of course the C# language specification, for more details.