Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type,...

Post on 21-Jan-2016

229 views 0 download

Transcript of Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type,...

Section 3 - Arrays and Methods

Arrays

Array: collection of group of data variables of sametype, sharing the same name for convenience

- Easy to search and manipulate

- Elements in an array are always numbered 0through 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, no allocation of memory to hold array elements.

But no actual array created yet.

dataType[] arrayName;

Exampleint[] data;string[] sentence;

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

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];

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 array

Exampleint[] 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 [ ] anArray = new int[ ] {100, 200, 400, 600};

char [ ] grade = new char[ ] { ‘A’, ‘B’, ‘C’, ‘D’, ‘F’}; double [ ] depth = new double[2] {2.5, 3};

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

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 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]; }}

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;}

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

// Use of Array methodsusing 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); }}

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

Two-dimensional arrays

Declaration of two-dimension arrays

GetLength(0) and GetLength(1) respectively for the length of each dimension

string[] line; // 1-Ddouble [,] matrix] // 2-Dint [,,] plane; // 3-D

int[,] data = new int [3,5];

// Simple two dimensional arrayusing 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(); }}

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!

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() { ...}

Anatomy of a Method

Method components

static void Main(string[] args) { Console.WriteLine("Hello World!"); }

Return Type

Method NameModifier

Parameters

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

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

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)

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)

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

public static double CalculateKmsPerLiter (int kmsTraveled, double litersUsed){ return kmsTraveled / litersUsed;}

Compatible value (double) returned

Return type

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

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.