0% found this document useful (0 votes)
42 views9 pages

C# Array Basics and Examples

This document provides an overview of arrays in C#, including how to create, initialize, access, iterate through, and perform operations on array elements. The key points covered are: - Arrays allow storing multiple values of the same type under one variable name. - C# arrays can be initialized during declaration or by allocating memory later. - Elements are accessed via indexes that start at 0. - Loops can iterate through all elements. - The System.Linq namespace provides methods to find min, max, average and other operations. - Multidimensional arrays have elements that are also arrays, like a table with rows and columns.

Uploaded by

Sarah Saban
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views9 pages

C# Array Basics and Examples

This document provides an overview of arrays in C#, including how to create, initialize, access, iterate through, and perform operations on array elements. The key points covered are: - Arrays allow storing multiple values of the same type under one variable name. - C# arrays can be initialized during declaration or by allocating memory later. - Elements are accessed via indexes that start at 0. - Loops can iterate through all elements. - The System.Linq namespace provides methods to find min, max, average and other operations. - Multidimensional arrays have elements that are also arrays, like a table with rows and columns.

Uploaded by

Sarah Saban
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C# Arrays

In this tutorial, we will learn about C# arrays. We will learn to create, initialize, and access array with the help of examples.

An array is a collection of similar types of data. For example,

Suppose we need to record the age of 5 students. Instead of creating 5 separate variables, we can simply create an array:

Elements of an Array

1. C# Array Declaration
In C#, here is how we can declare an array.

datatype[] arrayName;

Here,

dataType - data type like int, string, char, etc

arrayName - it is an identifier

Let's see an example,

int[] age;

Here, we have created an array named age. It can store elements of int type.

But how many elements can it store?

To define the number of elements that an array can hold, we have to allocate memory for the array in C#. For example,

// declare an array

int[] age;

// allocate memory for array

age = new int[5];

Here, new int[5] represents that the array can store 5 elements. We can also say the size/length of the array is 5.

Note: We can also declare and allocate the memory of an array in a single line. For example,

int[] age = new int[5];

2. Array initialization in C#
In C#, we can initialize an array during the declaration. For example,

int [] numbers = {1, 2, 3, 4, 5};

Here, we have created an array named numbers and initialized it with values 1, 2, 3, 4, and 5 inside the curly braces.

Note that we have not provided the size of the array. In this case, the C# automatically specifies the size by counting the number of elements in
the array (i.e. 5).

In an array, we use an index number to determine the position of each array element. We can use the index number to initialize an array in C#.
For example,

// declare an array

int[] age = new int[5];

//initializing array

age[0] = 12;

age[1] = 4;

age[2] = 5;

...
C# Array Initialization

Note:

An array index always starts at 0. That is, the first element of an array is at index 0.

If the size of an array is 5, the index of the last element will be at 4 (5 - 1).

3. Access Array Elements


We can access the elements in the array using the index of the array. For example,

// access element at index 2

array[2];

// access element at index 4

array[4];

Here,

array[2] - access the 3rd element

array[4] - access the 5th element

Example: C# Array

using System;

namespace AccessArray {

class Program {

static void Main(string[] args) {

// create an array

int[] numbers = {1, 2, 3};

//access first element

[Link]("Element in first index : " + numbers[0]);

//access second element

[Link]("Element in second index : " + numbers[1]);

//access third element

[Link]("Element in third index : " + numbers[2]);

[Link]();

Output

Element in first index : 1

Element in second index : 2

Element in third index : 3

In the above example, we have created an array named numbers with elements 1, 2, 3. Here, we are using the index number to access elements
of the array.

numbers[0] - access first element, 1


numbers[1] - access second element, 2

numbers[3] - access third element, 3

4. Change Array Elements


We can also change the elements of an array. To change the element, we simply assign a new value to that particular index. For example,

using System;

namespace ChangeArray {

class Program {

static void Main(string[] args) {

// create an array

int[] numbers = {1, 2, 3};

[Link]("Old Value at index 0: " + numbers[0]);

// change the value at index 0

numbers[0] = 11;

//print new value

[Link]("New Value at index 0: " + numbers[0]);

[Link]();

Output

Old Value at index 0: 1

New Value at index 0: 11

In the above example, the initial value at index 0 is 1. Notice the line,

//change the value at index 0

numbers[0] = 11;

Here, we are assigning a new value of 11 to the index 0. Now, the value at index 0 is changed from 1 to 11.

5. Iterating C# Array using Loops


In C#, we can use loops to iterate through each element of an array. For example,

Example: Using for loop

using System;

namespace AccessArrayFor {

class Program {

static void Main(string[] args) {

int[] numbers = { 1, 2, 3};

for(int i=0; i < [Link]; i++) {

[Link]("Element in index " + i + ": " + numbers[i]);

}
[Link]();

Output

Element in index 0: 1

Element in index 1: 2

Element in index 2: 3

In the above example, we have used a for loop to iterate through the elements of the array, numbers. Notice the line,

[Link]

Here, the Length property of the array gives the size of the array.

We can also use a foreach loop to iterate through the elements of an array. For example,

Example: Using foreach loop

using System;

namespace AccessArrayForeach {

class Program {

static void Main(string[] args) {

int[] numbers = {1, 2, 3};

[Link]("Array Elements: ");

foreach(int num in numbers) {

[Link](num);

[Link]();

Output

Array Elements:

6. C# Array Operations using [Link]


In C#, we have the [Link] namespace that provides different methods to perform various operations in an array. For example,

Example: Find Minimum and Maximum Element

using System;

// provides us various methods to use in an array

using [Link];

namespace ArrayMinMax {

class Program {

static void Main(string[] args) {


int[] numbers = {51, 1, 3, 4, 98};

// get the minimum element

[Link]("Smallest Element: " + [Link]());

// Max() returns the largest number in array

[Link]("Largest Element: " + [Link]());

[Link]();

Output

Smallest Element: 1

Largest Element: 98

In the above example,

[Link]() - returns the smallest number in an array, 1

[Link]() - returns the largest number in an array, 98

Example: Find the Average of an Array

using System;

// provides us various methods to use in an array

using [Link];

namespace ArrayFunction {

class Program {

static void Main(string[] args) {

int[] numbers = {30, 31, 94, 86, 55};

// get the sum of all array elements

float sum = [Link]();

// get the total number of elements present in the array

int count = [Link]();

float average = sum/count;

[Link]("Average : " + average);

// compute the average

[Link]("Average using Average() : " + [Link]());

[Link]();

Output
Average : 59.2

Average using Average() : 59.2

In the above example, we have used

[Link]() to get the sum of all the elements of the array

[Link]() to get the total number of element present inside the array

We then divide the sum by count to get the average.

float average = sum / count;

Here, we have also used the [Link]() method of the [Link] namespace to get the average directly.

Note: It is compulsory to use the [Link] namespace while using Min(), Max(), Sum(), Count(), and Average() methods.

C# Multidimensional Array
In this tutorial, we will learn about the multidimensional array in C# using the example of two-dimensional array.

Before we learn about the multidimensional arrays, make sure to know about the single-dimensional array in C#.

In a multidimensional array, each element of the array is also an array. For example,

int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };

Here, x is a multidimensional array which has two elements: {1, 2, 3} and {3, 4, 5}. And, each element of the array is also an array
with 3 elements.

Two-dimensional array in C#

A two-dimensional array consists of single-dimensional arrays as its elements. It can be represented as a table with a specific number of rows
and columns.

C# Two-dimensional array

Here, rows {1, 2, 3} and {3, 4, 5} are elements of a 2D array.

1. Two-Dimensional Array Declaration

Here's how we declare a 2D array in C#.

int[ , ] x = new int [2, 3];

Here, x is a two-dimensional array with 2 elements. And, each element is also an array with 3 elements.

So, all together the array can store 6 elements (2 * 3).

Note: The single comma [ , ] represents the array is 2 dimensional.

2. Two-Dimensional Array initialization

In C#, we can initialize an array during the declaration. For example,

int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };

Here, x is a 2D array with two elements {1, 2, 3} and {3, 4, 5}. We can see that each element of the array is also an array.

We can also specify the number of rows and columns during the initialization. For example,

int [ , ] x = new int[2, 3]{ {1, 2, 3}, {3, 4, 5} };

3. Access Elements from 2D Array

We use the index number to access elements of a 2D array. For example,

// a 2D array
int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };

// access first element from first row

x[0, 0]; // returns 1

// access third element from second row

x[1, 2]; // returns 5

// access third element from first row

x[0, 2]; // returns 3

Elements of Two-Dimensional array in C#

Example: C# 2D Array

using System;

namespace MultiDArray {

class Program {

static void Main(string[] args) {

//initializing 2D array

int[ , ] numbers = {{2, 3}, {4, 5}};

// access first element from the first row

[Link]("Element at index [0, 0] : "+numbers[0, 0]);

// access first element from second row

[Link]("Element at index [1, 0] : "+numbers[1, 0]);

Output

Element at index [0, 0] : 2

Element at index [1, 0] : 4

In the above example, we have created a 2D array named numbers with rows {2, 3} and {4, 5}.

Here, we are using the index numbers to access elements of the 2D array.

numbers[0, 0] - access the first element from the first row (2)

numbers[1, 0] - access the first element from the second row (4)

Change Array Elements


We can also change the elements of a two-dimensional array. To change the element, we simply assign a new value to that particular index. For
example,

using System;

namespace MultiDArray {

class Program {

static void Main(string[] args) {

int[ , ] numbers = {{2, 3}, {4, 5}};

// old element

[Link]("Old element at index [0, 0] : "+numbers[0, 0]);

// assigning new value

numbers[0, 0] = 222;

// new element

[Link]("New element at index [0, 0] : "+numbers[0, 0]);

Output

Old element at index [0, 0] : 2

New element at index [0, 0] : 222

In the above example, the initial value at index [0, 0] is 2. Notice the line,

// assigning new value

numbers[0, 0] = 222;

Here, we are assigning a new value 222 at index [0, 0]. Now, the value at index [0, 0] is changed from 2 to 222.

Iterating C# Array using Loop

using System;

namespace MultiDArray {

class Program {

static void Main(string[] args) {

int[ , ] numbers = { {2, 3, 9}, {4, 5, 9} };

for(int i = 0; i < [Link](0); i++) {

[Link]("Row "+ i+": ");

for(int j = 0; j < [Link](1); j++) {

[Link](numbers[i, j]+" ");

[Link]();

}
}

Output

Row 0: 2 3 9

Row 1: 4 5 9

In the above example, we have used a nested for loop to iterate through the elements of a 2D array. Here,

[Link](0) - gives the number of rows in a 2D array

[Link](1) - gives the number of elements in the row

Note: We can also create a 3D array. Technically, a 3D array is an array that has multiple two-dimensional arrays as its elements. For example,

int[ , , ] numbers = { { { 1, 3, 5 }, { 2, 4, 6 } },

{ { 2, 4, 9 }, { 5, 7, 11 } } };

Here, [ , , ] (2 commas) denotes the 3D array.

Common questions

Powered by AI

In a single-dimensional array, elements are accessed with a single index indicating the position of the element, such as numbers[2]. In two-dimensional arrays, elements require two indices: one for the row and another for the column, e.g., numbers[0,2] accesses the third element in the first row. This two-index system in 2D arrays allows the representation and manipulation of data in a grid-like structure opposed to the linear form in single-dimensional arrays .

To change the value of an element in a 2D array in C#, assignment is used where you specify the indices of the element to change. For instance, numbers[0, 0] = 222 would change the value at the first row and first column to 222. The implication of changing this value is that the stored data at specified index is directly modified, impacting any operations or outputs relying on that specific array data structure .

Loops such as for and foreach in C# improve the efficiency of performing operations on arrays by allowing systematic iteration over each array element. For example, using a for loop, int[] numbers = {1,2,3}; for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); }, iterates through all elements. The foreach loop can simplify this to foreach(int num in numbers) {Console.WriteLine(num);}. These loops eliminate the need for manual element access, reduce potential errors, and facilitate operations like processing, transformation, or aggregating array data .

In C#, index numbers are used to assign initial values to specific positions in an array, allowing tailored initialization rather than a uniform solution. An example: int[] age = new int[5]; age[0] = 18; age[1] = 21; age[2] = 30; assigns specific values at specific indices, ensuring that each element is strategically initialized according to the program's requirements. Such an approach is helpful when individual data points need to be independently set, rather than assigning a contiguous range of values .

A foreach loop is often preferred over a for loop when ease of use and code readability are priorities. In scenarios where all array elements need processing without modification or access by index, foreach provides a straightforward construct, reducing manual index management, which can simplify code especially in larger applications, increasing maintainability. For example, processing an array simply to display values or perform operations on each item without altering them is efficiently handled via foreach, minimizing potential for index errors .

The System.Linq namespace provides methods like Min(), Max(), Sum(), Count(), and Average() which can greatly enhance operations on C# arrays by simplifying common data operations. For example, finding the largest or smallest element can be achieved with numbers.Max() or numbers.Min() without implementing extensive logic to compare elements. Similarly, Sum() can be used to calculate the total of all array elements, and Average() automatically computes the mean of array data. These operations enhance productivity and reduce code complexity, making System.Linq particularly useful in data-intensive applications that require frequent aggregation and calculation .

Indices in a 2D array are pivotal for accessing and modifying elements as they specify the position within the array's grid structure. Each element of a 2D array is identified through a pair of indices, corresponding to its row and column position, such as array[1,2] which accesses the element in the second row and third column. Modifying an element follows the same indexing method. Accurate use of indices ensures precise targeting of data operations, mitigating errors and preserving data integrity across operations .

When declaring and using arrays in C#, several limitations must be considered: arrays are of a fixed size, meaning once declared, their size cannot be dynamically adjusted. This necessitates prior knowledge or estimation of needed capacity, which can lead to inefficient memory use if miscalculated. Data type consistency within an array (all elements must be of the same data type) is another limitation. If diverse types are needed, alternative data structures like Lists or object arrays might be better. Also, array initialization at indices must account for zero-based indexing, to prevent out-of-range exceptions .

A 3D array in C# is declared with three sets of brackets, int[,,] numbers, representing an array of arrays, where each element can itself be a 2D array. This differs from a 2D array declared with two brackets int[,] x, representing a grid or table-like structure. Usage of 3D arrays involves accessing elements through three indices, such as numbers[0,0,0] to specify a particular point within the three-dimensional space. 3D arrays are especially useful for representing complex structures such as 3D space or layered data analysis requiring hierarchical or depth representation .

In C#, single-line array declaration and memory allocation is done by combining both actions in one statement, for instance, int[] age = new int[5]; where both the array declaration and the memory allocation for 5 integer elements happen simultaneously. On the other hand, multi-step declaration and allocation involves first declaring the array (e.g., int[] age;) and then separately allocating memory (age = new int[5];). This process highlights flexibility that separates the type declaration and the size of the array, which can be useful in scenarios where the size might be determined programmatically at runtime .

You might also like