0

I am new here please help me out. code is running but afterwards compailer is not printing anything and giving error of IndexOutOfRangeException.

class Program
    {
        static void Main(string[] args)
        {
            string brd = board();
            string[] sub = subjects();
            Console.WriteLine(brd);
            Console.WriteLine(sub);
            Console.ReadLine();
        }
        public static string board()
        {
            Console.WriteLine("Please Enter Board Name ");
            string Board = Console.ReadLine();
            return Board;
        }
        public static string[] subjects()
        {
            Console.WriteLine("Please Enter How many Subject Do you Want to input");
            int limit = System.Convert.ToInt32(Console.ReadLine());
            string[] Subjects = new string[limit];
            string[] index = new string[limit];
            for (limit = 1; limit <= index.Length; limit++)
            {
                Console.WriteLine("Please Enter Subject Name " + limit );
                Subjects[limit] = Console.ReadLine();
            }
            return Subjects;
        }
           }
haris.m
  • 11
  • 3
  • Arrays in NET start at index 0. If you read any tutorial about NET you can find this info everywhere – Steve Feb 20 '17 at 10:29
  • `for (limit = 1; limit <= index.Length; limit++)` should be `for (limit = 0; limit < index.Length; limit++)` – Mairaj Ahmad Feb 20 '17 at 10:29

2 Answers2

2

Change this:

for (limit = 1; limit <= index.Length; limit++)

to this:

for (limit = 1; limit < index.Length; limit++) // <= to <

Index is always lower than Length because indexing starts from 0 (not from 1). In your case it can be equal to Length.

Also, you start from second element. To start from first:

for (limit = 0; limit < index.Length; limit++) //limit = 0
Roman
  • 11,966
  • 10
  • 38
  • 47
0

Arrays are 0 indexed, so the first item to access will be at 0

Your for loop should start at 0 therefore.

e.g. Your for loop in the code should look like this.

for (limit = 0; limit < index.Length; limit++)
NotJarvis
  • 1,267
  • 11
  • 17