Skip to main content

UNIT 3 Array in C#

 

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

int[] arr = new int[5];

Multi-Dimensional

Array with multiple rows and columns

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

Jagged Array

Array of arrays (different lengths allowed)

int[][] jagged = new int[3][];

 

 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:

  1. 2D
  2. 3D
  3. 4D
  1. int[,] arr=new int[3,3];//declaration of 2D array  

  2. 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];

Comments

Post a Comment

Popular posts from this blog

Function of OS 1. Process Management The operating system helps in running many programs at the same time. It keeps track of each running program (called a process), decides which one should run next, and stops or starts them as needed. It makes sure that all the programs get a fair chance to use the CPU.   2. Memory Management The OS manages the computer's memory (RAM). It decides which program will use how much memory and keeps track of it. When a program is closed, it frees up the memory so that other programs can use it. This helps the computer run smoothly without crashing.   3. File System Management The operating system helps us to create, save, open, and delete files. It organizes files in folders and keeps them safe. It also controls who can open or edit a file to protect our data.   4. Device Management The OS controls all the input and output devices like the keyboard, mouse, printer, and monitor. It tells the devices what to do and makes su...
  Unit-2 Control Statements in c# A control statement in java is a statement that determines whether the other statements will be executed or not. It controls the flow of a program. Control Statements can be divided into three categories, namely ●         Decision Making statements ●         Iteration (Looping) statements ●         Jump statements ⮚   Decision Making statements Decision making statements help you to make decision based on certain conditions. These conditions are specified by a set of decision making statements having boolean expressions which are evaluated to a boolean value true or false. There are following types of decision making statements in C#. 1) Simple if statement:   It is the most basic statement among all control flow statements in C#. It evaluates a Boolean expression and enables the program to enter a block of code if the ...
    Basic Structure Of Java Program   // 1. Package Declaration (optional) package mypackage;   // 2. Import Statements (optional) import java.util.Scanner;   // 3. Class Declaration public class MyProgram {       // 4. Main Method – Entry point of the program     public static void main(String[] args) {           // 5. Statements – Code to be executed         System.out.println("Hello, World!");     } }   1. Package Declaration (Optional) A Java program may begin with a package declaration that defines the folder or package name in which the class is stored. For example: package mypackage; This helps organize code into different logical groups.   2. Import Statements (Optional) After the package declaration, import statements can be added to include built-in or user-defined Jav...