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;
}