KEMBAR78
arrays in c# including Classes handling arrays | PPTX
Arrays
➢Simple arrays
➢Multidimensional arrays
➢Jagged arrays
➢The Array class
➢ArrayList class
Rajpat Systems
Arrays
• If you need to work with multiple elements/
objects of the same type, you can use arrays
and collections.
• Arrays :
- An array stores a fixed-size sequential collection of
elements of the same type.
- An array is a data structure that contains a number
of elements of the same type.
- Reference data type.
eg: string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};
Array Declaration & Array Initialization
• The array cannot be resized after the size is
mentioned
• Syntax
datatype[] arrayName;
where,
● datatype is used to specify the type of elements in the array.
● [ ] specifies the size of the array. The rank specifies the size of the
array.
● arrayName specifies the name of the array.
eg:
int[] myArray; // array of integers
Memory Allocation & Array Initialization
Initializing an Array
➢ Declaring an array does not initialize the array in the memory.
When the array variable is initialized, you can assign values to
the array.
➢ Array is a reference type, so you need to use the new keyword
to create an instance of the array. For example,
myArray = new int[4];
// Assign values
int[] myArray = new int[4] {4, 7, 11, 2};
int[] myArray = new int[] {4, 7, 11, 2};
int[] myArray = {4, 7, 11, 2};
Rajpat Systems
Accessing Array Elements
• After an array is declared and initialized, you can
access the array elements using an index or subscript.
• Arrays only support indexes that have integer
parameters.
eg:
int[] myArray = new int[] {4, 7, 11, 2};
int v1 = myArray[0]; // read first element
int v2 = myArray[1]; // read second element
myArray[3] = 44; // change fourth element
• If you use a wrong index value where no element
exists, an exception of type
IndexOutOfRangeExceptijon iss thrown.
Array Length
• If you don’ t know the number of elements in
the array, you can use the Length property
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]);
}
Demo
using System;
namespace geeksforgeeks {
class onedarr {
// Main Method
public static void Main()
{
// declares a 1D Array of string.
string[] weekDays;
// allocating memory for days.
weekDays = new string[] {"Sun", "Mon", "Tue", "Wed",
"Thu", "Fri", "Sat"};
// Displaying Elements of array
foreach(string day in weekDays)
Console.Write(day + " ");
}
}
Multidimensional Arrays
• You cannot change the size after declaring an array.
• A 2-dimensional array can be thought of as a table, which
has x number of rows and y number of columns.
Declaration
int[,] a = new int[3, 3];
Thus, every element in the array a is identified by an element
name of the form a[ i , j ], where a is the name of the array, and
i and j are the subscripts that uniquely identify each element in
array a.
Multidimensional Arrays
• A 2-dimensional array can be thought of as a table, which has x
number of rows and y number of columns.
• Also called rectangular arrays
Declaration
int[,] twodim = new int[3, 3];
twodim[0, 0] = 1;
twodim[0, 1] = 2;
twodim[0, 2] = 3;
twodim[1, 0] = 4;
twodim[1, 1] = 5;
twodim[1, 2] = 6;
twodim[2, 0] = 7;
twodim[2, 1] = 8;
twodim[2, 2] = 9;
Using an array initializer
• When using an array initializer, you must
initialize every element of the array. It is
not possible to leave the initialization for
some values.
2D array - Example
using System;
public class twodarr
{
public static void Main(string[] args)
{
int[ ,] arr=new int[3,3];//declaration of 2D array
arr[0,1]=10;//initialization
arr[1,2]=20;
arr[2,0]=30;
//traversal
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();//new line at each row
}
}
}
Jagged Arrays - Variable sized arrays
• A jagged array is more flexible in sizing the array.
• With a jagged array every row can have a
different size.
• Array of arrays
int[][] jagged = new int[3][];
jagged[0] = new int[2] { 1, 2 };
jagged[1] = new int[6] { 3, 4, 5, 6,7, 8 };
jagged[2] = new int[3] { 9, 10, 11 };
Jagged array - Example
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++)
{ // Print the row number
System.Console.Write("Row : " +n + " :");
for (int k = 0; k < jagged_arr[n].Length; k++)
{
// Print the elements in the row
System.Console.Write( " "+jagged_arr[n][k]);
}
System.Console.WriteLine();
}
Array Class
• The Array class is the base class for all the arrays in C#.
• It is defined in the System namespace.
• The Array class provides various properties and methods
to work with arrays.
Rajpat Systems
Array Class
Rajpat Systems
Method / Property Purpose
Clear() Sets a range of elements to empty
values
CopyTo() Copies elements from the source
array to the destination array
GetLength() Gives the number of elements in a
given dimension of the array
GetValue() Gets the value for a given index in the
array
Length Gives the length of an array
SetValue() Sets the value for a given index in the
array
Reverse() Reverses the contents of a one
dimensional array
Sort() Sorts the elements in a one
dimensional array
System.Array Class - example
using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
// Creating an array
int[] arr = new int[6] { 5, 8, 9, 25, 0, 7 };
// Creating an empty array
int[] arr2 = new int[6];
// Displaying length of array
Console.WriteLine("length of first array: "+arr.Length);
// Sorting array
Array.Sort(arr);
Console.Write("First array elements: ");
// Displaying sorted array
PrintArray(arr);
// Finding index of an array element
Console.WriteLine("nIndex position of 25 is "+Array.IndexOf(arr,25));
// Coping first array to empty array
Array.Copy(arr, arr2, arr.Length);
Console.Write("Second array elements: ");
System.Array Class - example - contd..
// Displaying second array
PrintArray(arr2);
Array.Reverse(arr);
Console.Write("nFirst Array elements in reverse order: ");
PrintArray(arr);
}
// User defined method for iterating array elements
static void PrintArray(int[] arr)
{
foreach (Object elem in arr)
{
Console.Write(elem+" ");
}
}
}
}
System.Array Class - example - contd..
// Displaying second array
PrintArray(arr2);
Array.Reverse(arr);
Console.Write("nFirst Array elements in reverse order: ");
PrintArray(arr);
}
// User defined method for iterating array elements
static void PrintArray(int[] arr)
{
foreach (Object elem in arr)
{
Console.Write(elem+" ");
}
}
}
}
C# - ArrayList Class
• It represents an ordered collection of an object that can be indexed
individually.
• It is basically an alternative to an array. However, unlike array you can
add and remove items from a list at a specified position using an index
and the array resizes itself automatically.
• It also allows dynamic memory allocation, adding, searching and
sorting items in the list.
Difference between Array and ArrayList class
using System;
using System.Collections;
namespace ConsoleApplication3
{
class arrlistdemo
{ static void Main(string[] args)
{
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("Hello");
myAL.Add("World");
myAL.Add("!");
// Displays the properties and values of the ArrayList.
Console.WriteLine("myAL");
Console.WriteLine(" Count: "+ myAL.Count);
Console.WriteLine(" Capacity: "+ myAL.Capacity);
Console.Write(" Values:");
foreach (Object obj in myAL)
Console.Write(" "+ obj);
Console.WriteLine();
Console.ReadLine();
}
}
}
ArrayList Class - example 1
ArrayList Class - example 2
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class arrlist2
{
public static void Main()
{
ArrayList arlist = new ArrayList();
arlist.Add(1);
arlist.Add("Bill");
arlist.Add("300 ");
arlist.Add(true);
arlist.Add(4.5);
arlist.Add(null);
foreach (object item in arlist)
Console.WriteLine(item + ", "); //output: 1, Bill, 300, 4.5,
ArrayList Class - example 2 contd..
arlist.Insert(2, "Second Item");
Console.WriteLine("After inserting second item in index 2");
foreach (var val in arlist)
Console.WriteLine(val + " , ");
Console.WriteLine("After removing null");
arlist.Remove(null); //Removes first occurance of null
foreach (var val in arlist)
Console.WriteLine(val+" , ");
Console.WriteLine("After removing val at index 4");
arlist.RemoveAt(4); //Removes element at index 4
foreach (var val in arlist)
Console.WriteLine(val + " , ");
Console.WriteLine("After removing range from 0 to 2");
arlist.RemoveRange(0, 2);//Removes two elements starting from 1st item (0
index)
foreach (var val in arlist)
Console.WriteLine(val + " , ");
Console.ReadLine();
}
}

arrays in c# including Classes handling arrays

  • 1.
    Arrays ➢Simple arrays ➢Multidimensional arrays ➢Jaggedarrays ➢The Array class ➢ArrayList class Rajpat Systems
  • 2.
    Arrays • If youneed to work with multiple elements/ objects of the same type, you can use arrays and collections. • Arrays : - An array stores a fixed-size sequential collection of elements of the same type. - An array is a data structure that contains a number of elements of the same type. - Reference data type. eg: string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; int[] myNum = {10, 20, 30, 40};
  • 3.
    Array Declaration &Array Initialization • The array cannot be resized after the size is mentioned • Syntax datatype[] arrayName; where, ● datatype is used to specify the type of elements in the array. ● [ ] specifies the size of the array. The rank specifies the size of the array. ● arrayName specifies the name of the array. eg: int[] myArray; // array of integers
  • 4.
    Memory Allocation &Array Initialization Initializing an Array ➢ Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. ➢ Array is a reference type, so you need to use the new keyword to create an instance of the array. For example, myArray = new int[4]; // Assign values int[] myArray = new int[4] {4, 7, 11, 2}; int[] myArray = new int[] {4, 7, 11, 2}; int[] myArray = {4, 7, 11, 2};
  • 5.
  • 6.
    Accessing Array Elements •After an array is declared and initialized, you can access the array elements using an index or subscript. • Arrays only support indexes that have integer parameters. eg: int[] myArray = new int[] {4, 7, 11, 2}; int v1 = myArray[0]; // read first element int v2 = myArray[1]; // read second element myArray[3] = 44; // change fourth element • If you use a wrong index value where no element exists, an exception of type IndexOutOfRangeExceptijon iss thrown.
  • 7.
    Array Length • Ifyou don’ t know the number of elements in the array, you can use the Length property for (int i = 0; i < myArray.Length; i++) { Console.WriteLine(myArray[i]); }
  • 8.
    Demo using System; namespace geeksforgeeks{ class onedarr { // Main Method public static void Main() { // declares a 1D Array of string. string[] weekDays; // allocating memory for days. weekDays = new string[] {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; // Displaying Elements of array foreach(string day in weekDays) Console.Write(day + " "); } }
  • 9.
    Multidimensional Arrays • Youcannot change the size after declaring an array. • A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Declaration int[,] a = new int[3, 3]; Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in array a.
  • 10.
    Multidimensional Arrays • A2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. • Also called rectangular arrays Declaration int[,] twodim = new int[3, 3]; twodim[0, 0] = 1; twodim[0, 1] = 2; twodim[0, 2] = 3; twodim[1, 0] = 4; twodim[1, 1] = 5; twodim[1, 2] = 6; twodim[2, 0] = 7; twodim[2, 1] = 8; twodim[2, 2] = 9;
  • 11.
    Using an arrayinitializer • When using an array initializer, you must initialize every element of the array. It is not possible to leave the initialization for some values.
  • 12.
    2D array -Example using System; public class twodarr { public static void Main(string[] args) { int[ ,] arr=new int[3,3];//declaration of 2D array arr[0,1]=10;//initialization arr[1,2]=20; arr[2,0]=30; //traversal for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ Console.Write(arr[i,j]+" "); } Console.WriteLine();//new line at each row } } }
  • 13.
    Jagged Arrays -Variable sized arrays • A jagged array is more flexible in sizing the array. • With a jagged array every row can have a different size. • Array of arrays int[][] jagged = new int[3][]; jagged[0] = new int[2] { 1, 2 }; jagged[1] = new int[6] { 3, 4, 5, 6,7, 8 }; jagged[2] = new int[3] { 9, 10, 11 };
  • 14.
    Jagged array -Example 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++) { // Print the row number System.Console.Write("Row : " +n + " :"); for (int k = 0; k < jagged_arr[n].Length; k++) { // Print the elements in the row System.Console.Write( " "+jagged_arr[n][k]); } System.Console.WriteLine(); }
  • 15.
    Array Class • TheArray class is the base class for all the arrays in C#. • It is defined in the System namespace. • The Array class provides various properties and methods to work with arrays. Rajpat Systems
  • 16.
    Array Class Rajpat Systems Method/ Property Purpose Clear() Sets a range of elements to empty values CopyTo() Copies elements from the source array to the destination array GetLength() Gives the number of elements in a given dimension of the array GetValue() Gets the value for a given index in the array Length Gives the length of an array SetValue() Sets the value for a given index in the array Reverse() Reverses the contents of a one dimensional array Sort() Sorts the elements in a one dimensional array
  • 17.
    System.Array Class -example using System; namespace CSharpProgram { class Program { static void Main(string[] args) { // Creating an array int[] arr = new int[6] { 5, 8, 9, 25, 0, 7 }; // Creating an empty array int[] arr2 = new int[6]; // Displaying length of array Console.WriteLine("length of first array: "+arr.Length); // Sorting array Array.Sort(arr); Console.Write("First array elements: "); // Displaying sorted array PrintArray(arr); // Finding index of an array element Console.WriteLine("nIndex position of 25 is "+Array.IndexOf(arr,25)); // Coping first array to empty array Array.Copy(arr, arr2, arr.Length); Console.Write("Second array elements: ");
  • 18.
    System.Array Class -example - contd.. // Displaying second array PrintArray(arr2); Array.Reverse(arr); Console.Write("nFirst Array elements in reverse order: "); PrintArray(arr); } // User defined method for iterating array elements static void PrintArray(int[] arr) { foreach (Object elem in arr) { Console.Write(elem+" "); } } } }
  • 19.
    System.Array Class -example - contd.. // Displaying second array PrintArray(arr2); Array.Reverse(arr); Console.Write("nFirst Array elements in reverse order: "); PrintArray(arr); } // User defined method for iterating array elements static void PrintArray(int[] arr) { foreach (Object elem in arr) { Console.Write(elem+" "); } } } }
  • 20.
    C# - ArrayListClass • It represents an ordered collection of an object that can be indexed individually. • It is basically an alternative to an array. However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. • It also allows dynamic memory allocation, adding, searching and sorting items in the list.
  • 21.
    Difference between Arrayand ArrayList class
  • 24.
    using System; using System.Collections; namespaceConsoleApplication3 { class arrlistdemo { static void Main(string[] args) { // Creates and initializes a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add("Hello"); myAL.Add("World"); myAL.Add("!"); // Displays the properties and values of the ArrayList. Console.WriteLine("myAL"); Console.WriteLine(" Count: "+ myAL.Count); Console.WriteLine(" Capacity: "+ myAL.Capacity); Console.Write(" Values:"); foreach (Object obj in myAL) Console.Write(" "+ obj); Console.WriteLine(); Console.ReadLine(); } } } ArrayList Class - example 1
  • 25.
    ArrayList Class -example 2 using System; using System.Collections; using System.Linq; using System.Text; namespace ConsoleApplication3 { class arrlist2 { public static void Main() { ArrayList arlist = new ArrayList(); arlist.Add(1); arlist.Add("Bill"); arlist.Add("300 "); arlist.Add(true); arlist.Add(4.5); arlist.Add(null); foreach (object item in arlist) Console.WriteLine(item + ", "); //output: 1, Bill, 300, 4.5,
  • 26.
    ArrayList Class -example 2 contd.. arlist.Insert(2, "Second Item"); Console.WriteLine("After inserting second item in index 2"); foreach (var val in arlist) Console.WriteLine(val + " , "); Console.WriteLine("After removing null"); arlist.Remove(null); //Removes first occurance of null foreach (var val in arlist) Console.WriteLine(val+" , "); Console.WriteLine("After removing val at index 4"); arlist.RemoveAt(4); //Removes element at index 4 foreach (var val in arlist) Console.WriteLine(val + " , "); Console.WriteLine("After removing range from 0 to 2"); arlist.RemoveRange(0, 2);//Removes two elements starting from 1st item (0 index) foreach (var val in arlist) Console.WriteLine(val + " , "); Console.ReadLine(); } }