Presentation is loading. Please wait.

Presentation is loading. Please wait.

Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search.

Similar presentations


Presentation on theme: "Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search."— Presentation transcript:

1 Section 3 - Arrays and Methods

2 Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search and manipulate - Elements in an array are always numbered 0 through N-1, where N is the total number of elements, called the size or length of array - Position of of an element in an array is called the element index or subscript - Array of values are arranged in consecutive memory locations

3 One-Dimensional Array Declaration of array In C#, declaration of array is a reference declaration, no allocation of memory to hold array elements. But no actual array created yet. dataType[] arrayName; Example int[] data; string[] sentence;

4 Create an array using the new operator arrayName = new dataType[size] Allocate memory; hence an array data = new [10]; Put together declaration and creation int[] data = new int[100]; To access each element, use subscript or index, e.g. data[i], where i should be in the range 0 through length-1

5 Format for creating an array type [ ] identifier = new type [size]; const int size = 15; string [ ] lastName = new string[25]; double [ ] cost = new double 1000]; double [ ] temperature = new double[size]; int [ ] score; score = new int[size + 15];

6 Array of primitive number types automatically initialized as 0, while bool type is initialized as false. Other types are reference types and initialized to the special value null. Once an aray has been declared and created, can assign values to each element. Example a[0] = 10; a[1] = 20;

7 C# has an easy way to initialize element values while declaring and creating the array Example int[] a = new int[2] {10, 20}; Or int[] a = new int[] {10, 20}; length, a public method of System.Array, can be used to get the total number of elements, i.e. size of an array. Lots of other methods in System.Array

8 Examples int [ ] anArray = new int[ ] {100, 200, 400, 600}; char [ ] grade = new char[ ] { ‘A’, ‘B’, ‘C’, ‘D’, ‘F’}; double [ ] depth = new double[2] {2.5, 3};

9 using System; class ArraySum { public static void Main() { int[] data = new int[] {11, 12, 13, 14, 15, 16, 17}; int sum = 0; double average; for (int i = 0; i < data.Length; ++i) { sum = sum + data[i]; Console.Write(data[i] + ", "); } average = sum / (double)(data.Length); Console.WriteLine(“Sum = " + sum + " average = " + average); } Example

10 Passing Array to Method as Parameter C# passes array parameters by reference More efficient to pass by reference, rather than large amount of data Called method can manipulate the contents of the array passed from a calling method, which causes side effect: possible alteration to the original data by the method. May use built-in methods to copy and sort arrays.

11 using System; class MyCopy { public static void Main( ) { int[] data1 = {1, 2, 3, 4, 5, 6, 7}; int[] data2 = {8, 9, 10, 11, 12, 13, 14}; CopyIt(data1, data2); Console.Write("data1:"); // Output data1 for (int i = 0; i < data1.Length; ++i) Console.Write(" " + data1[i]); Console.WriteLine(); Console.Write("data2:"); // Output data2 for (int i = 0; i < data2.Length; ++i) Console.Write(" " + data2[i]); Console.WriteLine(); // Output data2 } static void CopyIt(int[] from, int[] to) { for (int i = 0; i < from.Length; ++i) to[i] = from[i]; }

12 The foreach Statement Alternative and simplified statement for the for statement for (indexVar=0; indexVar<arrayName.Length; ++indexVar) { process arrayName[indexVar]; } foreach (Type variableName in arrayName) { statements; }

13 Example static void WriteArray(int[] a) { foreach (int element in a) Console.Write(element +" "); Console.WriteLine(); } foreach cannot be used to change the contents of the array

14 // Use of Array methods using System; class ArrayMethods { public static void Main() { string[] words = {"the", "quick", "brown", "fox", "jumped", "over", "the", "fence"}; foreach (string s in words) Console.Write(s + ", "); Console.WriteLine("\nthe is at 1st " + Array.IndexOf(words, "the")); Console.WriteLine("the is at last " + Array.LastIndexOf(words, "the")); Array.Reverse(words); foreach (string s in words) Console.Write(s+ ", "); Console.WriteLine("\n\nSorted"); Array.Sort(words); foreach (string s in words) Console.WriteLine(s); }

15 Recap: Arrays - One-dimensional int[] a = new int[3]; int[] b = new int[3] {3, 4, 5}; SomeClass[] d = new SomeClass[10];// Array of references int len = a.Length; // number of elements in array

16 Two-dimensional arrays Declaration of two-dimension arrays GetLength(0) and GetLength(1) respectively for the length of each dimension string[] line; // 1-D double [,] matrix] // 2-D int [,,] plane; // 3-D int[,] data = new int [3,5];

17 // Simple two dimensional array using System; class TwoD { public static void Main() { int[,] data = new int[3,5]; // row x column Console.WriteLine("No. of elements = " + data.Length); for (int i = 0; i < data.GetLength(0); ++i) { Console.WriteLine("Row " + i + ": "); for (int j = 0; j < data.GetLength(1); ++j) { data[i,j] = i * j; Console.Write(data[i,j] + ", "); } Console.WriteLine(); }

18 Two-dimensional array initialization Different organizations int[,] a = {{1,2}, {3,4}, {5,6}}; int[,] b = {{1,2,3}, {4,5,6}}; int[,] c = {{1,2,3,4,5,6}}; a has three rows of two elements b has two rows of three elements c has one row of six elements – a degenerate two- dimensional array!

19 Methods C#, like most languages, organizes code in terms of functions. However, unlike some languages, C# functions are member functions or methods of a class. Methods can take any number of parameters, or no parameters. Methods can return any type or void to indicate no return type.

20 Methods access_modifier return_type method_name(parameters ) { statements } E.g. public static void Main() {... }

21 Anatomy of a Method Method components static void Main(string[] args) { Console.WriteLine("Hello World!"); } Return Type Method Name Modifier Parameters

22 using System; { class SquareExample { static void Main( ) { int aValue = 768; int result; result = aValue * aValue; Console.WriteLine(“{0} squared is {1}”, aValue, result); Console.Read( ); } Required method

23 Types of methods Classes contain 2 types of methods: –Those with no return value (void) –Those with a return value (int, string, etc.) Methods may be: –instance –Static Instance methods require an object to call them Static methods are global and thus require only require a class name, e.g. Main()

24 Example Array class –fully-qualified name is System.Array namespace System { public class Array { public int GetLength(int dimension) {... } public static void Sort(Array a) {... }. } instance method (absence of static) static method (presence of static)

25 Calling methods Here's an example of calling into the Array class: using System; public class App { public static void Main() { int[] data = { 11, 7, 38, 55, 3 }; Array.Sort(data); for (int i=0; i<data.GetLength(0); i++) Console.WriteLine(i + ": " + data[i]); } instance method (prefixed by object name) static method (prefixed by class name)

26 Return Type Indicates what type of value is returned when the method is completed Always listed immediately before method name void –No value being returned return statement –Required for all non-void methods –Compatible value

27 Return Type public static double CalculateKmsPerLiter (int kmsTraveled, double litersUsed) { return kmsTraveled / litersUsed; } Compatible value (double) returned Return type

28 Parameter passing C# offers three options: –pass-by-value (default) –pass-by-reference –pass-by-result ("copy-out")

29 Pass-by-value Pass-by-value is default parameter passing mechanism –Data copied into method formal parameter –Any changes to parameter inside method affect local copy only value parameter void F(int x) { x = 0; } int y = 9; F(y); y unchanged

30 Pass-by-Reference No copy is made of the parameter Parameter of method does not contain a value, but rather the memory address of the element being passed Useful when want to pass large amounts of data, e.g. array. Just pass the address of the first element, not copy the whole array.


Download ppt "Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search."

Similar presentations


Ads by Google