-1

i have a problem regarding my code. I have tried searching on it, but it only confused me more.

I want to split an array(called Array for simplicity) of size 6 in half. one of the halves will move to another array, called Split1

But it gives me an error when trying to move the numbers using a for loop.

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

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,,,,,] Array = new int[7, 5, 9, 4, 2, 1];
            int[] Split1 = new int[3];
            for (int i = 0; i <= Array.Length / 2; i++)
            {
                Split1[i] = Array[i]; //This is where i get my error
            }

        }
    }
}

If you could point me to the right direction, I would be grateful

Rickard B.
  • 534
  • 4
  • 13

5 Answers5

3

Initialize your array as

int[] Array = new int[6]{7, 5, 9, 4, 2, 1};

What you did before was attempt to create array with 6 dimensions and address one of its cell.

As others pointed out, in loop you want to count from 0 to 2, therefore change <= for <.

miroxlav
  • 10,935
  • 5
  • 48
  • 86
3

This

int[,,,,,] Array = new int[7, 5, 9, 4, 2, 1];

is not an array with 6 elements, this is a 6-dimentional array.

You should define your one dimensional array like this:

int[] Array = new int[] {7, 5, 9, 4, 2, 1};

Additionally, your loop condition is incorrect, you should use < to check upper bound instead of <=:

for (int i = 0; i < Array.Length / 2; i++)
dotnetom
  • 23,445
  • 9
  • 47
  • 52
1

You have wrong index with loop

for (int i = 0; i < Array.Length / 2; i++)
{
    Split1[i] = Array[i]; //This is where i get my error
}
Siamak Ferdos
  • 2,745
  • 2
  • 25
  • 51
1

The way you declare the Array is incorrect, see the following code.

int[] Array = new int[] {7, 5, 9, 4, 2, 1}; // initialization will set the size automatically
int[] Split1 = new int[3];
for (int i = 0; i < 3; i++)
{
    Split1[i] = Array[i];
}
Abdul Mateen Mohammed
  • 1,784
  • 1
  • 10
  • 19
1

1.) You can initialize 1D arrays in many ways :

        string[] array = new string[2]; // creates array of length 2, default values
        string[] array = new string[] { "A", "B" }; // creates populated array of length 2
        string[] array = { "A" , "B" }; // creates populated array of length 2 

In your case :

        int[] Array = new int[] {7, 5, 9, 4, 2, 1};

2.) Array.Length won't return number of elements inside array. You need Array.Count(). Refer this link for more detail.

        for (int i = 0; i <= Array.Count() / 2; i++)
        {
            Split1[i] = Array[i]; //This is where i get my error
        }
Community
  • 1
  • 1
Prince
  • 431
  • 3
  • 16