Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
58 views

C# Array

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
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

C# Array

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
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

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

Console.WriteLine("Element in first index : " + numbers[0]);

//access second element

Console.WriteLine("Element in second index : " + numbers[1]);

//access third element

Console.WriteLine("Element in third index : " + numbers[2]);

Console.ReadLine();

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};

Console.WriteLine("Old Value at index 0: " + numbers[0]);

// change the value at index 0

numbers[0] = 11;

//print new value

Console.WriteLine("New Value at index 0: " + numbers[0]);

Console.ReadLine();

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 < numbers.Length; i++) {

Console.WriteLine("Element in index " + i + ": " + numbers[i]);

}
Console.ReadLine();

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,

numbers.Length

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};

Console.WriteLine("Array Elements: ");

foreach(int num in numbers) {

Console.WriteLine(num);

Console.ReadLine();

Output

Array Elements:

6. C# Array Operations using System.Linq


In C#, we have the System.Linq 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 System.Linq;

namespace ArrayMinMax {

class Program {

static void Main(string[] args) {


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

// get the minimum element

Console.WriteLine("Smallest Element: " + numbers.Min());

// Max() returns the largest number in array

Console.WriteLine("Largest Element: " + numbers.Max());

Console.ReadLine();

Output

Smallest Element: 1

Largest Element: 98

In the above example,

numbers.Min() - returns the smallest number in an array, 1

numbers.Max() - 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 System.Linq;

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 = numbers.Sum();

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

int count = numbers.Count();

float average = sum/count;

Console.WriteLine("Average : " + average);

// compute the average

Console.WriteLine("Average using Average() : " + numbers.Average());

Console.ReadLine();

Output
Average : 59.2

Average using Average() : 59.2

In the above example, we have used

numbers.Sum() to get the sum of all the elements of the array

numbers.Count() 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 numbers.Average() method of the System.Linq namespace to get the average directly.

Note: It is compulsory to use the System.Linq 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

Console.WriteLine("Element at index [0, 0] : "+numbers[0, 0]);

// access first element from second row

Console.WriteLine("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

Console.WriteLine("Old element at index [0, 0] : "+numbers[0, 0]);

// assigning new value

numbers[0, 0] = 222;

// new element

Console.WriteLine("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 < numbers.GetLength(0); i++) {

Console.Write("Row "+ i+": ");

for(int j = 0; j < numbers.GetLength(1); j++) {

Console.Write(numbers[i, j]+" ");

Console.WriteLine();

}
}

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,

numbers.GetLength(0) - gives the number of rows in a 2D array

numbers.GetLength(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.

You might also like