Home c# One-dimensional dynamic array C #

One-dimensional dynamic array C # [Duplicate]

Author

Date

Category

There is such a task:

random numbers ranging from -5 to 5 to decompose on two arrays: in
Some put only positive, in the second – only negative.
Numbers equal to ignore. Display all generated
Random numbers and elements of both arrays.

I can not figure out what a mistake and whether I do it in generally do

int p = 1;
int n = 1;
for (int i = 0; i & lt; 20; i ++)
{
  int [] poloz = new int [p];
  int [] otric = new int [n];
  int ch = random ();
  if (ch & gt; 0)
  {
    poloz [p - 1] = ch;
    P ++;
  }
  ELSE If (CH & LT; 0)
  {
    OTRIC [N - 1] = CH;
    N ++;
  }
}

Answer 1, Authority 100%

I think it is worth putting arrays outside the cycle body and ask them the size. If you need an array, then the option is only to change the size for each addition. Inside Array.Resize Allocation of the array of the new size and copying:

int p = 1;
int n = 1;
int [] poloz = new int [0];
int [] otric = new int [0];
for (int i = 0; i & lt; 20; i ++)
{
  int ch = random ();
  if (ch & gt; 0)
  {
    Array.Resize (Ref Poloz, P);
    poloz [p - 1] = ch;
    P ++;
  }
  ELSE If (CH & LT; 0)
  {
    Array.Resize (Ref Otric, N);
    OTRIC [N - 1] = CH;
    N ++;
  }
}

Answer 2, Authority 300%

You want to use a dynamic array, but in C # is really no such.
There are only data structures that are similar to the dynamic array

var poloz = new list & lt; int & gt; (15);
var otric = new list & lt; int & gt; (15);
for (int i = 0; i & lt; 20; i ++)
{
  int ch = random ();
  if (ch & gt; 0)
  {
    poloz.add (CH);
  }
  ELSE If (CH & LT; 0)
  {
    otric.add (CH);
  }
}

at the class list there is a count method – it is your “dynamic” size array

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions