Definition of Array:

An array is a collection of elements of the same data type stored in contiguous memory locations. It allows you to store multiple values under a single name, and you can access each value by its index number. It allows programmers to store multiple values of the same data type, like integers or strings, instead of declaring separate variables for each value.

In arrays, each value is called an element, and every element can be easily accessed by its index number, which always starts from zero and goes up to size minus one. For example, if you declare an array of size 8, the valid indexes are 0, 1, 2, 3,4,5,6, and 7.

array index

Syntax:
Basic syntax  and example in C#:

Example: int[] marks = new int[8];

Array Declaration:

Declaring an array means telling the compiler or interpreter about the type of elements and the number of elements the array will hold. Example in C#:

int[] numbers; // Declares an array of integers 
int[] marks = new int[8]; // Declares and allocates memory for 8 integers

Here, int[] numbers; declares an integer array named numbers, but it doesn’t specify its size yet. int[] marks = new int[8]; declares and initializes an array named marks with space to store 8 integer values.

How to Access an Array Element:

To access an element of an array, you use the array name followed by the index number in square brackets [ ].
Remember that indexing starts from 0, so the first element is at index 0, the second at 1, and so on.Example

int[] num = { 2, 4, 6, 8, 10 };
// Access the first element
Console.WriteLine(num[0]); // Output: 2
// Access the third element
Console.WriteLine(num[2]); // Output: 6

Accessing an Array Element Using a for Loop:

A for loop is used when you want to access each element of the array one by one automatically.
The loop uses an index variable that starts from 0 and goes up to n-1 (where n is the size of the array. Example

int[] num = { 2, 4, 6, 8, 10 };
for (int i = 0; i < num.Length; i++)
{
Console.WriteLine(num[i]);  // Access element: arrayName[i]
}

Accessing an Array Element Using a For Loop:

You can access each element of an array by using a for loop. A for loop allows you to repeat a block of code for each index of the array. Inside the loop, you use the index to access the element. Example.

using System;
class Program
{
static void Main(string[] args)
{
// Declare and initialize an array
int[] numbers = { 10, 20, 30, 40, 50 };

Console.WriteLine("Array elements are:");
// Use a for loop to access each element
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Element at index " + i + " is: " + numbers[i]);
}
}
}

The line using System; includes the System namespace, which provides classes for input and output operations. The class Program defines the main program class that contains the code to run. The Main method is the entry point of the program where execution starts. Inside Main, the line int[] numbers = { 10, 20, 30, 40, 50 }; declares and initializes an array with five integer elements. The for loop then goes through each index of the array and prints the corresponding element. When you run this program, it will display each array element along with its index in the console window.

Example: Calculate the Sum of Array Elements

using System;
class Program
{
static void Main(string[] args)
{
// Declare and initialize an array
int[] marks = { 75, 80, 90, 85, 95 };
int sum = 0;
// Use a for loop to access each element and calculate the sum
for (int i = 0; i < marks.Length; i++)
{
sum += marks[i];
}
Console.WriteLine("The sum of the marks is: " + sum);
}
}

Accessing an Array Using a foreach Loop

A foreach loop is a simple way to access each element in an array one by one, without needing an index. It automatically goes through each element in the order they appear. Example.

using System;
class Program
{
static void Main(string[] args)
{
int[] numbers = { 5, 10, 15, 20, 25 };
Console.WriteLine("Array elements are:");
foreach (int number in numbers)  //Acesses an arrary elements by foreach looop
{
Console.WriteLine(number);
}
}
}

Multi-Dimensional array: 

A multi-dimensional array in C# is an array that has more than one dimension. It’s like a table or grid with rows and columns, or even more complex structures like cubes or higher dimensions. A multi-dimensional array allows you to store data in a tabular form. For example, a 2D array (matrix) has rows and columns, a 3D array has rows, columns, and depth (like a cube).

Syntax Example (2D array):

int[,] matrix = new int[3, 4]; // 3 rows, 4 columns

Initialization Example:
int[,] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Accessing Elements:
Console.WriteLine(matrix[1, 2]); // Output: 7

2D Array:

A 2-dimensional array, also known as a rectangular array, is a collection of elements of the same type, organized in a grid-like structure of rows and columns. Think of it like a spreadsheet or a chessboard.

 Syntax for Declaration

The basic syntax for declaring a 2D array specifies the data type followed by a comma within square brackets [,] and then the name of the array.

Syntax:

dataType[,] arrayName;
  • dataType: The type of elements the array will hold (e.g., int, string, double, bool).
  • [,]: This is the key syntax that tells C# it’s a 2-dimensional array. A single-dimensional array would be [], a 3D array would be [,,], and so on.
  • arrayName: The variable name for your array.

Example Declaration:

// Declares a 2D array of integers named 'matrix'
int[,] matrix;
// Declares a 2D array of strings named 'grid'
string[,] grid;

Initialization of a 2-Dimensional Array: A 2-dimensional array can be initialized  with two methods, i.e, static initialization and Dynamic initialization 

1. Static Initialization method: A 2-dimensional array can be initialized the array at declaration using curly braces { } to specify values for each row.

// 2x3 array (2 rows, 3 columns)
int[,] arr = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};

2. Dynamic Initialization Method: A 2-dimensional array can be initialized with a Dynamic initialization method by using new and assigning values later, typically using loops.

// Declare and allocate a 2x3 array
int[,] arr = new int[2, 3];
// Assign values using loops
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
arr[i, j] = i * 3 + j + 1; // Assigns 1, 2, 3, 4, 5, 6
}
}

Access 2-dimensional array element

Elements are accessed using arr[row, column], where row is the row index and column is the column index (0-based).

int value = arr[1, 2]; // Accesses element at row 1, column 2 (value = 6)

Here’s a complete example demonstrating declaration, initialization, and printing a 2D array:

using System;
class Program
{
static void Main()
{
// Static initialization
int[,] arr = {
{1, 2, 3},
{4, 5, 6}
};
// Print array
for (int i = 0; i < arr.GetLength(0); i++) // GetLength(0) = rows
{
for (int j = 0; j < arr.GetLength(1); j++) // GetLength(1) = columns
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
}

Accessing Two-Dimensional Array Elements Using a For Loop in C#

In C#, a two-dimensional array is like a table — you have rows and columns. To access each element, you use two indices: one for the row and one for the column.

A nested for Loop is the best way to do this. The outer loop goes through the rows, and the inner loop goes through the columns.

Example: Accessing and Printing Elements of a 2D Array

using System;
class Program
{
static void Main()
{
// Declare and initialize a 2D array
int[,] numbers = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
// Get the number of rows and columns
int rows = numbers.GetLength(0);
int columns = numbers.GetLength(1);
// Use nested for loops to access each element
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write(numbers[i, j] + " ");
}
Console.WriteLine(); // Move to the next row
}
}
}

Jugged Array:

It is a special type of multidimensional array that has irregular dimension size. Every row has a different number of elements. It consists of multiple arrays as its elements, but each array inside it can be of various sizes. A jagged array is an array of arrays such that members of the array can be of different sizes. i.e., the length of each array index can differ.

Declaration of Jagged Array in C#
A jagged array in C# is an array whose elements are themselves arrays, allowing each inner array to have a different length. It’s declared using two sets of square brackets ([][]). You can initialize it by first creating the outer array and then assigning each inner array separately, or you can declare and initialize everything in one line. For example

int[][] jagged = new int[2][]; 
jagged[0] = new int[] {1, 2}; 
jagged[1] = new int[] {3, 4, 5};  creates a jagged array with rows of different lengths.

Declaration and initialization in one line: You can also declare and initialize at the same time:

int[][] jaggedArray = new int[][]
{
new int[] { 1, 2 },
new int[] { 3, 4, 5 },
new int[] { 6, 7, 8, 9 }
};

Here’s a complete C# program that shows how to declare, initialize, and display a jagged array:

using System;
class Program
{
static void Main()
{
// Declare and initialize a jagged array with 3 rows
int[][] jaggedArray = new int[3][];

// Initialize each row with different lengths
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

// Display the jagged array elements
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write("Row " + i + ": ");
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
}
}
output of program: 
Row 0: 1 2 
Row 1: 3 4 5 
Row 2: 6 7 8 9 

Write a C# program using a jagged array to display the following pattern of stars:

  *
  **
  ***
  *****

using System;

class Program
{
static void Main()
{
// Declare and initialize a jagged array for the pattern
char[][] stars = new char[4][];

stars[0] = new char[] { ‘*’, ‘*’ }; // 2 stars
stars[1] = new char[] { ‘*’, ‘*’, ‘*’ }; // 3 stars
stars[2] = new char[] { ‘*’, ‘*’, ‘*’, ‘*’ }; // 4 stars
stars[3] = new char[] { ‘*’, ‘*’, ‘*’, ‘*’, ‘*’ }; // 5 stars

// Print the pattern
for (int i = 0; i < stars.Length; i++)
{
for (int j = 0; j < stars[i].Length; j++)
{
Console.Write(stars[i][j]);
}
Console.WriteLine();
}
}
}

compiled by; Er. Basant kumar yadav

error: Content is protected !!
Scroll to Top