Friday, April 26, 2024 10:45

Table of contents >> Arrays > Initialization of arrays

Initialization of arrays

Like any other variables, arrays must be initialized before we can access and use an element of that array. In C#, initialization of arrays is done automatically with default initial values. For numeral types, the default initialization value is 0, False for bool type, null for reference types, etc.

In addition to the default initialization which happens when we declare our array, we can also initialize it explicitly. There are multiple ways through which we can perform the initialization of arrays. The most simple one is by combining the declaration and initialization in a single statement:

But in our previous lesson I said that initialization of arrays can be done this way:

So, why the difference? True, both statements produce an array of 6 elements of type integer. However, in the first example, we also assign specific values to our array elements, while in the second example, the array is populated with 6 integers, all having the default value of 0. Of course, we can combine the two examples, though this would be an unnecessary complication (since we can simply use our first example):

The concepts explained in this lesson are also shown visually as part of the following video:

EXERCISES
1. Write a program which creates an array of 20 elements of type integer and initializes each of the elements with a value equals to the index of the element multiplied by 5. Print the elements to the console.

Solution


Guidelines: Use an int[] array and afor loop.

2. Write a program which reads two arrays from the console and checks whether they are equal (two arrays are equal when they are of equal length and all of their elements, which have the same index, are equal).

Solution


Guidelines: Two arrays are equal if they have the same value for the length and the values for their elements. You can check for the second condition using a for-loop.

3. Sorting an array means to arrange its elements in an increasing (or decreasing) order. Write a program, which sorts an array using the algorithm “selection sort“.

Solution


Guidelines: The idea is to find the smallest element and to place it at position 0 (through swapping) then to find the smallest number excluding the first and place it at position 1 and so on, until the entire array is arranged in ascending order.

Tags: , ,

Leave a Reply



Follow the white rabbit