Error in program c# with vectors

Asked

Viewed 226 times

3

I’m having a problem on line 18 of this code that says:"There was an untreated "System.Indexoutofrangeexception" exception in Consoleapp19.exe The index was outside the matrix boundaries.

How to solve?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp19
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] x = new int[n];
            int contPar = 0, maior = 0;
            for (int i = 1; i<= x.Length; i++)
            {
                x[i] = int.Parse(Console.ReadLine());
                if(x[i]%2 == 0)
                {
                    contPar++;
                }
                if(x[i] > maior)
                {
                    maior = x[i];
                }
            }
            Console.WriteLine("O maior número é {0}", maior);
            Console.WriteLine("Existem {0} n°s pares", contPar);
        }
    }
}
  • Vectors start from Intel Zero. The problem is in the for header: (int i = 0; i< x.Length; i++)

2 answers

2

Two things you have to take into account.

  • Vectors in C# has as its first index zero.
  • Vectors in C# has as its last index Length - 1.

Aware of this:

   public static void Main(string[] args)
    {
        int n = int.Parse(Console.ReadLine());
        int[] x = new int[n];
        int contPar = 0, maior = 0;


        //As únicas modificações no seu código i começa em 0 e comparação entre
        // i e x.Length deixa de ser '<='  e passe a ser '<'
        // o que equivaleria i <= x.Length - 1
        for (int i = 0; i < x.Length; i++)
        {
            x[i] = int.Parse(Console.ReadLine());
            if(x[i]%2 == 0)
            {
                contPar++;
            }
            if(x[i] > maior)
            {
                maior = x[i];
            }
        }
        Console.WriteLine("O maior número é {0}", maior);
        Console.WriteLine("Existem {0} n°s pares", contPar);
    }

0

Vector indices range from 0 to n-1, being n the size. Therefore, int[] vetor = new int[3]; will have the items vetor[0], vetor[1] and vetor[2]

Your for goes from 1 to x.Length, then when you reach the last value, the x[n] will look for an index that does not exist in the vector.

Browser other questions tagged

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