I have to create a function to calculate the average age of a class of 50 students, here is my code
public class Student
{
public int[] age = new int[10];
Student()
{
age[0] = 17;
age[1] = 19;
age[2] = 17;
age[3] = 18;
age[4] = 17;
age[5] = 18;
age[6] = 18;
age[7] = 19;
age[8] = 17;
age[9] = 18;
}
}
class Program
{
public void averageAge(Student student)
{
foreach(int i in student.age)
{
int avgage = (i += i) / 2;
}
}
static void main (string[] args)
{
}
I got an error saying cannot assign to "i" it is a foreach iteration variable, any other way I can initialize this array for ages of students, cause I have to calculate average age of 50 students so assigning 50 different times feels a bit too redundant
I don't know what I was thinking using foreach in such a manner, I have swapped the foreach with for loop now like this:
public void averageAge(Student student)
{
int avgage = 0;
for (int i =0;i<50;i++)
{
avgage += student.age[i];
}
avgage /= 50;
}
int[] age = new int[] {10, 20, ... 50};listing out all the values to init your array. Note, you don't give the size of the array, it ends up as big as it needs to. Then initialize an int variable before your loopvar sum=0;and within the loop, do thissum+=i;. Then below the loopvar average=sum/student.age.Length;. I have no idea what you expectedint avgage = (i += i) / 2;to do. Oh yeah, and what does this have to do with the title of your question? Also note that my code does integer division (rounding down) if you want a result like 17.8, you'll need a castvar list = new List<int> { 1, 8, 3, 2 }; double result = list.Average();// result: 3.5