using System;
class FirstArray
{
static void Main()
{
int numOfGrades;
double[] listOfGrades;
Console.Write("How many students in the class? ");
numOfGrades = int.Parse(Console.ReadLine());
listOfGrades = new double[numOfGrades];
ReadGrades(listOfGrades);
double sumGrades = GetGradesSum(listOfGrades);
Console.WriteLine("\n\nClass statistics\n--------------------");
Console.WriteLine("Grades sum = {0:F2}", sumGrades);
}
static void ReadGrades(double[] grades)
{
for(int i = 0; i < grades.Length; i++)
{
Console.Write("Enter the grade of student {0}:", i + 1);
grades[i] = double.Parse(Console.ReadLine());
}
}
static double GetGradesSum(double[] grades)
{
double sum = 0;
for(int i = 0; i < grades.Length; i++)
sum += grades[i];
return sum;
}
}
Hi everyone,
Why does the for loop in the GetGradeSum method not require {}? When I do put the braces in, there is a compile time errors of "unreachable code detected" and "not all code paths return a value. Does it have something to do with the return function?
Thanks in advance!
Why does the for loop in the GetGradeSum method not require {}?
Because its body is a single statement. It's much simpler to understand if you indent your code properly. Your current code is more clearly written as:
static double GetGradesSum(double[] grades)
{
double sum = 0;
for(int i = 0; i < grades.Length; i++)
sum += grades[i];
return sum;
}
Note how the return
statement is not part of the loop. If it were, it would return the first grade, rather than the sum.
So the equivalent code with braces is:
static double GetGradesSum(double[] grades)
{
double sum = 0;
for(int i = 0; i < grades.Length; i++)
{
sum += grades[i];
}
return sum;
}
It sounds like you tried to put braces around both statements, so:
// Broken
static double GetGradesSum(double[] grades)
{
double sum = 0;
for(int i = 0; i < grades.Length; i++)
{
sum += grades[i];
return sum;
}
}
At this point, the compiler complains because it's entirely possible to reach the end of the method without returning anything - if grades
has a length of 0, we'll never go into the body of the loop, so never return.
Note that LINQ makes all of this irrelevant anyway, mind you - you can just write:
using System.Linq;
...
double sumGrades = listOfGrades.Sum();
See more on this question at Stackoverflow