Array in C#
An array
is a collection of variables of the same
data type, stored in contiguous
memory locations, and accessed using a common name and index.
Each item in an array is called an element, and the index of arrays in C# starts from 0.
Key Points About Arrays in C#:
1.
Elements are stored
in contiguous memory locations.
2.
Index starts from
0. So, for an array of size 5, valid indexes are 0 to 4.
3.
Arrays are
reference types and are allocated on the heap.
4.
C# array is an
object of base type System.Array.
5.
Array elements can
be of any type, including another array (array of arrays).
6.
Jagged array
(array of arrays) elements are reference types and are initialized to null.
7.
Arrays can be single-dimensional,
multi-dimensional (rectangular),
or jagged.
8. The size of an array is fixed after its declaration (unless using dynamic collections like List<T>).
Types of Arrays in C#:
|
Type |
Description |
Example Syntax |
|
Single-Dimensional |
One row of elements |
|
|
Multi-Dimensional |
Array with multiple rows and columns |
|
|
Jagged Array |
Array of arrays (different lengths allowed) |
|
Declaration
and Initialization of Arrays in C#
In C#, an array must first be declared before it can be used, and then
it must be initialized to allocate
memory and optionally assign values.
Declaration of an Array
An array is declared by specifying the data type of its elements, followed by
square brackets [],
and the array name.
Syntax:
datatype[] arrayName;
This statement declares a reference to an array
of the specified data type but does not
allocate memory for the elements.
Example:
int[] numbers;string[] names;
In the above examples, numbers is declared
as an array of integers, and names is an array of strings.
2. Initialization of an Array
After declaration, an array must be initialized using the new
keyword to allocate memory.
There are several ways to initialize an array in C#:
a. Using the new keyword with a fixed size
This method allocates memory for a specific
number of elements. The elements will be initialized to their default values
(e.g., 0 for int, null for string).
int[] numbers = new int[5]; // Creates an array of 5 integers with default values (0)
b. Assigning values individually using index
After initializing the array, values can be
assigned one by one using the index position.
numbers[0] = 10;numbers[1] = 20;
c. Initialization with values at the
time of declaration
You can directly assign values to the array
during declaration.
int[] numbers = { 10, 20, 30, 40, 50 };
In this case, the size of the array is automatically determined based on the number of values.
d. Using new keyword with values
Here, the array is explicitly created using new,
and values are assigned at the same time.
int[] numbers = new int[] { 10, 20, 30, 40, 50 };
e. Specifying size and values together
You can also specify both the size and the
initial values.
int[] numbers = new int[5] { 10, 20, 30, 40, 50 };
Here, the number of elements in the initializer must match the specified size.
f. Creating an empty array and assigning
later
This approach is useful when the values are
not known at the time of declaration.
string[] names = new string[3];names[0] = "Alice";names[1] = "Bob";names[2] = "Charlie";
Accessing Data from an Array in C#
Once an array is declared and initialized, you can access and
manipulate its elements using their index. Array elements in
C# are zero-indexed, meaning the first element
is at index 0, the second at index 1, and so on.
Accessing Individual Elements
You can access or modify any element in the array using its
index inside square brackets [ ].
Syntax:
arrayName[index];
Example:
int[] numbers = { 10, 20, 30, 40, 50 };
// Accessing the first element
Console.WriteLine(numbers[0]); // Output: 10
// Accessing the third element
Console.WriteLine(numbers[2]); // Output: 30
2. Modifying Array Elements
You can also change the value of a specific element by assigning
a new value to a particular index.
Example:
numbers[1] = 25; // Changing second element from 20 to 25
Console.WriteLine(numbers[1]); // Output: 25
3. Traversing an Array Using Loops
To access all elements in an array, you can use loops like for.
Using for loop
int[ ] marks = { 70, 85, 90, 60, 95 };
for (int i = 0; i < marks.Length; i++)
{
Console.WriteLine("Element at index " + i + " is " + marks[i]);
}
4. Accessing Array Length
To avoid errors like accessing out-of-bounds indexes, you can
use the .Length property.
Console.WriteLine("Total elements: " + marks.Length);
5. Accessing Elements in Multi-Dimensional Arrays
For multi-dimensional arrays, you use multiple indices.
int[,] matrix = { {1, 2}, {3, 4}, {5, 6} };
Console.WriteLine(matrix[0, 1]); // Output: 2
Question 1:
Write a C# program to store the names of 4 students in an array and display the
first student's name using array indexing.
Question 2:
Write a C# program to take 10 integer inputs from the user and
display all the entered numbers using an array.
Question 3:
Write a C# program to input 10 numbers in an array and
calculate the sum of all elements.
Question 4:
Write a C# program to:
·
Input 5 elements in array A
·
Input 5 elements in array B
·
Find the sum of corresponding elements of both arrays and store it in
a third array.
·
Print the resulting sum array.
Multi-Dimensional Array
The multidimensional array is also known as rectangular
arrays in C#. It can be two dimensional or three dimensional. The data is
stored in tabular form (row * column) which is also known as matrix.
Array can be:
- 2D
- 3D
- 4D
- int[,] arr=new int[3,3];//declaration of 2D array
- int[,,] arr=new int[3,3,3];//declaration of 3D array
Two-Dimensional Arrays
The simplest form of the multidimensional array is the 2-dimensional array.
A 2-D array is a list of one-dimensional arrays.
A 2-D array can be thought of as a table,which has x number of rows and
y number of columns. Following is a 2-D array, which contains 3 rows
and 4 columns −
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values
for each row. The Following array is with 3 rows and each row has 4
columns.
int [,] a = new int [3,4] {
{0, 1, 2, 3} , /* row indexed by 0 */
{4, 5, 6, 7} , /* row indexed by 1 */
{8, 9, 10, 11} /* row indexed by
2 */
};
Accessing Two-Dimensional
Array Elements
An element in a 2-dimensional array is accessed by using the subscripts.
That is, row index and column index of the array. For example,
int val = a[2,3];
Jagged Array in C#
A jagged array is an array whose elements are themselves
arrays. It is sometimes called an “array of arrays.” Unlike a multidimensional
array, where every row must have the same number of columns, a jagged array
allows each row to have a different size. This makes it more flexible and
memory efficient when working with uneven or irregular data.
A jagged array is declared using two square brackets. For example,
int[][] jaggedArr = new int[3][];
This declaration creates a jagged array with three rows, but the number of
elements in each row is not fixed yet. Each row must then be initialized
separately.
We can initialize rows step by step, for instance:
jaggedArr[0] = new int[2]; // row 0 has 2 elements
jaggedArr[1] = new int[4]; // row 1 has 4 elements
jaggedArr[2] = new int[3]; // row 2 has 3 elements
Here, each row has a different length, which shows the flexibility of a
jagged array.
Initialization can also be done directly at the time of declaration. For
example:
int[][] jaggedArr = new int[][]
{
new int[] {1, 2},
new int[] {3, 4, 5, 6},
new int[] {7, 8, 9}
};
This creates three rows where the first row has two elements, the second row
has four elements, and the third row has three elements.
To access elements of a jagged array, we use two indexes. The first index
selects the row, and the second index selects the element inside that row. For
example, jaggedArr[1][2]
means the third element of the second row.
When we want to display or process all the elements of a jagged array, we
use nested loops. The outer loop goes through each row, while the inner loop
goes through each element of that row.
Here is a complete example:
using System;
class Jaggedarr { public static void Main() { // Declare the Jagged Array of four elements int[][] jagged_arr = new int[4][]; // Initialize the elements jagged_arr[0] = new int[] {1, 2, 3, 4}; jagged_arr[1] = new int[] {11, 34, 67}; jagged_arr[2] = new int[] {89, 23}; jagged_arr[3] = new int[] {0, 45, 78, 53, 99}; // Display the array elements for (int n = 0; n < jagged_arr.Length; n++) { Console.Write("Row({0}): ", n); for (int k = 0; k < jagged_arr[n].Length; k++) { Console.Write("{0} ", jagged_arr[n][k]); } Console.WriteLine(); } }}
Array Class in C#
In C#, Array is a fundamental class in the
.NET Framework, present in the System namespace.
It provides a collection of static methods
and properties to work with arrays.
This makes array handling easier by allowing operations like sorting,
searching, copying, and retrieving values.
1. Properties of the Array Class
1. Length → Gets the total number of elements in all dimensions of the array.
int[] num = {1,4,8,90,100,14,12};
Console.WriteLine(num.Length); // Output: 7
2. Rank → Gets the number of dimensions in the array.
int[] num = {88,4,8,90,100,14,12};
Console.WriteLine(num.Rank); // Output: 1
3. GetLength(int dimension) → Returns the size of a specified dimension.
int[] num = {88,4,8,90,100,14,12};
Console.WriteLine(num.GetLength(0)); // Output: 7
4. GetLowerBound(int dimension) → Returns the lower bound (starting index) of
a given dimension.
int[] num = {88,4,8,90,100,14,12};
Console.WriteLine(num.GetLowerBound(0)); // Output: 0
5. GetUpperBound(int dimension) → Returns the upper bound (last index) of a
given dimension.
int[] num = {88,4,8,90,100,14,12};
Console.WriteLine(num.GetUpperBound(0)); // Output: 6
Methods of Array Class
The Array class provides a variety of static and instance
methods for manipulating arrays:
●
Sort(): Sorts the elements of an array.
●
Reverse(): Reverses the order of elements in an array.
●
Copy(): Copies elements from one array to another.
●
Clear(): Sets a range of elements in an array to the default value.
●
IndexOf(): Searches for a specific object and returns its index.
●
Find(): Searches for an object that matches a condition and returns it.
●
GetValue(): Retrieves the value of an element at a specified index.
● SetValue(): Sets the value of an element at a specified index.
Examples of Methods
Sort()
int[] num={88,4,8,90,100,14,12};
Array.Sort(num);
foreach(int i in num)
Console.WriteLine(i);
Reverse()
int[] num={88,4,8,90,100,14,12};
Array.Reverse(num);
foreach(int i in num)
Console.WriteLine(i);
Copy()
int[] sourceArray = {1,2,3,4,5};
int[] destinationArray = new int[5];
Array.Copy(sourceArray, destinationArray, sourceArray.Length);
foreach(var item in destinationArray)
Console.Write(item + " "); // 1 2 3 4 5
Clear()
int[] array = {1,2,3,4,5};
Array.Clear(array, 1, 3);
foreach(var item in array)
Console.Write(item + " "); // 1 0 0 0 5
IndexOf()
int[] array = {10,20,30,40,50};
Console.WriteLine(Array.IndexOf(array, 30)); // 2
Console.WriteLine(Array.IndexOf(array, 100)); // -1
Find()
int[] array = {5,10,15,20,25};
int found = Array.Find(array, x => x > 10);
Console.WriteLine(found); // 15
GetValue()
int[] myArray={0,1,2,3,9,23};
Console.WriteLine(myArray.GetValue(2)); // 2
SetValue()
int[] myArray=new int[4];
myArray.SetValue(5,0);
myArray.SetValue(4,1);
myArray.SetValue(3,2);
myArray.SetValue(2,3);
foreach(int val in myArray)
Console.Write(val + " "); // 5 4 3 2
Param Array
By using the params keyword, you can specify a method parameter that takes
a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
If the declared type of the params parameter is not a single-dimensional array, compiler error occurs.
When you call a method with a params parameter, you can pass in:
● A comma-separated list of arguments of the type of the array elements.
● An array of arguments of the specified type.
● No arguments. If you send no arguments, the length of the params list is zero.
using System;
namespace ArrayApplication {
class MyClass{
public int MyMethod(params int[] arr) {
int sum = 0;
foreach (int i in arr) {
sum += i;
}
return sum;
}
}
class TestClass {
static void Main(string[] args) {
MyClass app = new MyClass();
int sum = app.MyMethod(512, 720, 250, 567, 889);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey();
}
}
}
Write a C# program that:
Accepts marks of N students (integer values).
Displays all marks entered.
Finds and displays:
The highest mark
The lowest mark
The average mark
Sorts the marks in ascending order and displays them.
Reverses the array and displays marks in descending order.
wow this note is very interesting.π
ReplyDeleteOHH YESππ
Deletewow
ReplyDelete