0

Well I'm trying to write a program in which if you add for example 3 integers in the array, let's say 3 2 1, it will add them again after it so it becomes 321 321.

Here is the code I need to fix. And sorry for the stupid question I am a beginner with arrays.

I get this error

Index was outside the bounds of the array

My code:

using System;

public class Program
{
    public static void Main()
    {
        int arraylength = int.Parse(Console.ReadLine());
        int[] array = new int[arraylength];

        for (int i = 0; i < arraylength + 1 / 2; i++)
        {
            int typed = int.Parse(Console.ReadLine());
            array[i] = typed;

            if (i == arraylength / 2)
            {
                for (int a = arraylength + 1 / 2; a < arraylength + 1; a++)
                {
                    array[a] = typed;
                }
            }
        }
    }
}
8
  • which line causes the error? Commented Jan 20, 2018 at 18:21
  • Change it to a < arrayLenght instead of a < arrayLenght+1 since the arrayIndex is from 0 to arrayLenght so trying to do array[a] where a = arrayLenght will fail Commented Jan 20, 2018 at 18:22
  • (arraylenght + 1) / 2 Commented Jan 20, 2018 at 18:23
  • @Code-Apprentice error on line 14 (array[a] = typed) Commented Jan 20, 2018 at 18:26
  • 1
    This: arraylenght + 1 / 2 will equal arraylenght because it means arraylenght + (1 / 2) and 1/2 equals 0. I am pretty sure that is not what you meant. Commented Jan 20, 2018 at 18:26

1 Answer 1

3

Array indices in C# start at 0 and end at length - 1. You need to remove the + 1 from each of your for loop conditions:

for (int i = 0; i < arraylenght / 2; i++)

and

for (int a = (arraylenght + 1) / 2; a < arraylenght; a++)

I also suggest that you change arraylenght to arraylength. Since you probably autocompleted this every time you used it, the misspelling occurs consistently throughout your code and the compiler is satisfied. However, misspellings make it difficult for humans to read your code.

p.s. Your code doesn't do what you think it does. I suggest you step away from the computer for a moment and write in words what you are trying to accomplish. Describe each step of your solution in as much detail as you can. Then look at how your words match with the code you wrote. You will probably find that you do not need nested loops.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.