Error while trying to pass ticket[i] = i;

Asked

Viewed 35 times

3

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

namespace Testes
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] ticket = new int[5];
            string[] nome = new string[5];
            for(int i = 1; i < 6; i++)
            {
                Console.WriteLine("Bem vindo, digite seu nome: ");
                ticket[i] = i;
                nome[i] = Console.ReadLine();
                Console.WriteLine("Ticket número {0} do Sr. {1}", ticket[i], nome[i]);
                Console.WriteLine("Pressione Enter");

            }
            Console.ReadKey();
        }   
    }
}

The error that appears is:

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

  • The error occurs on the first run or correctly executes an x of iterations?

1 answer

4


Your array is declared to have 5 items:

int[] ticket = new int[5];  

The problem with your code is assuming that the first item in the array is Indice 1.
Arrays indices in C# and most languages start at 0.

The way your for the code will access the item Indice 5 which exceeds the array length.

Change your cycle for for:

for(int i = 0; i < 5; i++)  

One way to avoid this type of error is to use, on condition, the property Length of array:

for(int i = 0; i < ticket.Length; i++)

Browser other questions tagged

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