1 / 30

Section 3 - Arrays and Methods

Section 3 - Arrays and Methods. Arrays Array : collection of group of data variable s of same type , shar ing the same name for convenience - Easy to search and manipulate - Elements in an array are always numbered 0

pamelasmith
Download Presentation

Section 3 - Arrays and Methods

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Section 3 - Arrays and Methods

  2. Arrays Array: collection of group of data variables of same type, sharingthe 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 ofelements, called the sizeor lengthof array - Position of of an element in an array is called the element index or subscript - Array of values are arranged in consecutive memorylocations

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

  4. Createan 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 orindex, e.g.data[i], wherei should be in the range 0through 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 typesautomatically initialized as 0, while booltypeis initialized as false. Other types are reference types andinitialized to the special value null. Once an aray has been declared andcreated, can assign values to eachelement. 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 ofSystem.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. Example 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); } }

  10. Passing Array to Method as Parameter C# passes array parameters by reference More efficient to pass by reference, rather thanlarge amount of data Called method can manipulate the contentsof 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 statementfor 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(); } foreachcannot be used to change thecontents 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-dimensionarrays GetLength(0) and GetLength(1)respectively for the length of eachdimension 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 arrayinitialization 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 Name Parameters Return Type Modifier static void Main(string[] args) { Console.WriteLine("Hello World!"); } Method components

  22. using System; { class SquareExample { static void Main( ) { intaValue = 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]); } } static method(prefixed by class name) instance method(prefixed by object 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 Return type publicstaticdouble CalculateKmsPerLiter (int kmsTraveled, double litersUsed) { return kmsTraveled / litersUsed; } Compatible value (double) returned

  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 void F(int x) { x = 0; } value parameter 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.

More Related