Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I quicky fill an array with a specific value?

Tags:

arrays

.net

Array.Clear() fills the arrays with the default value (zero for integers), I would like to fill it using -1 for example.

Thanks.

like image 975
abenci Avatar asked Feb 23 '11 09:02

abenci


People also ask

How do you populate an entire array with a certain value?

Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.

How do you fill an element in an array?

The fill() method fills specified elements in an array with a value. The fill() method overwrites the original array. Start and end position can be specified. If not, all elements will be filled.

How do you fill an array with user input?

To read data from user create a scanner class. Read the size of the array to be created from the user using nextInt() method. Create an array with the specified size. In the loop read the values from the user and store in the array created above.


1 Answers

The other way is:

int[] arr =  Enumerable.Repeat(-1, 10).ToArray();
Console.WriteLine(string.Join(",",arr));
like image 187
apros Avatar answered Oct 02 '22 15:10

apros