Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return...

60
Methods Version 1.1

description

Objectives At the end of this topic, students should be able to: Write programs that use built-in methods Know how to use methods in the Math library Correctly write code that generates random numbers Correctly write and use user defined methods in a program Describe what scope is and how it affects the execution of a program. 3

Transcript of Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return...

Page 1: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

MethodsVersion 1.1

Page 2: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

TopicsBuilt-in methods

Methods that return a valueMethods that do not return a value (void methods)Random number generatorsProgrammer defined methods return values of void/int/double/etc.Scope

Programmer defined methods

2

Local (automatic) variables

Page 3: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

ObjectivesAt the end of this topic, students should be able to:

Write programs that use built-in methodsKnow how to use methods in the Math libraryCorrectly write code that generates random numbersCorrectly write and use user defined methods in a programDescribe what scope is and how it affects the executionof a program.

3

Page 4: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

At this point we have learned to write quitecomplex programs, that contain decisions and loops.

… but most of our programs are still quitesmall and easy to manage.

What if I gave you an assignment to write a program that would contain5,000 lines of code?

4

Page 5: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

We often write a program as a series of pieces or blocks

because it is easier to understand what goes onin a small block (piece) of code.

because we can re-use the same block (piece) of codemany times from within our program

we call this functional decomposition -- breaking the program down into more manageable blocks (pieces).

in C# these smaller blocks (pieces) are called methods

5

Page 7: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Let’s do a top-down design.

Ask for user’s choiceAnd get the input

Generate computer’s

choiceDetermine winner

Display the results

See if user wantsto play again

7

Page 8: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Ask for user’s choice

and get the input

Prompt the user to make a choice (r-p-

s)

Get the users input

Is theinput valid

?

no

8

Page 9: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Generate computer’s

choice

Generate aRandom numberBetween 1 and 3

9

Page 10: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Determine Winneruser =

computer?

yes tie

computer= rock

?

yes user= paper

?

yes winner isuser

no

winner iscomputernono

computer= paper

?

yes user= rock

?

yes winner iscomputer winner is

usernono

user= rock

?no

yes winner isuser

winner iscomputer

10

Page 11: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Display user choice

Display computer choice

Display the winner

Display the results

11

Page 12: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

See if user wantsTo play again

Prompt the user to make a choice (y/n)

Get the users input

Is theinput valid

?

no

PlayAgain

?

noquit

12

Page 13: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

We could now write this program as one long list of statements. It would be very big and quite complex … there would be several loops and lots of decision blocks.

Whenever you have a large block of codethat does many different things, it becomesdifficult to visualize what is happening in thecode, and so much harder to get the codeto work correctly. In software engineering wesay that it lacks “COHESION.”

13

REMEMBER, every line of code you write has the potential of 1 to n errors!

REMEMBER, other than dating and marriage, programming is the MOST error-prone activity know to mankind.

Page 14: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Prompt the user to make a choice (r-p-

s)

Get the users input

Is theinput valid

?

no

This is easy to visualize

14

Page 15: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

tie

quit

This is much harderto visualize. We reallycan’t even get it on onepage . . . and make itreadable.

15

Page 16: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

So … let’s take each of these pieces and write each asa separate, stand-alone block of code called a method.

Ask for user’s choiceAnd get the input

Generate computer’s

choiceDetermine winner

Display the results

See if user wantsto play again

Each method will have one well defined thing that it does. (Providesa service.)

We will have the ability to giveeach method any data that itneeds to do its job.

Each method can return to usthe results of its work.

16

Page 17: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Method Syntax

static int DetermineWinner( int compChoice, int userChoice){

// statements

}

The type of datareturned by thismethod.

The method’sname (for address)

These are parameters.Each parameter has a data type and a name.

The body of the methodis made up of valid C#statements (providing a service), enclosed in curly braces.

method header

method block (body)

17

Denotes a class levelmethod.

Page 18: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Just as a reminder … Main( ) is a method which satisfies all theconditions specified earlier.

Header static void Main( )Block {(body)

}18

class level specifier

return data type Method identifier (address)

comma delimited parameter list

Page 19: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

General Format of C# Methods

Header <return type> <method identifier> ( <comma delimited parameter list> ) {

Block <statements>(body) }

19

Page 20: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Built-in MethodsIn general, if you can find some written and tested code that does what you want, it is better to use that already existing code than to re-create the code yourself.

saves timefewer errorstested under all conditions

Most programming languages, including C#, includelibraries of pre-written (built-in) and tested methods that docommon programming tasks. In C#, these librariesare in the .Net library accessed via using statements.

20

Page 21: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Built-In MethodsWe have already used a number

of built-in methods– WriteLine(…), Write(…)– ReadLine(…)– Sqrt(…)– Others?

21

Page 22: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Methods that return a valueAs an example of a method that returns a value, considerthe Sqrt method in the Math class.

To set a value to the square root of the number 9, we wouldwrite

result = Math.Sqrt (9);

this is the method’s argument.

The argument may be a literal value,a variable, a constant, or an expression.

Some methods may take more than oneargument. If so, they are separated bycommas (a comma delimited list).

the value returned by the functionis called its return value.

A method can only have onereturn value.

this is called a method invocation.It can be used anywhere an expressioncan be used. The Sqrt method belongsto the Math class.

22

Page 23: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

The Math classThe Sqrt method is found in the Math class.

Other common functions in the Math class:

Pow (int x, int y) calculates xy double

Abs (double n) absolute value of n double

Ceil (double n ) smallest integer >= n double

Floor (double n) largest integer <= n double

name function (service) return type

23

Page 24: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

RoundingWhen we round a number, we pick the closest integer value.For example,

if a = 2.7, then the rounded value of a is 3if a = 2.4, then the rounded value of a is 2.

The Ceil and Floor methods given in the previous slidedon’t do rounding. For example,

Math.Floor (2.9) returns 2.0, while Math.Ceil (2.3) returns 3.0.

24

Page 25: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Methods that don’t return a value

methods that don’t return a value are called void methods.

void methods are written as statements. They cannot be usedin an expression, as expressions must return a typed value.

void methods can have zero or more parameters.

25

Page 26: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Writing a Method

What job will the method do?What data does it need to do it’s work?What will the method return?

26

Page 27: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Prompt the user to make a choice (r-p-

s)

Get the users input

Is theinput valid

?

no

Here is the activity diagramfor the method we need to write to get the user’s choice.

What is it’s job (service provided)?What data does it need?What should it return?

27

Page 28: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

The Method Prologue

Every method should have a method prologue.The method prologue tells us * What the purpose of the method is * What data the method needs to do its work properly * What data the method returns

28

Page 29: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

The Method Prologue

// The GetUserChoice method// Purpose: gets a valid user choice (1-3)// Parameters: none// Returns: the user choice as an int

29

Page 30: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Prompt the user to make a choice (r-p-

s)

Get the users input

Is theinput valid

?

no

static int GetUserChoice( ) {

int choice;

do { Console.WriteLine("Enter your choice: "); Console.WriteLine("1 - Rock"); Console.WriteLine("2 - Paper"); Console.WriteLine("3 - Scissors: "); choice = int.Parse(Console.ReadLine( ) ); choice = char.ToUpper(choice);

if (choice < ROCK || choice > SCISSORS) Console.WriteLine("Invalid selection.");

} while (choice < ROCK || choice > SCISSORS);

return choice; }

30

Page 31: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Generate aRandom numberBetween 1 and 3

Here is the activity diagramfor the method we need to write to get the computer’s choice.

What is it’s job (service it provides)?What data does it need?What should it return?

31

Page 32: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

The Method Prologue

// The GetComputerChoice function// Purpose: generates a random choice (1-3)// Parameters: none// Returns: the computer choice as an int// Pre-conditions: none// Post-conditions: none

32

Page 33: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Random Number GeneratorThe .Net library provides a class that we can use to createa random number generator. To create a random numbergenerator object we instantiate it as an object, so we write

Random randoms = new Random( );

This is the referenceto the Random object. This creates the Random object in the Heap.

This initializes the Random object.Know as a constructor.

33

Page 34: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Random Number GeneratorA random number generator generates a pseudo-random integer value between zero and 2,147,483,646.

To get a random number within a specific range we scalethe result …. for example, to get a number between 0 and 2,inclusive

int n = randoms.Next( 3 );

generates value up to, but not including 3 (0-2)

34

Page 35: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Random Number GeneratorTo shift the range of the random numbers, for example, to geta random number between 1 and 3, use this form of the Nextmethod:

int n = randoms.Next(1, 4);

Start at 1 Generate values up to, but not including 4 (1-3)

35

Page 36: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Random Number Generator

To get a repeatable sequence of pseudo-random numbers,use the same seed when creating the Random object

Random randoms = new Random( 3 );

*

* same machine, same compiler36

Page 37: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Generate aRandom numberBetween 1 and 3

static int GetComputerChoice( ) { int choice;

choice = randoms.Next(1,4);

return choice; }

We created the Random object randoms elsewhere.

37

Page 38: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

user =computer

?

yes tie

computer= rock

?

yes user= paper

?

yes winner isuser

no

winner iscomputernono

computer= paper

?

yes user= rock

?

yes winner iscomputer winner is

usernono

user= rock

?no

yes winner isuser

winner iscomputer

Here is the activity diagramfor the method we need to write to get the computer’s choice.

What is it’s job (service)?What data does it need?What should it return?

38

Page 39: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

The Method Prologue

// ---------------- PickWinner method ----------------// Purpose: decide who wins, computer or user// Parameters: computer choice, user choice// Returns: the winner as an int // (1 – user wins, 2 – computer wins, 0 - tie)// Pre-conditions: none// Post-conditions: none

39

Page 40: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

static int PickWinner(int userCh, int computerCh) { int winner = 0;

if (userCh == computerCh) winner = 0;

else if (computerCh == ROCK) { if (userCh == PAPER) winner = USER; else // userCh = scissors winner = COMPUTER; } else if (computerCh == PAPER) { if (userCh == ROCK) winner = COMPUTER; else // userCh = scissors winner = USER; } else // computerCh = scissors { if (userCh == ROCK) winner = USER; else winner = COMPUTER; } return winner; } //End PickWinner() 40

Page 41: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Display user choice

Display computer choice

Display the winner

Here is the activity diagramfor the method we need to display the winner.

What is it’s job (service)?What data does it need?What should it return?

41

Page 42: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

The Method Prologue

// --------------- DisplayResults Method ----------------// Purpose: displays each choice and the winner// Parameters: computer choice, user choice, winner// Returns: nothing (void)// Pre-conditions: none// Post-conditions: none

42

Page 43: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Display user choice

Display computer choice

Display the winner

static void DisplayResults(int userCh, int computerCh, int winR) { Console.Write("You chose "); if (userCh == ROCK) Console.WriteLine("Rock."); else if (userCh == PAPER) Console.WriteLine("Paper"); else Console.WriteLine("Scissors");

Console.Write("I chose "); if (computerCh == ROCK) Console.WriteLine("Rock"); else if (computerCh == PAPER) Console.WriteLine("Paper"); else Console.WriteLine("Scissors");

if (winR == 0) Console.WriteLine("It is a tie."); else if (winR == USER) Console.WriteLine("You win."); else Console.WriteLine("I win.");

Console.WriteLine(); }//End DisplayResults()

43

Page 44: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Prompt the user to make a choice (y/n)

Get the users input

Is theinput valid

?

no

Here is the activity diagramfor the method we need to decide if the user wants toPlay again..

What is it’s job (service)?What data does it need?What should it return?

Return the choice

44

Page 45: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

The Method Prologue

// The PlayAgain method// Purpose: get user answer to “playa gain?”// Parameters: none// Returns: the user’s choice (y or n)// Pre-conditions: none// Post-conditions: none

45

Page 46: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Prompt the user to make a choice (y/n)

Get the users input

Is theinput valid

?

no

static char PlayAgain() { char answer = ‘N’;

do { Console.Write("Do you want to play again? "); answer = char.Parse(Console.ReadLine()); answer = char.ToLower(answer);

if (answer != 'y' && answer != 'n') Console.WriteLine("Invalid response.");

} while (answer != 'y' && answer != 'n');

return answer; }//End PlayAgain()

Return the choice

46

Page 47: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Now with these methods, ourMain( ) method just looks like …

static void Main() { // declarations int userChoice = 0, computerChoice = 0; int winner = 0; char yn = ‘N’;

Console.WriteLine("Play Rock, Paper, and Scissors"); do { userChoice = GetUserChoice(); computerChoice = GetComputerChoice(); winner = PickWinner(userChoice, computerChoice); DisplayResults(userChoice, computerChoice, winner); yn = playAgain(); yn = char.ToLower(yn); } while (yn == 'y');

Console.ReadLine(); }//End Main()

47

Page 48: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Revisit The Rounding Issue

C# does not provide a method that rounds. Let’s write a method that rounds a double tothe nearest integer, using the floor method.

48

Page 49: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

3 4

for any value n, in this range Math.Floor (n ) = 3.

3.5

but … in this rangeMath.Floor(n + 0.5) = 4.0

49

Page 50: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

static int Round (double number){ return (int)(Math.Floor(number + 0.5));}

So, we can write the method Round( ) as follows:

50

Page 51: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

ScopeScope has to do with where a variable can be seen.

global variables (class level variables)

local variables (method level variables)

51

Page 52: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

A related term is storage class or lifetime, which defines how longa variable exists within a program.

automatic variables – come into existence when theyAre declared, and exist until the block in which they aredeclared is left..

static variables – exist for the lifetime of the program

Class level variables – exist for the lifetime of the program(const’s at the class level)

52

Page 53: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Exampleusing System;

class Program{ static string globalValue = "I was declared outside any method"; static void Main() { Console.WriteLine("Entering main( ) ..."); string localValue = "I was declared in Main( )"; SomeMethod( ); Console.WriteLine("Local value = {0}", localValue); Console.ReadLine( ); }//End Main()

static void SomeMethod( ) { Console.WriteLine("Entering SomeMethod( )..."); string localValue = "I was declared in SomeMethod( )"; Console.WriteLine("Global value = {0}", globalValue); Console.WriteLine("Local value = {0}", localValue); }//End SomeMethod()}//End class Program

global variables must be declared outsideof any method. They need to be declared withina class as static. Constants are automatically static.

the name localValueis used twice. In this casethe scope of localValueis inside of Main( ). It isa local variable.

localValue is also declaredin this method, but itsscope is just inside themethod. It cannot be seenoutside of the method. Itis a different variable than the one declared in Main( ).It is a local variable. 53

Page 54: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

54

Page 55: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

BlocksAnytime we use curly braces to delineate a piece of code,that code is called a block. We can declare variables thatare local to a block and have block scope.

Local variables declared in a nested block are onlyknown to the block that they are declared in.

When we declare a variable as part of a loop, for examplefor (int j = 0; j< MAX; j++)…

the variable j will have the block of the loop as its scope.

55

Page 56: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Static VariablesA static variable comes into existence when it is declared and itlives until the program ends. A static variable has class scope –that is, it is visible to all of the methods in the class. Static variables live in the data segment.

56

Page 57: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

PracticeWrite the prologue for a method named CalcRatiothat takes two integer parameters and returns a double.

57

Page 58: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

PracticeWrite the code for this method. The ratiois found by dividing the first parameter by the second.

58

Page 59: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

Practice

Write a complete program that(1) gets two input values from the user(2) passes those values to the CalcRatio method(3) displays the result

59

Page 60: Methods Version 1.1. Topics Built-in methods Methods that return a value Methods that do not return a value (void methods) Random number generators Programmer.

PracticeWrite a program that converts dollar values into another currency. The program should work as follows:(1) Prints an introduction to the program(2) Gets a currency conversion factor and currency name from user(3) Gets a dollar value(4) Calls a method CalcConvertedValue( ) and displays answer (5) Asks if the user wants to do another conversion(6) If the answer is yes, go back to step 3(7) Ask if the user wants to do a different conversion(8) If the answer is yes, go back to step 2

60