Introduction to Arrays in C#
An array is a list of items or collection of elements which is of same or
similar data type (homogenous elements).
An array is a collection of elements of a single data type stored in
adjacent memory locations.
An array is a collection of related values placed in contiguous memory
locations and these values are referenced using a common array name.
An array simplifies the task of maintaining these values
An array always stores values of a single data type.
Each value is referred to as an element.
These elements are accessed using subscripts or index numbers that
determine the position of the element in the array list.
C# supports zero-based index values in an array.
This means that the first array element has an index number zero while
the last element has an index number n-1, where n stands for the total
number of elements in the array.
This arrangement of storing values helps in efficient storage of data, easy
sorting of data, and easy tracking of the data length.
Create an Array in C#
Syntax
data_type [] name_of_array
Declaration of an Array:
class Name
{
static void Main(string[]args)
{
Int32[] intarray; //array declaration
}
}
Array Initialization:
class Name
{
static void Main(string[]args)
{
Int32[] Intarray; //array declaration
Intarray = new Int32[4]; // array initialization
Intarray[0]= 23; // assigning values to the elements
Intarray[1]=5;
Intarray[2]=88;
Intarray[3]=6;
}
}
Displaying values of Array:
class Name
{
static void Main(string[]args)
{
Int32[] Intarray; //array declaration
Intarray = new Int32[4]; //array initialization
Intarray[0]= 23; //assigning values to array
Intarray[1]=5;
Intarray[2]=88;
Intarray[3]=6;
Console.WriteLine(Intarray[0]);
Console.WriteLine(Intarray[1]);
Console.WriteLine(Intarray[2]);
Console.WriteLine(Intarray[3]);
Console.ReadKey();
}
}
Examples:
using System;
namespace ArrayDemo
{
class Name
{
static void Main(string[] args)
{
Int32[] Intarray; // array declaration
Intarray = new Int32[4]; // array initialization
Intarray[0] = 23; // assigning values to the array element
Intarray[1] = 5;
Intarray[2] = 88;
Intarray[3] = 6;
Console.WriteLine(Intarray[0]);
Console.WriteLine(Intarray[1]);
Console.WriteLine(Intarray[2]);
Console.WriteLine(Intarray[3]);
Console.ReadKey();
}
}
}
Example - 2:
using System;
namespace Demo
{
class Array
{
static void Main(string[] args)
{
int[] arr = new int[4] { 10, 20, 30, 40 };
for (int i = 0; i < arr.Length; i++) // Traverse array elements
{
Console.WriteLine(arr[i]);
}
}
}
}
Example - 3:
using System;
namespace Demo
{
class Array
{
static void Main(string[] args)
{
int[] arr = new int[4] { 10, 20, 30, 40 };
foreach (int i in arr)
{
Console.WriteLine(i);
}
}
}
}
Types of Array in C#:
1. Single dimension array.
2. Multi-dimension array.
3. Jagged array.
Multi-dimension Array
Multi-dimensional arrays, data is stored in tabular form. In a multidimensional array, each element of the array is
also an array.
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.
Two-Dimensional Array Declaration
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.
Two-Dimensional Array initialization
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
int [ , ] x = new int[2, 3]{ {1, 2, 3}, {3, 4, 5} };
Access Elements from 2D Array
// 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
Example:
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]);
}
}
}
Change Array Elements
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]);
}
}
}
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();
}
}
}
}Note:
numbers.GetLength(0) - gives the number of rows in a 2D array
numbers.GetLength(1) - gives the number of elements in the row
Example:
using System;
namespace TwoDimensionalArayDemo
{
class Program
{
static void Main(string[] args)
{
//Creating a 2D Array with 4 Rows and 5 Columns
int[,] RectangleArray = new int[4, 5];
int a = 0;
//Printing the values of 2D array using foreach loop
//It will print the default values as we are not assigning any values to the array
foreach (int i in RectangleArray)
{
Console.Write(i + " ");
}
Console.WriteLine("\n");
//Assigning values to the 2D array by using nested for loop
for (int i = 0; i < RectangleArray.GetLength(0); i++)
{
for (int j = 0; j < RectangleArray.GetLength(1); j++)
{
a += 5;
RectangleArray[i, j] = a;
}
}
for (int i = 0; i < RectangleArray.GetLength(0); i++)
{
for (int j = 0; j < RectangleArray.GetLength(1); j++)
{
Console.Write(RectangleArray[i, j] + " ");
}
}
Console.ReadKey();
}
}
}
2D Array Declaration and Initialization at the Same Statement:
using System;
namespace TwoDimensionalArayDemo
{
class Program
{
static void Main(string[] args)
{
//Assigning the Array Elements at the time of declaration
//Row Size: 3
//Column Size: 4
int[,] NumbersArray = {{11,12,13,14},{21,22,23,24},{31,32,33,34}};
//Printing Array Elements using for each loop
Console.WriteLine("Printing Array Elements using ForEach loop");
foreach (int i in NumbersArray)
{
Console.Write(i + " ");
}
//Printing Array Elements using nested for each
Console.WriteLine("\n\nPrinting Array Elements using Nested For Loop");
for (int i = 0; i < NumbersArray.GetLength(0); i++)
{
for (int j = 0; j < NumbersArray.GetLength(1); j++)
{
Console.Write(NumbersArray[i, j] + " ");
}
}
Console.ReadKey();
}
}
}
Program to Add 2 Matrices using C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Addmatrices
{
class Program
{
static void Main(string[] args)
{
int i, j, n;
int[,] arr1 = new int[50, 50];
int[,] brr1 = new int[50, 50];
int[,] crr1 = new int[50, 50];
Console.Write("\n\naddition of two Matrices :\n");
Console.Write("-----------------------------------------\n");
Console.Write("Input the size of the square matrix (less than 5): ");
n = Convert.ToInt32(Console.ReadLine());
/* Stored values into the array*/
Console.Write("Input elements in the first matrix :\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write("element - [{0},{1}] : ", i, j);
arr1[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.Write("Input elements in the second matrix :\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write("element - [{0},{1}] : ", i, j);
brr1[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.Write("\nThe First matrix is :\n");
for (i = 0; i < n; i++)
{
Console.Write("\n");
for (j = 0; j < n; j++)
Console.Write("{0}\t", arr1[i, j]);
}
Console.Write("\nThe Second matrix is :\n");
for (i = 0; i < n; i++)
{
Console.Write("\n");
for (j = 0; j < n; j++)
Console.Write("{0}\t", brr1[i, j]);
}
/* calculate the sum of the matrix */
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
crr1[i, j] = arr1[i, j] + brr1[i, j];
Console.Write("\nThe Addition of two matrix is : \n");
for (i = 0; i < n; i++)
{
Console.Write("\n");
for (j = 0; j < n; j++)
Console.Write("{0}\t", crr1[i, j]);
}
Console.Write("\n\n");
Console.ReadKey();
}
} }
C# Jagged Arrays
A jagged array in C# is an array of arrays, where each sub-array can have a different length. This
makes jagged arrays very flexible, allowing you to store and manipulate data of varying sizes and
dimensions.
Here's an example of a jagged array in C# that stores the grades of a classroom of students:
int[][] grades = new int[3][];
grades[0] = new int[] { 85, 76, 90, 89 };
grades[1] = new int[] { 92, 88, 94 };
grades[2] = new int[] { 75, 80, 82, 77, 90 };
In this example, we've created a jagged array grades with three sub-arrays. The first sub-array
contains four grades, the second sub-array contains three grades, and the third sub-array contains
five grades. Notice that we didn't have to specify the length of each sub-array when we declared the
grades array; instead, we created each sub-array separately and assigned it to the appropriate
element of the grades array.
To access an element in a jagged array, you need to use two sets of square brackets. The first set of
brackets specifies the index of the sub-array you want to access, and the second set of brackets
specifies the index of the element within that sub-array.
For example, to access the grade 76 in the first sub-array of the grades array, you would use the
following code:
int x = grades[0][1];
Jagged arrays can be useful in a variety of situations, such as storing data from a database query or
representing a grid of values where each row may have a different number of columns. They also have
the advantage of being more memory-efficient than multidimensional arrays, since they only allocate
memory for the sub-arrays that are actually needed. However, accessing elements in a jagged array
can be slightly slower than accessing elements in a multidimensional array, since it requires an extra
level of indirection.
Introduction to String Array in C#
In C#, a string array is an array of strings, where each element of the array is a string. Here's an
example of a string array in C# that stores the names of several colors:
string[] colors = new string[] { "red", "green", "blue", "yellow" };
In this example, we've created a string array colors with four elements, each of which is a string that
represents a color. Notice that we used the new keyword to allocate memory for the array and
initialize its elements all in one step.
You can access an element in a string array by using its index, which is an integer value that
represents its position in the array. For example, to access the third element of the colors array (which
is the string "blue"), you would use the following code:
string color = colors[2];
You can also change the value of an element in a string array by assigning a new string value to it. For
example, to change the value of the second element of the colors array to "purple", you would use
the following code:
colors[1] = "purple";
C# Multidimensional Arrays
A multidimensional array in C# is an array of arrays, where each element of the array is itself an array.
A two-dimensional array, for example, is an array of rows, where each row is an array of columns.
Here's an example of a two-dimensional array in C# that stores the grades of a classroom of students:
int[,] matrix = new int[3, 4]
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
In this example, we've created a two-dimensional array matrix with 3 rows and 4 columns. Each row
represents a set of numbers and each column represents a specific value. The values of the array have
been initialized to the numbers 1 through 12.
We can access specific elements of the array using their indices like this:
int value = matrix[0, 2]; // This gets the value in row 0, column 2 (which is 3)
We can also modify elements of the array by assigning new values to them:
matrix[1, 3] = 20; // This sets the value in row 1, column 3 to 20
We can even use loops to iterate through the elements of the array and perform operations on them:
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
Console.Write(matrix[i, j] + " ");
Console.WriteLine();
This code uses a nested for loop to iterate through each element of the array and print its value to the
console. The GetLength method is used to get the length of each dimension of the array, which allows
us to iterate through all the elements even if we don't know the exact size of the array.