Error trying to pass ticket [i] = i;

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

    
asked by anonymous 25.05.2015 / 15:42

1 answer

4

Your array is declared as having 5 items:

int[] ticket = new int[5];  

The problem with your code is to assume that the first item in the array is indexed 1.
Array indices in C # and most languages start at 0.

As for your for the code will access index item 5 which goes beyond the length of the array.

Change your for cycle to:

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

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

for(int i = 0; i < ticket.Length; i++)
    
25.05.2015 / 15:54