I have an array. int[] array = new int[10];
. I want to assign '0' to whole array without using loop means that 0 is to be stored in all of the indexes. How would i do it.
Using default values in initialization of array For double or float , the default value is 0.0 , and the default value is null for string. Type[] arr = new Type[capacity]; For example, the following code creates a primitive integer array of size 5 . The array will be auto-initialized with a default value of 0 .
int arr[10] = {5}; In the above example, only the first element will be initialized to 5. All others are initialized to 0. A for loop can be used to initialize an array with one default value that is not zero.
Arrays. fill() int[] arr = new int[10]; and int arr[10] = {0}; all use internal loops.
It will create an empty array object. This is still a perfectly valid object - and one which takes up a non-zero amount of space in memory. It will still know its own type, and the count - it just won't have any elements.
After creation all items of array will have default values, which is 0 for int. So, you don't need to do anything here.
From Arrays (C# Programming Guide):
The default values of numeric array elements are set to zero, and reference elements are set to null.
Also from C# Specification 12.2 Array creation
Elements of arrays created by array-creation-expressions are always initialized to their default value.
5.2 Default values
For a variable of a value-type, the default value is the same as the value computed by the value-type's default constructor
4.1.2 Default constructors
For sbyte, byte, short, ushort, int, uint, long, and ulong, the default value is 0.
but after assigning other values i want all the indexes to be 0 again so then how would i do it?
UPDATE: You can use Array.Clear
:
Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.
In your case:
Array.Clear(array, 0, array.Length);
Consider also to use List<int>
instead of array - it allows to add/remove items dynamically.
You don't need to do anything at all.
Since int
is a value type, all elements are initilialized to 0
as a default.
From Arrays (C# Programming Guide)
The default values of numeric array elements are set to zero, and reference elements are set to null.
ok if i want it to be assigned to 3 then how would i do it?
You can use for loop to assign them like;
int[] array = new int[10]; for(int i = 0; i < array.Length; i++) array[i] = 3;
If you want to give back their default values (which is 0
in this case), you can create a new array or you can use Array.Clear
method like;
Array.Clear(array, 0, array.Length);
If you really don't want to use any loop, you might need to use List<int>
instead an array. It has more functionality and it creates a clean list (without any default value).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With