Final Exam Review Monchai Sopitkamon, Ph.D. Final Exam Topics - - PDF document

final exam review
SMART_READER_LITE
LIVE PREVIEW

Final Exam Review Monchai Sopitkamon, Ph.D. Final Exam Topics - - PDF document

2/22/2007 Final Exam Review Monchai Sopitkamon, Ph.D. Final Exam Topics Arrays Methods 1 2/22/2007 What Is an Array? An array is a sequence of elements All elements in an array have the same type Structs can have elements


slide-1
SLIDE 1

2/22/2007 1

Final Exam Review

Monchai Sopitkamon, Ph.D.

Final Exam Topics

Arrays Methods

slide-2
SLIDE 2

2/22/2007 2

What Is an Array?

An array is a sequence of elements

All elements in an array have the same type Structs can have elements of different types Individual elements are accessed using integer indexes

Array notation in C#

You declare an array variable by if i specifying:

The element type of the array The rank of the array The name of the variable

slide-3
SLIDE 3

2/22/2007 3

Array Rank

Rank is also known as the array di i dimension The number of indexes associated with each element

Accessing Array Elements

Supply an integer index for each rank

Indexes are zero-based

slide-4
SLIDE 4

2/22/2007 4

Arrays - Declaration

D l ti l Declaration only

<type> [] <name>;

Declaration with creation

<type> [] <name> = new <type>[<num-elts>];

Declaration with initialization: 2 ways

  • 1. <type> [] <name> = new <type>[<num-elts>]

{<value-lists>};

  • 2. <type> [] <name> = {<value-lists>};

Arrays – Declaration: Examples

  • Declaration only

i t []

? int[] a

STACK HEAP

int [] a;

  • Declaration with creation

int [] a = new int[3];

  • Declaration with initialization
  • 1. int [] a = new int[3] {1,2,3};

? @ int[] a @ int[] a 1 2 3

  • 2. int [] d = {7,8,9,10};
slide-5
SLIDE 5

2/22/2007 5

Array - Rules

First index of an array begins with 0 Must initialize all elements; can’t do partial Must initialize all elements; can t do partial initialization. Arrays are reference types, not value types. The array size does not need to be a compile- time constant; any valid integer expression will work Rank property specifies the dimension of the Rank property specifies the dimension of the array instance. Length property specifies the total number of elements in an array instance.

Comparing Arrays to Collections

An array cannot resize itself when full

A collection class, such as ArrayList, can resize co ect o c ass, suc as ay st, ca es e

An array is intended to store elements of one type

A collection is designed to store elements of different types

Elements of an array cannot have read-only access

A collection can have read-only access

In general, arrays are faster but less flexible

Collections are slightly slower but more flexible

slide-6
SLIDE 6

2/22/2007 6

Array Rank & Length Example Copying Arrays

Arrays are reference types. A i bl t i f t An array variable contains a reference to an array instance. This means that when you copy an array variable, you end up with two references that refer to the same array instance, for example:

int[] pins = { 9, 3, 7, 2 }; int[] alias = pins; // alias and pins refer to the same array instance

slide-7
SLIDE 7

2/22/2007 7

Copying Arrays

If you want to make a copy of the array instance that an array variable refers to you have to do that an array variable refers to, you have to do two things. First, you need to create a new array instance of the same type and the same length as the array you are copying, as in this example:

int[] pins = { 9 3 7 2 };

It's better to determine the length of an array by using its Length property

int[] pins = { 9, 3, 7, 2 }; int[] copy = new int[pins.Length];

Copying Arrays

The values inside copy are now all initialized to their default value of 0 their default value of 0. The second thing you need to do is set the values inside the new array to the same values as in the original array. You could do this by using a for statement, as shown in this example:

int[] pins = { 9, 3, 7, 2 }; int[] copy = new int[pins.Length]; for (int i = 0; i != copy.Length; i++) { copy[i] = pins[i]; }

slide-8
SLIDE 8

2/22/2007 8

Copying Arrays

An array copy is a shallow copy and not a deep copy copy. To illustrate this principle, consider the effect of creating and copying an array whose element type is, itself, a reference type. The following example creates an array of four triangles:

Triangle[] triangles = new Triangle[4];

Copying Arrays

If Triangle is a class, the rules of array instance initialization state that each element is initialized initialization state that each element is initialized to null. In other words, a diagram of the previous statement looks like this.

Triangle[] triangles = new Triangle[4];

slide-9
SLIDE 9

2/22/2007 9

Copying Arrays

Suppose you then fill the triangles array with four new Triangle objects, like this: Triangle objects, like this:

Triangle[] triangles = new Triangle[4]; for (int i = 0; i != triangles.Length; i++) { triangles[i] = new Triangle(); }

A diagram of this example looks like this.

Copying Arrays

Finally, suppose you now make a copy of the triangles array, like this: array, like this: A diagram of this example looks like this.

Triangle[] copy = new Triangle[triangles.Length]; for (int i = 0; i != copy.Length; i++) { copy[i] = triangles[i]; }

slide-10
SLIDE 10

2/22/2007 10

Copying Arrays – Important!

From the previous slide, an array of objects is really an array of references to objects really an array of references to objects. The references inside each array element live in contiguous memory, but the objects that these references refer to almost certainly do not. When you copy an array of references, you get two arrays whose corresponding references two arrays whose corresponding references refer to the same objects.

Array Methods

Sort – sorts the elements in an array of k 1 rank 1

slide-11
SLIDE 11

2/22/2007 11

Array Methods

Clear – sets a range of elements to zero (f l t ) ll (f f (for value types) or null (for reference types)

Array Methods

Clone – creates a copy of the array

slide-12
SLIDE 12

2/22/2007 12

Array Methods

GetLength – returns the length of a given di i dimension

Array Methods

IndexOf – returns the index of the first

  • ccurrence of a value/element or

if the

  • ccurrence of a value/element, or -1 if the

value/element is not present. Only works

  • n 1-dimensional arrays.
slide-13
SLIDE 13

2/22/2007 13

Methods

A method is a named sequence of statements. Each method has a name and a body Each method has a name and a body. The method body contains the actual statements to be run when the method is called. The method name should be a meaningful identifier that indicates the overall purpose of the method (CalculateIncomeTax, for example). ( p ) Most methods can be given some data, which they process, and can return information, which is usually the result of the processing.

Specifying the Method Declaration Syntax

The syntax of a Microsoft Visual C# th d i f ll method is as follows: returnType methodName ( parameterList ) { // method body statements go here }

slide-14
SLIDE 14

2/22/2007 14

Specifying the Method Declaration Syntax

The returnType is the name of a type and specifies what kind of information the method returns. This can be the f t h i t t i If ' iti name of any type, such as int or string. If you're writing a method that does not return a value, you must use the keyword void in place of the return type. The methodName is the name used to call the method. Method names must follow the same identifier rules as variable names. For example, addValues is a valid method name, whereas add$Values is not valid. The parameterList is optional and describes the types The parameterList is optional and describes the types and names of the information that the method accepts. You write the parameters between the left and right

  • parentheses. Two or more parameters must separated

with commas.

returnType methodName ( parameterList ) { // method body statements go here }

Important!

C# does not support global methods. You must write all your methods inside a class or your code will not your methods inside a class or your code will not compile.

Class Method1 Method2 Method3

slide-15
SLIDE 15

2/22/2007 15

Method: Examples

Here's the definition of a method called addValues that returns an int and has two int parameters called lhs and p rhs. Here's the definition of a method called showResult that does not return a value and has a single int parameter called answer:

Indicates that the method Does not return anything.

Writing return Statements

If you want your method to return information (in other words its return type information (in other words, its return type is not void), you must write a return statement inside the method. You do this using the keyword return followed by an expression that calculates the returned value and a semicolon the returned value and a semicolon. The type of expression must be the same as the type specified by the function.

slide-16
SLIDE 16

2/22/2007 16

return Statement Example

The return statement should be at the end of your method because it causes the method to

  • finish. Any statements after the return statement
  • finish. Any statements after the return statement

will not be executed (though the compiler will warn you about this problem if you put statements after the return statement).

return Statement Example 2

If you don't want your method to return information (its return type is void) you can use information (its return type is void), you can use a variation of the return statement to cause an immediate exit from the method. You write the keyword return, immediately followed by a

  • semicolon. For example:
slide-17
SLIDE 17

2/22/2007 17

void Method

If your method does not return anything, l it th t t t t you can also omit the return statement because the method will finish automatically when execution arrives at the closing curly brace at the end of the method.

Calling Methods

You call a method by name to ask it to perform its task perform its task. If the method requires information (as specified by its parameters), you must supply the information as requested. If the method returns information (as ifi d b it t t ) h ld specified by its return type), you should arrange to catch this information somehow.

slide-18
SLIDE 18

2/22/2007 18

Specifying the Method Call Syntax

The syntax of a C# method call is as follows: The methodName must exactly match the name of the method you're calling. Remember, C# is a case-sensitive language. The argumentList supplies the optional information that

methodName ( argumentList )

The argumentList supplies the optional information that the method accepts. You must supply an argument for each parameter, and the value of each argument must be compatible with the type of its corresponding parameter.

Here is the addValues method:

Method Call Example

int addValues(int lhs, int rhs) { // ... }

The addValues method has two int parameters, so The addValues method has two int parameters, so you must call it with two comma-separated int arguments: addValues(39, 3) // okay

slide-19
SLIDE 19

2/22/2007 19

Method Call Example

If you try to call addValues in some other way, you will probably not succeed: you will probably not succeed: The addValues method returns an int value. This int value can be used wherever an int value can int value can be used wherever an int value can be used. Consider this example: c

Understanding Scope

A variable can be used only in certain places after it has been created places after it has been created. Once the method has finished, the variable disappears completely. The scope of an identifier is simply the region of the program in which that id tifi i bl identifier is usable. Scope applies to methods as well as variables.

slide-20
SLIDE 20

2/22/2007 20

Creating Local Scope with a Method

The left and right curly braces that form the body

  • f a method create a scope
  • f a method create a scope.

Any variables you declare inside the body of a method are scoped to that method. These variables are called local variables because they are local to the method in which they are declared; they are not “in scope” in any th th d

  • ther method.

This means that you cannot use local variables to share information between methods.

Local Variable Scope Example

Consider this example:

class Example { void method() { int variable; } void anotherMethod() void anotherMethod() { variable = 42; // compile time error } }

slide-21
SLIDE 21

2/22/2007 21

Creating Class Scope with a Class

The left and right curly braces that form the body

  • f a class also create a scope
  • f a class also create a scope.

Any "variables" you declare inside the body of a class (but not inside a method) are scoped to that class. The proper C# name for these variables is fields. I t t t l l i bl fi ld In contrast to local variables, you can use fields to share information between methods.

Class Scope Example

Here is an example:

class Example { void method() { field = 42; // ok } void anotherMethod() {

NOTE In a method, you must declare a variable before you can use it. Fields are a little different. A method can use a field before the field is defined—the compiler sorts out the details for you!

{ field = 42; // ok } int field; }

sorts out the details for you!

slide-22
SLIDE 22

2/22/2007 22

Method: Quick Reference

To Do this

Declare a method Write the method inside a class E g Declare a method Write the method inside a class. E.g., int addValues(int lhs, int rhs) { } Return a value from inside a method Write a return statement inside the method. E.g., return lhs + rhs; Return from a method before the end of the method Write a return statement inside the method. E.g., return; Call a method Write the name of the method, together with any arguments between parentheses. E.g., addValues(39, 3);