I am making a simple program to study Vectors, when I run it appears the error "Index was Outside the Bounds of the array" on line 24

Asked

Viewed 28 times

0

using System;

public class Program
{
    public static void Main()
    {

         int i, n;

        Console.WriteLine("Entre com o número de Alunos: ");
        n = Convert.ToInt32(Console.ReadLine());

        String[] nome = new String [n];
        Double[] n1 = new Double[n];
        Double[] n2 = new Double[n];
        Double[] m = new Double[n];


        for (i=1; i<=n; i++);
        {
         Console.WriteLine("Entre com o seu nome: ");
         nome[i] = Console.ReadLine();
         Console.WriteLine("Entre com o a sua primeira nota: ");
         n1[i] = Convert.ToDouble(Console.ReadLine());
         Console.WriteLine("Entre com o a sua segunda nota: ");
         n2[i] = Convert.ToDouble(Console.ReadLine());

          m[i] = (n1[i] + n2[i])/2;

         Console.WriteLine("Seu nome é: {0} " , nome);
         Console.WriteLine("Sua média é: {0} " , m);

        }
    }
}

Error

Index was Outside the Bounds of the array

on line 24.

  • 1

    for has to go from 0 a n-1. Arrays always start at 0

1 answer

1

change your go

for (i=1; i<=n; i++);

for

for (i=0; i<n; i++);

The indices of array begin at 0, then at a array size 5, the indexes will be:

[0], [1], [2], [3], [4]

That is, it starts at 0, and ends at size -1

Your for current, would try to access:

[1], [2], [3], [4], [5]

since there is no position 5, the error is returned:

"The index was outside the matrix boundaries"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.