How to make the array size a ReadLine? - c#

I'm trying to make a sorting algorithm and asking the user to input the array size is a must. I am a beginner in C# so I don't have any idea how to do that.
This is the idea that came to my mind, but I'm having an error.
Console.WriteLine("Enter how many elements you want to be sorted:");
a = Convert.ToInt32(Console.ReadLine());
int[] MyArray= new int[a] {""};
Visual Studio says that 'a constant value is expected'. How could I make the array length a ReadLine? My goal is for the user to decide which array length they want the program to show and that the elements inside the array would be system generated based on the array length that the user chose.

You can initialise an array like this:
int[] MyArray= new int[a];
But, I would also point out, that you could use a dynamic collection (such as a list), then you don't need to ask up front how many items, you just keep adding items until the user decides to stop.
ICollection<int> myCollection = new List<int>();
myCollection.Add(1);
myCollection.Add(1);

The type of your array is int but you are trying to initialize it with an empty string. In C# you can declare an array in a few ways. You can declare it by providing a size as in:
int[] myArray = new int[size];
And initialize the values later.
An alternative is to instantly intialize it with values like this:
int[] myArray = new int[] { 1, 2, 3 };
Note that when using the second option, you shouldn't provied the size as the compiler will infere it.

Related

Find compressed total ZipFile size in KB (not length) [duplicate]

How can I determine size of an array (length / number of items) in C#?
If it's a one-dimensional array a,
a.Length
will give the number of elements of a.
If b is a rectangular multi-dimensional array (for example, int[,] b = new int[3, 5];)
b.Rank
will give the number of dimensions (2) and
b.GetLength(dimensionIndex)
will get the length of any given dimension (0-based indexing for the dimensions - so b.GetLength(0) is 3 and b.GetLength(1) is 5).
See System.Array documentation for more info.
As #Lucero points out in the comments, there is a concept of a "jagged array", which is really nothing more than a single-dimensional array of (typically single-dimensional) arrays.
For example, one could have the following:
int[][] c = new int[3][];
c[0] = new int[] {1, 2, 3};
c[1] = new int[] {3, 14};
c[2] = new int[] {1, 1, 2, 3, 5, 8, 13};
Note that the 3 members of c all have different lengths.
In this case, as before c.Length will indicate the number of elements of c, (3) and c[0].Length, c[1].Length, and c[2].Length will be 3, 2, and 7, respectively.
You can look at the documentation for Array to find out the answer to this question.
In this particular case you probably need Length:
int sizeOfArray = array.Length;
But since this is such a basic question and you no doubt have many more like this, rather than just telling you the answer I'd rather tell you how to find the answer yourself.
Visual Studio Intellisense
When you type the name of a variable and press the . key it shows you a list of all the methods, properties, events, etc. available on that object. When you highlight a member it gives you a brief description of what it does.
Press F1
If you find a method or property that might do what you want but you're not sure, you can move the cursor over it and press F1 to get help. Here you get a much more detailed description plus links to related information.
Search
The search terms size of array in C# gives many links that tells you the answer to your question and much more. One of the most important skills a programmer must learn is how to find information. It is often faster to find the answer yourself, especially if the same question has been asked before.
Use a tutorial
If you are just beginning to learn C# you will find it easier to follow a tutorial. I can recommend the C# tutorials on MSDN. If you want a book, I'd recommend Essential C#.
Stack Overflow
If you're not able to find the answer on your own, please feel free to post the question on Stack Overflow. But we appreciate it if you show that you have taken the effort to find the answer yourself first.
for 1 dimensional array
int[] listItems = new int[] {2,4,8};
int length = listItems.Length;
for multidimensional array
int length = listItems.Rank;
To get the size of 1 dimension
int length = listItems.GetLength(0);
yourArray.Length :)
With the Length property.
int[] foo = new int[10];
int n = foo.Length; // n == 10
For a single dimension array, you use the Length property:
int size = theArray.Length;
For multiple dimension arrays the Length property returns the total number of items in the array. You can use the GetLength method to get the size of one of the dimensions:
int size0 = theArray.GetLength(0);
In most of the general cases 'Length' and 'Count' are used.
Array:
int[] myArray = new int[size];
int noOfElements = myArray.Length;
Typed List Array:
List <int> myArray = new List<int>();
int noOfElements = myArray.Count;
it goes like this:
1D:
type[] name=new type[size] //or =new type[]{.....elements...}
2D:
type[][]name=new type[size][] //second brackets are emtpy
then as you use this array :
name[i]=new type[size_of_sec.Dim]
or You can declare something like a matrix
type[ , ] name=new type [size1,size2]
What has been missed so far is what I suddenly was irritated about:
How do I know the amount of items inside the array? Is .Length equal .Count of a List?
The answer is: the amount of items of type X which have been put into an array of type X created with new X[number] you have to carry yourself!
Eg. using a counter: int countItemsInArray = 0 and countItemsInArray++ for every assignment to your array.
(The array just created with new X[number] has all space for number items (references) of type X already allocated, you can assign to any place inside as your first assignment, for example (if number = 100 and the variable name = a) a[50] = new X();.
I don't know whether C# specifies the initial value of each place inside an array upon creation, if it doesn't or the initial value you cannot compare to (because it might be a value you yourself have put into the array), you would have to track which places inside the array you already assigned to too if you don't assign sequentially starting from 0 (in which case all places smaller than countItemsInArray would be assigned to).)
In your question size of an array (length / number of items) depending on whether / is meant to stand for "alternative" or "divide by" the latter still has to be covered (the "number of items" I just gave as "amount of items" and others gave .Length which corresponds to the value of number in my code above):
C# has a sizeof operator (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof). It's safe to use for built-in types (such as int) (and only operates on types (not variables)). Thus the size of an array b of type int in bytes would be b.Length * sizeof(int).
(Due to all space of an array already being allocated on creation, like mentioned above, and sizeof only working on types, no code like sizeof(variable)/sizeof(type) would work or yield the amount of items without tracking.)

dynamic array does not working properly

I take dynamic array as
double[] array = new double[10];
I put some values in it in run time, but if user put less then
10 values like if user put 5 values in it instead of 10.
After that when i display the array first it's show the five value
and after that start displaying 0 0 0 0 0. I just want to know is there any method
to get rid of using dynamic array in c#?
double[10] is not a dynamic array. It's fixed length to 10 entries.
Try using List<double> instead. It's actually dynamic.
https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
If I intend correctly, I think you may be looking for something like this:
var list = new List<double>();
list.Add(1.1);
list.Add(2.2);
list.Add(3.4);
list.Add(4.8);
list.Add(5.0);
var array = list.ToArray();
//here you can see that array has a length of 5
System.Diagnostics.Debug.WriteLine($"My array contains {array.Length}.");

Storing lots of Arrays into a List on every Loop

I have a question about storing lots of arrays into a list.
First, I initialize the array and list:
int[] arr = new int[9];
List<int[]> forkarr = new List<int[]>();
then I run through a lot of for loops and modify the array each time in order to produce all possible tic tac toe variations. While looping through all those variations, if the array is a possible board then I print it, and additionally if the array meets certain criteria for being a 'fork', then I will add it to the list like this:
if (ForkCheck.fork(arr)) { forkarr.Add(arr); Console.WriteLine("It's a Fork!");}
which also prints that message letting you know that particular array is a fork.
Now, when I am printing all of the arrays, the ones that are forks are printed properly and labeled as such.
However, when I go to print out all of the int[] elements of my list forkarr like so:
foreach (int[] arry in forkarr)
{
PrintGame.print(arry);//this is my method that prints the array
Console.WriteLine();
}
for some reason each array becomes an identical:
222
222
222
(I'm using 2 as 'X' and 1 as 'O' and 0 as 'empty' btw)
And it just prints that out over and over for all the forks.
So, something is going wrong when I am adding each modification of the array as a new element in the list I think, but I'm not sure why.
Thanks for any help.
Because you are modifying the same array and adding it to the list. Each time you done with one array array you need to create a new instance like this:
arr = new int[9];
This will create a new reference which will be independent from other arrays. And modifying it's elements wont affect the others.
For more information about value vs reference types you can refer to the question below:
What is the difference between a reference type and value type in c#?

Why changing one array changes another array in C#?

I have a two dimensional array namely States in C#. I build a one dimensional array, namely SubState, from States. When I change SubState, States changes too. I want States be unchanged. Thanks
int[] SubState = State [0];
SubState[0]-=1; //State[0][0] is also changed here
In my mind your State definition is:
int[][] State;
Array is a reference type and when you copy an element from the State array you get a reference to the array from the first list and the both references map to the same int[] array. So when you change array stored at SubArray you use a link to the same array.
The simple fix is a copy of the source array
var SubState = State[0].ToArray();
That is because when you assign the array you pass its reference you are not making a copy of it. Look at the msdn link on the array copy method https://msdn.microsoft.com/en-us/library/System.Array.Copy(v=vs.110).aspx
int[] SubState = State [0]; is just another reference to the state array and so can be changed via it as well.
What you probably want to do, is create a separate array from the state array like
int[] substate = new int[state.GetLength(0)];
state.CopyTo(substate, 0);
You are not building a new one-dimensional array. You are simply creating a new reference to the first row of your two-dimensional array. If you actually want to build a new one-dimensional array, you have to iteratively copy the first row of your two-dimensional array.
Try:
int[] SubState = new int[States[0].length];
States[0].CopyTo(SubState, 0);
instead of
int[] SubState = State [0];
try
int[] SubState = new int[State[0].Length];
Array.Copy(State[0],Substate, Substate.Length)
So you are not simply assigning a new reference, but are actually copying the array correctly
Obviously your element at position 0 of State is an array of int which is a reference-type. Thus both SubState and State reference the same array which is why changes to any of their elements are reflected by both. To overcome this problem you may create a copy of your State-array and copy its values to SubState:
States.CopyTo(SubStates, 0);
EDIT: Thius assumes that SubStates was already initialized with the same size as States. e.g:
int[] SubStates = new int[States[0].Length];

C#: Is there a way to resize an array of unknown type using reflection?

My users pass me an array of some type, say int[] or string[]. I can easily query the types of the elements via GetElementType, and I can find out how long the array was when it was passed to me via GetRank, GetLength, etc.
The arrays are passed in a params list, so visualize code like this:
public void Resizer(params object[] objs)
{
foreach (object o in objs)
Array.Resize(ref o, 3);
}
What I would like to do is the converse of the Get methods that are available and that do work: I want to resize the array that was passed to me, setting the length to some other length (like 3 in this silly example).
I'm doing this because in my setting the array will contain data received from a set of cloud computing servers and we can't know how many will respond in advance, hence can't preallocate the array to have the right length. Ideally, in fact, my user passes in an array of length 0, and I pass back an array of length n, signifying that I got n replies from the servers that were queries.
I can't do this with Array.Resize(ref T, int) because I don't know T at compile time.
Is there a way to pull this off?
This should work:
static void Resize(ref Array array, int newSize) {
Type elementType = array.GetType().GetElementType();
Array newArray = Array.CreateInstance(elementType, newSize);
Array.Copy(array, newArray, Math.Min(array.Length, newArray.Length));
array = newArray;
}
Why not just create a new array of whichever type you need that is the size that you want? Then populate it from the array you want to resize, setting non existent values to some default.
In case anyone is curious, I ended up switching my code to use List
I agree with the comments that you should be using List(Of T), but if you want to copy your array into a new array of the same type, you could do something like the following.
// Your passed in array.
object[] objs = new object[5] {1,2,3,4,5};
// Create an array of the same type.
Array a = Array.CreateInstance(objs[0].GetType(), objs.Length+3);
// Copy in values.
objs.CopyTo(a,0);
I guess I'll just switch to using Lists, but this is a shame; the code will be quite a bit messier looking and since my users are basically at the level of first-semester ugrads, each little thing will make their lives less good. But I'm suspecting that you folks don't see a way to do this either. Oh well....

Categories