AlexAgla
AlexAgla

Reputation: 63

c# mark average calc issue

        Console.Write ("How many students do you have?: ");
        student = Convert.ToInt32 (Console.ReadLine ());

        int[] numberOfStudents = new int[student];

        for (int i = 1; i <= numberOfStudents.Length; i++) {
            Console.Write ($"Enter student {i}'s current grade: ");
            numberOfStudents [i] = Convert.ToInt16 (Console.ReadLine ());
        }

        int sum = 0;
        for(int i = 0; i < numberOfStudents.Length; i++)
        {
            sum += numberOfStudents[i];
        }

        average = sum / numberOfStudents.Length;

        Console.WriteLine ($"Your student average is {average}.");
        Console.ReadLine ();

Basically the user inputs the number of students and that determines the length of the array. The for loop gathers all the marks where the average is later calculated.

For some reason if the numberOfStudents length is 5 when the for loop gets to its fifth go around it ask for the student mark but when you enter it instead of getting the sum and calculating the average the program crashes with the system.indexoutofrange error.

Thanks for the help!

Upvotes: 0

Views: 981

Answers (2)

Aashish Kumar
Aashish Kumar

Reputation: 1643

In C# array starting index is 0 not 1 so you just need to initialize i in your first for loop with 0 and your code will work perfectly fine. Try below code:

    Console.Write ("How many students do you have?: ");
    student = Convert.ToInt32 (Console.ReadLine ());

    int[] numberOfStudents = new int[student];

    for (int i = 0; i <= numberOfStudents.Length; i++) {
        Console.Write ($"Enter student {i+1}'s current grade: ");
        numberOfStudents [i] = Convert.ToInt16 (Console.ReadLine ());
    }

    int sum = 0;
    for(int i = 0; i < numberOfStudents.Length; i++)
    {
        sum += numberOfStudents[i];
    }

    average = sum / numberOfStudents.Length;

    Console.WriteLine ($"Your student average is {average}.");
    Console.ReadLine ();

Upvotes: 6

Jite
Jite

Reputation: 5847

Arrays start on index 0, so the first for-loop will run out of bounds when trying to select the last value (as the i variable will go from index 1 => 6).

for (int i = 1; i <= numberOfStudents.Length; i++) { 
  // The i variable is starting on 1, loops til the index is greater than 5 (I.E., 6)
  Console.Write ($"Enter student {i}'s current grade: ");
  numberOfStudents [i] = Convert.ToInt16 (Console.ReadLine ());
  // On last fetch the variable i is 6, trying to fetch from array where last index is 5
  // will make the array throw an exception.
}

To fix this, you could either start the loop on index 0 and just loop it as you do in your second loop (for (i=0;i<numberOfStudents.Length;i++)) and then in your output add +1 to make the output start on 1 instead of 0.
Or by just changing the part where you fetch from the array to fetch i - 1.

Upvotes: 1

Related Questions