Error while traversing vector

Asked

Viewed 82 times

0

The user pastes the values that will be saved within the array and then displays these values. However, the following error is occurring:

An unhandled Exception of type 'System.Indexoutofrangeexception' occurred in vetoor.exe ".

My code is as follows:

namespace vetoor 
{
class Program
{
    static void Main(string[] args)
    {
        int[] vet = new int[3];
        int i,a;


        for (i = 0; i < vet.Length;  i++)
        {
            Console.WriteLine("Digite o numero");
            vet[i] = int.Parse(Console.ReadLine());

        }
        for(a=0; a<4; a++)
        {
            Console.WriteLine("{0}", vet[i]);
        }

        Console.ReadKey();
    }
}

}

  • 1

    Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

3 answers

3

You created a vector with 3 elements and even started well in the first loop going until reaching its size, although in this very specific case you do not need to do this. But then it was up to 3. The vector goes from 0 to 2. Changing the second condition to 3 will solve. Or always use the Length to avoid this problem. Perhaps the ideal was even to use foreach in place of for, but I guess you haven’t learned that yet.

But this code can be more organized and modernized:

using static System.Console;

namespace vetor {
    public class Program {
        public static void Main() {
            int[] vet = new int[3];
            for (int i = 0; i < vet.Length; i++) {
                WriteLine("Digite o numero: ");
                vet[i] = int.Parse(ReadLine());
            }
            for (int a = 0; a < vet.Length; a++) WriteLine($"{vet[a]}");
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Note that there is still a potential problem. When you ask someone to enter a value and have no control over it you cannot use Parse() because if typing cannot be converted it will generate an error. you will have to use TryParse().

2

The second is iterates over its vector up to index 3.

When accessing the vet[a] index when a is equal to 3, this exception is launched. This means that the vet vector does not have the 3.

This can be confusing at first, but although you have declared the vet vector with 3 positions, the index starts from 0. That is, the vet vector has only 0, 1 and 2.

0

my answer is based on error only.. I don’t know if you had any other doubts or not.. you also have an alternative to a.. foreach traversing a list/array

       namespace vetoor 
     {
    class Program
      {
    static void Main(string[] args)
{
    int[] vet = new int[3];
    int i,a;


    for (i = 0; i <= vet.Length;  i++)
    {
        Console.WriteLine("Digite o numero");
        vet[i] = int.Parse(Console.ReadLine());

    }
   // for(a=0; a<4; a++) -> a = 3 e a = 4 iria estar fora do vector
   // {
   //     Console.WriteLine("{0}", vet[i]);
   // }
   foreach(int num in vet){
    Console.WriteLine(num);
   }

    Console.ReadKey();
   }
 }

Browser other questions tagged

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