Section 3 Arrays and Methods Arrays Array collection

  • Slides: 30
Download presentation
Section 3 - Arrays and Methods

Section 3 - Arrays and Methods

Arrays Array: collection of group of data variables of same type, sharing the same

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

One-Dimensional Array Declaration of array In C#, declaration of array is a reference declaration,

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. data. Type[] array. Name; Example int[] data; string[] sentence;

Create an array using the new operator array. Name = new data. Type[size] Allocate

Create an array using the new operator array. Name = new data. Type[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

Format for creating an array type [ ] identifier = new type [size]; const

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

Array of primitive number types automatically initialized as 0, while bool type is initialized

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;

C# has an easy way to initialize element values while declaring and creating the

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

Examples int [ ] an. Array = new int[ ] {100, 200, 400, 600};

Examples int [ ] an. Array = new int[ ] {100, 200, 400, 600}; char [ ] grade = new char[ ] { ‘A’, ‘B’, ‘C’, ‘D’, ‘F’}; double [ ] depth = new double[2] {2. 5, 3};

Example using System; class Array. Sum { public static void Main() { int[] data

Example using System; class Array. Sum { 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. Write. Line(“Sum = " + sum + " average = " + average); } }

Passing Array to Method as Parameter C# passes array parameters by reference More efficient

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.

using System; class My. Copy { public static void Main( ) { int[] data

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

The foreach Statement Alternative and simplified statement for the for statement for (index. Var=0;

The foreach Statement Alternative and simplified statement for the for statement for (index. Var=0; index. Var<array. Name. Length; ++index. Var) { process array. Name[index. Var]; } foreach (Type variable. Name in array. Name) { statements; }

Example static void Write. Array(int[] a) { foreach (int element in a) Console. Write(element

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

// Use of Array methods using System; class Array. Methods { public static void

// Use of Array methods using System; class Array. Methods { public static void Main() { string[] words = {"the", "quick", "brown", "fox", "jumped", "over", "the" , "fence"}; foreach (string s in words) Console. Write(s + ", "); Console. Write. Line("nthe is at 1 st " + Array. Index. Of(words, "the")); Console. Write. Line("the is at last " + Array. Last. Index. Of(words, "the")); Array. Reverse(words); foreach (string s in words) Console. Write(s+ ", "); Console. Write. Line("nn. Sorted"); Array. Sort(words); foreach (string s in words) Console. Write. Line(s); } }

Recap: Arrays - One-dimensional int[] a = new int[3]; int[] b = new int[3]

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

Two-dimensional arrays Declaration of two-dimension arrays Get. Length(0) and Get. Length(1) respectively for the

Two-dimensional arrays Declaration of two-dimension arrays Get. Length(0) and Get. Length(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];

// Simple two dimensional array using System; class Two. D { public static void

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

Two-dimensional array initialization Different organizations int[, ] a = {{1, 2}, {3, 4}, {5,

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 twodimensional array!

Methods C#, like most languages, organizes code in terms of functions. However, unlike some

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.

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

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

Anatomy of a Method Modifier Method Name Return Type static void Main(string[] args) {

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

using System; { class Square. Example { Required method static void Main( ) {

using System; { class Square. Example { Required method static void Main( ) { int a. Value = 768; int result; result = a. Value * a. Value; Console. Write. Line(“{0} squared is {1}”, a. Value, result); Console. Read( ); } } }

Types of methods • Classes contain 2 types of methods: – Those with no

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()

Example • Array class – fully-qualified name is System. Array instance method (absence of

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

Calling methods • Here's an example of calling into the Array class: using System;

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 }; static method (prefixed by class name) instance method (prefixed by object name) Array. Sort(data); for (int i=0; i<data. Get. Length(0); i++) Console. Write. Line(i + ": " + data[i]); } }

Return Type • Indicates what type of value is returned when the method is

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

Return Type Return type public static double Calculate. Kms. Per. Liter (int kms. Traveled,

Return Type Return type public static double Calculate. Kms. Per. Liter (int kms. Traveled, double liters. Used) { return kms. Traveled / liters. Used; } Compatible value (double) returned

Parameter passing • C# offers three options: – pass-by-value (default) – pass-by-reference – pass-by-result

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

Pass-by-value • Pass-by-value is default parameter passing mechanism – Data copied into method formal

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; y unchanged F(y);

Pass-by-Reference • No copy is made of the parameter • Parameter of method does

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.