SlideShare a Scribd company logo
1 of 26
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();
}
}

More Related Content

Similar to arrays in c# including Classes handling arrays

Similar to arrays in c# including Classes handling arrays (20)

Arrays
ArraysArrays
Arrays
 
Python array
Python arrayPython array
Python array
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Arrays
ArraysArrays
Arrays
 
Lecture 2.8 Arrays.pdf
Lecture 2.8 Arrays.pdfLecture 2.8 Arrays.pdf
Lecture 2.8 Arrays.pdf
 
Ch08
Ch08Ch08
Ch08
 
2D Array
2D Array 2D Array
2D Array
 
2 arrays
2   arrays2   arrays
2 arrays
 
LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
7.basic array
7.basic array7.basic array
7.basic array
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
array-191103180006.pdf
array-191103180006.pdfarray-191103180006.pdf
array-191103180006.pdf
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
 

Recently uploaded

SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxSOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxkessiyaTpeter
 
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡anilsa9823
 
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxPhysiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxAArockiyaNisha
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )aarthirajkumar25
 
Work, Energy and Power for class 10 ICSE Physics
Work, Energy and Power for class 10 ICSE PhysicsWork, Energy and Power for class 10 ICSE Physics
Work, Energy and Power for class 10 ICSE Physicsvishikhakeshava1
 
Caco-2 cell permeability assay for drug absorption
Caco-2 cell permeability assay for drug absorptionCaco-2 cell permeability assay for drug absorption
Caco-2 cell permeability assay for drug absorptionPriyansha Singh
 
Boyles law module in the grade 10 science
Boyles law module in the grade 10 scienceBoyles law module in the grade 10 science
Boyles law module in the grade 10 sciencefloriejanemacaya1
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...RohitNehra6
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...Sérgio Sacani
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...anilsa9823
 
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...jana861314
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​kaibalyasahoo82800
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfSwapnil Therkar
 
G9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptG9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptMAESTRELLAMesa2
 
Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTSérgio Sacani
 
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...Sérgio Sacani
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxUmerFayaz5
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksSérgio Sacani
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCEPRINCE C P
 

Recently uploaded (20)

SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxSOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
 
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
 
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxPhysiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )
 
Work, Energy and Power for class 10 ICSE Physics
Work, Energy and Power for class 10 ICSE PhysicsWork, Energy and Power for class 10 ICSE Physics
Work, Energy and Power for class 10 ICSE Physics
 
Caco-2 cell permeability assay for drug absorption
Caco-2 cell permeability assay for drug absorptionCaco-2 cell permeability assay for drug absorption
Caco-2 cell permeability assay for drug absorption
 
Boyles law module in the grade 10 science
Boyles law module in the grade 10 scienceBoyles law module in the grade 10 science
Boyles law module in the grade 10 science
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
 
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
 
G9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptG9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.ppt
 
Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOST
 
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptx
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disks
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
 

arrays in c# including Classes handling arrays

  • 1. Arrays ➢Simple arrays ➢Multidimensional arrays ➢Jagged arrays ➢The Array class ➢ArrayList class Rajpat Systems
  • 2. 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};
  • 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};
  • 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 • 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]); }
  • 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 • 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.
  • 10. 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;
  • 11. 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.
  • 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 • 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
  • 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# - 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.
  • 21. Difference between Array and ArrayList class
  • 22.
  • 23.
  • 24. 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
  • 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(); } }