Methods version 1 1
This presentation is the property of its rightful owner.
Sponsored Links
1 / 76

Methods Version 1.1 PowerPoint PPT Presentation


  • 147 Views
  • Uploaded on
  • Presentation posted in: General

Methods Version 1.1. Topics. Built-in methods. Methods that return a value. void methods. Random number generators. Programmer defined methods. Scope. Objectives. At the end of this topic, students should be able to:. Write programs that use built-in methods

Download Presentation

Methods Version 1.1

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Methods version 1 1

MethodsVersion 1.1


Topics

Topics

Built-in methods

Methods that return a value

void methods

Random number generators

Programmer defined methods

Scope


Objectives

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.


Methods version 1 1

At this point we have learned to write quite

complex programs, that contain decisions

and loops.

… but most of our programs are still quite

small and easy to manage.

What if I gave you an assignment to write a program that would contain

5,000 lines of code?


Methods version 1 1

because it is easier to understand what goes on

in a small block (piece) of code.

because we can re-use the same block (piece) of code

many 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

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


Methods version 1 1

As an example, suppose that you have been asked

to write a program to play paper-rock-scissors.


Methods version 1 1

Let’s do a top-down design.

Ask for user’s choice

And get the input

Generate computer’s

choice

Determine winner

Display the results

See if user wants

to play again


Methods version 1 1

Ask for user’s choice

and get the input

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

Get the users input

no

Is the

input valid

?


Methods version 1 1

Generate computer’s

choice

Generate a

Random number

Between 1 and 3


Methods version 1 1

Determine Winner

user =

computer

?

yes

tie

no

user

= paper

?

winner is

user

yes

yes

computer

= rock

?

winner is

computer

no

no

user

= rock

?

winner is

computer

yes

yes

computer

= paper

?

winner is

user

no

no

user

= rock

?

winner is

user

yes

winner is

computer

no


Methods version 1 1

Display the results

Display user choice

Display computer choice

Display the winner


Methods version 1 1

See if user wants

To play again

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

Get the users input

no

Is the

input valid

?

no

Play

Again

?

quit


Methods version 1 1

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 code

that does many different things, it becomes

difficult to visualize what is happening in the

code, and so much harder to get the code

to work correctly.


Methods version 1 1

This is easy to visualize

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

Get the users input

no

Is the

input valid

?


Methods version 1 1

This is much harder

to visualize. We really

can’t even get it on one

page . . . and make it

readable.

tie

quit


Methods version 1 1

So … let’s take each of these pieces and write each as

a separate, stand-alone block of code called a method.

Each method will have one well

defined thing that it does. (Provides

a service.)

Ask for user’s choice

And get the input

Generate computer’s

choice

We will have the ability to give

each method any data that it

needs to do its job.

Determine winner

Display the results

Each method can return to us

the results of its work.

See if user wants

to play again


Methods version 1 1

Method Syntax

These are parameters.

Each parameter has a

data type and a name.

The type of data

returned by this

method.

The method’s

name

method header

static intDetermineWinner( intcompChoice, intuserChoice)

{

// statements

}

The body of the method

is made up of valid C#

statements (providing a service),

enclosed in curly braces.

method block (body)


Methods version 1 1

Just as a reminder … Main( ) is a method which satisfies all the

conditions specified earlier.

Header static void Main()

Block {

(body)

}


Methods version 1 1

General Format of C# Methods

Header static <return type> <method identifer> ( <comma delimited parameter list )

Block {

(body) <statements>

}


Built in methods

Built-in Methods

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

fewer errors

tested under all conditions

Most programming languages, including C#, include

libraries of pre-written and tested methods that do

common programming tasks. In C#, these libraries

are in the .Netlibrary accessed via using statements.


Methods that return a value

Methods that return a value

As an example of a method that returns a value, consider

the Sqrtmethod in the Math class.

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

write

result = Math.Sqrt (9);

this is called a method invocation.

It can be used anywhere an expression

can be used. The Sqrt method belongs

to the Math class.

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 one

argument. If so, they are separated by

commas (a comma delimited list).

the value returned by the function

is called its return value.

A method can only have one

return value.


The math class

The Math class

The Sqrt method is found in the Math class.

Other common functions in the Math class:

namefunction (service)return type

Pow (int x, int y)calculates xydouble

Abs (double n)absolute value of ndouble

Ceil (double n )smallest integer >= ndouble

Floor (double n)largest integer <= ndouble


Rounding

Rounding

When we round a number, we pick the closest integer value.

For example,

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

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

The Ceil and Floor methods given in the previous slide

don’t do rounding. For example,

Math.Floor (2.9) returns 2.0, while

Math.Ceil (2.3) returns 3.0.


Methods that return void

Methods thatreturn void

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

void methods are written as statements. They cannot be used

in an expression, as expressions must return a typed value.

void methods can have zero or more parameters.

void methods can have return; statement.


Methods version 1 1

Writing a Method

What job will the method do?

What data does it need to do it’s work?

What will the method return?


Methods version 1 1

Here is the activity diagram

for the method we need to

write to get the user’s

choice.

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

Get the users input

What is it’s job (service provided)?

What data does it need?

What should it return?

no

Is the

input valid

?


Methods version 1 1

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

* What data the method returns


Methods version 1 1

The Method Prologue

// The GetUserChoicemethod

// Purpose: gets a valid user choice (1-3)

// Parameters: none

// Returns: the user choice as an int


Methods version 1 1

  • static intGetUserChoice( )

  • {

    • intchoice = 0;

  • do

  • {

  • Console.Clear();

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

  • }

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

Get the users input

no

Is the

input valid

?


Methods version 1 1

Here is the activity diagram

for the method we need to

write to get the computer’s

choice.

Generate a

Random number

Between 1 and 3

What is it’s job (service it provides)?

What data does it need?

What should it return?


Methods version 1 1

The Method Prologue

// The GetComputerChoicefunction

// Purpose: generates a random choice (1-3)

// Parameters: none

// Returns: the computer choice as an int

// Pre-conditions: none

// Post-conditions: none


Random number generator

Random Number Generator

The .Net library provides a class that we can use to create

a random number generator. To create a random number

generator object, we write

Random randoms = new Random( );

This initializes the Random object.

This is the reference

to the Random object.

This creates the Random object in the Heap.


Random number generator1

Random Number Generator

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

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


Random number generator2

Random Number Generator

To shift the range of the random numbers, for example, to get

a random number between 1 and 3, use this form of the Next

method:

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

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

Start at 1


Random number generator3

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 compiler


Methods version 1 1

static intGetComputerChoice( )

{

int choice;

choice = randoms.Next(1,4);

return choice;

}

Generate a

Random number

Between 1 and 3

We created the Random object randoms elsewhere.


Methods version 1 1

user =

computer

?

yes

Here is the activity diagram

for the method we need to

write to get the computer’s

choice.

tie

no

user

= paper

?

winner is

user

yes

yes

computer

= rock

?

winner is

computer

no

no

user

= rock

?

winner is

computer

yes

yes

computer

= paper

?

winner is

user

no

no

user

= rock

?

winner is

user

yes

What is it’s job (service)?

What data does it need?

What should it return?

winner is

computer

no


Methods version 1 1

The Method Prologue

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


Methods version 1 1

static intPickWinner(intuserCh, intcomputerCh)

{

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


Methods version 1 1

Here is the activity diagram

for the method we need to

display the winner.

Display user choice

Display computer choice

What is it’s job (service)?

What data does it need?

What should it return?

Display the winner


Methods version 1 1

The Method Prologue

// The DisplayResults method

// Purpose: displays each choice and the winner

// Parameters: computer choice, user choice, winner

// Returns: nothing (void)

// Pre-conditions: none

// Post-conditions: none


Methods version 1 1

static void DisplayResults(intuserCh, intcomputerCh, intwinR)

{

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

Display user choice

Display computer choice

Display the winner


Methods version 1 1

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

Here is the activity diagram

for the method we need to

decide if the user wants to

Play again..

Get the users input

no

Is the

input valid

?

What is it’s job (service)?

What data does it need?

What should it return?

Return the choice


Methods version 1 1

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


Methods version 1 1

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

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

Get the users input

no

Is the

input valid

?

Return the choice


Methods version 1 1

Now with these methods, our

Main( ) method just looks like …

static void Main()

{

// declarations

intuserChoice = 0, computerChoice = 0;

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


Revisit the rounding issue

Revisit The Rounding Issue

C# does not provide a method that rounds.

Let’s write a method that rounds a double to

the nearest integer, using the floormethod.


Methods version 1 1

for any value n, in this range

Math.Floor(n ) = 3.

3.5

4

3

but … in this range

Math.Floor(n + 0.5) = 4.0


Methods version 1 1

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

static intRound(double number)

{

return (int)(Math.Floor(number + 0.5));

}

Note that the Math class has a Round method

That works just this way.


Scope

Scope

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

global variables (class level variables)

local variables (method level variables)


Methods version 1 1

A related term is storage class or lifetime, which defines how long

a variable exists within a program.

automaticvariables – come into existence when they

are declared, and exist until the block in which they are

declared is left..

staticvariables – exist for the lifetime of the program

Class level variables – exist for the lifetime of the program

(const’s at the class level)


Example

global variables must be declared outside

of any method. They need to be declared within

a class as static. Constants are automatically static.

Example

using System;

static 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

the name localValue

is used twice. In this case

the scope of localValue

is inside of Main( ). It is

a localvariable.

localValue is also declared

in this method, but its

scope is just inside the

method. It cannot be seen

outside of the method. It

is a different variable than

the one declared in Main( ).

It is a local variable.


Blocks

Blocks

Anytime we use curly braces to delineate a piece of code,

that code is called a block. We can declare variables that

are local to a block and have block scope.

Local variables declared in a nested block are only

known to the block that they are declared in.

When we declare a variable as part of a loop, for example

for (int j = 0; j< MAX; j++)

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


Static variables

Static Variables

A static variable comes into existence when it is declared and it

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


Methods version 1 1

The PseudoCode Programming Process

From “Code Complete” by Steve McConnell


Methods version 1 1

Step One: Before doing any work on the

method itself, make sure that the method

is really required, and that the job of the

method is well defined. Methods should do

one thing!


Methods version 1 1

Step Two: Clearly state the problem that the

method will solve.

- What does it do

- What are its inputs

- What are its outputs


Methods version 1 1

Step Three: Write a method prologue

- The method name

- Purpose

- Parameters

- Return value


Methods version 1 1

Step Four: Think about how you will test

your method once it is written. Write down

some test cases (input and output)


Methods version 1 1

Step Five: Research available code libraries

and algorithms … has someone else written the

code that you need?


Methods version 1 1

Step Six: Write the Pseudocode for your

method.


Methods version 1 1

Step Seven: Walk through your pseudocode

and see if it makes sense. Does it work? If not --

revisit your design.


Methods version 1 1

Step Eight: Write down the method declaration

(the first line of the method)


Methods version 1 1

Step Nine: Add your pseudocode to your program

as comments.


Methods version 1 1

Step Ten: Fill in the actual code below

each set of comments (pseudocode)


Methods version 1 1

Step Eleven: Walk through your code,

mentally check for errors.


Methods version 1 1

Step Twelve: Compile your code – fix

syntax errors.


Methods version 1 1

Step Thirteen: Use your test cases to see if

your method works correctly.


Practice

Practice

Write the prologue for a method named CalcRatio

that takes two integer parameters and returns a double.


Practice1

Practice

Write the code for this method. The ratio

is found by dividing the first parameter by the second.


Practice2

Practice

Write a complete program that

(1) gets two input values from the user

(2) passes those values to the CalcRatiomethod

(3) displays the result


Practice3

Practice

Write 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) Calculates and displays the value in the new currency

(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

-- Write a method to do the currency calculation


Methods version 1 1

Some Sample Exchange Rates

$1.00 = 0.679459 Euros

$1.00 = 13.3134 Mexican Pesos

$1.00 = 1.04338 Canadian Dollars


Methods version 1 1

Assume that we have used Functional

Decomposition to break this problem up

into pieces, and have determined that

we need a method that does the actual

currency conversion.


Methods version 1 1

Use the Pseudocode Programming Process

to develop the code for this method.


  • Login