How to declare trust array in c#? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm beginner in c#,i want to declare this c# array:
double[] array1;
for(int i=0;i<10;i++)
array1[i]=i;
but get error and c# say change that array to this:
double[] array1={1.1,2.2};
but i have to use my first code,how can i solve that?thanks.

double[] array1; only defines the variable, but doesn't instantiate the array.
Do this:
double[] array1 = new double[10];
for(int i=0;i<10;i++)
array1[i]=i;

In .Net when you initialise an array, you need to provide a size so that memory can be allocated to it.
this is done as such
double[] array1 = new double[10];
It is also worth noting that Arrays are statically sized so once you create it with that size, if you want it changed you need to create a new array.

you can try this :
int a = 10; // the size you want
array1 = new double[a];
for (int i = 0; i < a; i++)
array1[i] = i;

You simply cannot use your first code because it's not allowed in C#.
An array needs to know its length when created, and that's why you need to specify its length when creating it.
Also, you must assign it because otherwise, array1 remains null, which means you'll get an error when trying to use it.
So you have two choices here:
double[] array1 = new double[10], which means "create an array with room for 10 elements and set each value to 0.0", or you say
double[] array1 = { 1.0, 2.0, ..., 10.0 };, which sets the length of the array to the number of the elements you specified, and its values to the ones you specified (1.0-10.0 in the example).

If you know exactly number of elements in array you should use arrays. If you're uncertain about that use collection List and cast it to array (or just use it as it is).
Array:
double[] array1 = new double[10];
for(int i=0;i<10;i++) array1[i]=i;
Collection (don't use it if you know length of your array) :
list<double> coll1 = new List<double>();
for(int i=0; i < unknownNumber; i++) coll1.Add(i);
double[] array1 = coll1.ToArray();

Related

What is the point of using the new operator when initialising an array? [duplicate]

This question already has answers here:
All possible array initialization syntaxes
(19 answers)
Closed 2 years ago.
When initialising new arrays in C#, you can use either
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
or
int[] array1 = { 1, 3, 5, 7, 9 };
Is there a use case in which you should use the new int[] version when instantiating an array instead of the shorthand variant?
Yes, This is mostly used when you are only declaring the array. For Example you want to take values from user, than you will just declare the array. You will declare the size of the array in the bracket as shown below. In this example, "6" is the size of array.
int[] array1 = new int [6]
Now Let's takes the value from user and stored it in the array.
for(int i = 0 ; i < array1.length ; i++)
{
array1[i] = int.parse(Console.ReadLine());
}
Now, In above Example, you can see that we have run the for loop till length of array. that is 6.
array1.length is the property of array that returns the length of the array.
int.Parse((Console.ReadLine()) will take the input of the user that will stored it in the ith index of the array.
In short, you can say that we use "new" keyword when we just have to declare the array and don't have to initialize the values.
I hope, it will help you.

Pop values off Stack<T> [duplicate]

This question already has answers here:
Adding items to a LIST<> of objects results in duplicate Objects when using a NEW in a Loop
(2 answers)
Closed 5 years ago.
So I'm trying to create a backtracking recursive algorithm for maze generation using the stack to store the coordinates of the last spot entered in an array of ints [x,y]. When I try to store the results of .Pop off the stack, it sets my variable for the first popped value but not off of the next.
public static void Main(string[] args)
{
//Your code goes here
Stack<int[]> myStack = new Stack<int[]>();
int[] pusher = new int[] {1,2};
myStack.Push(pusher);
pusher[0] = 3;
pusher[1] = 4;
myStack.Push(pusher);
while(myStack.Count > 0){
int[] test = myStack.Pop();
for(int i = 0; i < test.Length; i++){
Console.WriteLine(test[i]);
}
}
}
Wanted result would be that the console displays 3,4,1,2. Instead I'm getting back 3,4,3,4.
You are only creating one array - pusher. You are then simply replacing the numbers 1 and 2 at the indexes 0 and 1 of this array respectively.
If you create another array and add 3 and 4 to this one, you will get the expected results:
Stack<int[]> myStack = new Stack<int[]>();
int[] pusher = new int[] { 1, 2 };
myStack.Push(pusher);
int[] second = new int[2];
second[0] = 3;
second[1] = 4;
myStack.Push(second);
while (myStack.Count > 0)
{
int[] test = myStack.Pop();
for (int i = 0; i<test.Length; i++)
{
Console.WriteLine(test[i]);
}
}
Question answered by Lasse Vågsæther Karlsen in comments on question. Moving to answer.:
You're reusing the same array instance so you're in fact pushing the same array onto the stack twice. When you store 3 and 4 into the array you overwrite the 1 and 2 already there. Push does not make a copy of the array contents, only of the array reference, therefore you push the same array twice. If you want to push a copy, use myStack.Push(pusher.ToArray()); – Lasse Vågsæther Karlsen 4 hours ago

How do I remove elements from an array in First In First Out manner [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
C# beginner here...
I have
int[] numbers = new int[10];
I would like to add 50 numbers to this array. Once the array is full, the first added number will be removed and the new number will be added. I would like to display the last added number on the top of the array. Such as
[5,4,3,2,1...]
not
[1,2,3,4,5,...]
How can I achieve this?
Thanks in advance
This is what I have tried
....
dataArray = new int[10];
....
Queue<int> numbers = new Queue<int>();
....
if (numbers.Count == 10)
{
numbers.Dequeue();
}
numbers.Enqueue(i);
numbers.CopyTo(dataArray, numbers.Count);
I keep getting " Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection" error
Array.Copy provides good performance for what you're trying to accomplish.
int[] newArray = new int[10];
newArray[0] = 4; // new value
Array.Copy(numbers, 0, newArray, 1, numbers.Length - 1);
Be careful with array lengths though with this as any bound issues with throw exceptions.
I think you should be using queue and then you can convert it into array if you want
class Program
{
static void Main(string[] args)
{
const int CAPACITY = 10;
Queue<int> queue = new Queue<int>(CAPACITY);
for (int i = 0; i < 50; i++)
{
if (queue.Count == CAPACITY)
queue.Dequeue();
queue.Enqueue(i);
}
queue.ToArray();
Console.WriteLine(queue.Count);
Console.ReadKey();
}
}
Take a look at the generic Queue class, that has the functionality that you are looking for with FILO structure. Doing this just with arrays...
int[] numbers=new int[50];
for(int i=0; i<numbers.length; i++) numbers[i]=i;
//fill the array with 1, 2, 3, 4...
//To reverse this order, swap elements in reverse
//numbers.length-1 is the last index of the array
// j<numbers.length/2,each time you swap you change two values, so only done half the length of the array
for(int j=numbers.length-1; j>numbers.length/2; j--) swap(numbers, j, numbers.length-j);
//swaps the values of different indexes in the array
void swap(int[] array, int index1, int index2) {
int temp=array[index1];
array[index1}=array[index2];
array[index2}=temp;
}
This should reverse the arrays

How do I find number of values in array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an array and am trying to extract the vlaues. I have tried to find the length of the array, but as the array isnt always full the .length doesnt work for me. How do i work out how many values are stored in the array?
Heres the code;
int length = numbers.Length;
I have created the array in the main section of the code, I am trying to make a function that can get the values out of the code using a for loop. E.G
int number(i) = numbers[i]
so that the variable number[i] will become number0, and then assigned the value in the first row of the array
If you want to use array which is not always full, then you definitely should use List<T> instead of array, because list can contain variable number of items. With array you never can tell if default value (zero for integer) was assigned to array item, or item was not assigned at all. Getting list items count will look like list.Count.
Of course, you can get number of array items which have non-default value (but see above why it might be not good approach):
int[] array = { 1, 2, 0, 1, 5 };
int count = array.Count(i => i != default(int)); // 4
try foreach you do not need the length. Here is code:
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
foreach (int element in numbers)
{
System.Console.WriteLine(element);
}

Modify multi Dimensional array

I have an Array variable. I can use the Rank property to get the number of dimensions and I know that you can use a foreach to visit each element as if the array was flattened. However, I wish to modify elements and change element references. I cannot dynamically create the correct number of for loops and I cannot invalidate an enumerator.
EDIT
Thanks for the comments, sorry about the previous lack of clarity at the end of a long tiring day. The problem:
private void SetMultiDimensionalArray(Array array)
{
for (int dimension = 0; dimension < array.Rank; dimension++)
{
var len = array.GetLength(dimension);
for (int k = 0; k < len; k++)
{
//TODO: do something to get/set values
}
}
}
Array array = new string[4, 5, 6];
SetMultiDimensionalArray(array);
Array array = new string[2, 3];
SetMultiDimensionalArray(array);
I had another look before reading this page and it appears all I need to do is create a list of integer arrays and use the overloads of GetValue and SetValue -
Array.GetValue(params int[] indices)
Array.SetValue(object value, params int[] indices)
Everything seems clear now unless someone can suggest a superior method. svick has linked to this so I will accept this answer barring any further suggestions.
It's hard to tell what exactly do you need, because your question is quite unclear.
But if you have a multidimensional array (not jagged array) whose rank you know only at runtime, you can use GetValue() to get the value at specified indices (given as an array of ints) and SetValue() to set it.

Categories