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

Methods PowerPoint PPT Presentation


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

Methods. Topics. Top Down Design. Built-in methods. Methods that return a value. Void methods. Programmer defined methods. Scope. Objectives. At the end of this topic, students should be able to:. Break a problem into smaller pieces. Write programs that use built-in methods

Download Presentation

Methods

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

Methods


Topics

Topics

Top Down Design

Built-in methods

Methods that return a value

Void methods

Programmer defined methods

Scope


Objectives

Objectives

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

Break a problem into smaller pieces

Write programs that use built-in methods

Know how to use methods in the Math library

Correctly write and use methods in a program

Describe what scope is and how it affects the execution

of a program.

Effectively use the pseudo-code programming process


Methods

You have already seen methods used

In a couple of different places

  • As event handlers in GUI programs

  • As members of a class


Methods

In this set of slides we will explore the use

of methods as a way of breaking a problem

into smaller pieces where each piece is easier to solve.


Methods

At this point you have learned to write quite

complex programs, that contain decisions

and loops.

… but most of your programs are still quite

small and easy to manage.

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


Methods

A big Problem

that’s hard to

solve


Methods

A smaller problem

that is easier to solve

A smaller problem

that is easier to solve

A smaller problem

that is easier to solve


Methods

We do this 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, and

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

because it allows a team of programmers to work on

different part of a program in parallel

we call this functional decomposition

-- breaking the program down into more

manageable blocks (pieces).

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


Methods

You have already written quite a few methods.

In the Graphical User Interface programs that

you have written, the event handlers you have

written are methods.


Methods

As an example, consider a program

to play a dice game.


Methods

Let’s do a top-down design.

Tell the user what we are going to do

Declare some variables

Roll the dice

Display the results

See if user wants

to play again


Methods

Let’s do a top-down design.

Tell the user what we are going to do

Declare some variables

You could write all of this code

in a big long Main( ) routine.

Roll the dice

Display the results

See if user wants

to play again


Methods

Let’s do a top-down design.

Tell the user what we are going to do

Declare some variables

Or … you can break the problem

up into smaller pieces, and write

a method to do each piece.

Roll the dice

Display the results

See if user wants

to play again


Methods

Let’s do a top-down design.

Tell the user what we are going to do

boxcars

Display

“boxcars”

Declare some variables

snake

eyes

Display

“snake-eyes”

Roll the dice

Display the results

Display

value of dice

See if user wants

to play again


Methods

Let’s do a top-down design.

Tell the user what we are going to do

ask … do you

want to play

again (y or n)?

Declare some variables

Get the user’s

Input. Save it

in “again”

Roll the dice

Display the results

not y or n

Display

“invalid input”

See if user wants

to play again


Methods

Writing these as methods

boxcars

Display

“boxcars”

A method will have one well

defined thing that it does.

snake

eyes

Display

“snake-eyes”

We will have the ability to give

a method any data that it

needs to do its job.

Display

value of dice

If appropriate, a methodcan

return the results of its work.


Methods

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

intWiggleYourEars( intparameter1, intparameter2)

{

// statements

}

method header

The body of the method

is made up of valid C#

statements (providing a service),

enclosed in curly braces.

method block (body)


Methods

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

conditions specified earlier.

Header static void Main()

Block {

(body)

}


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


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, we call the Next( ) method that is

declared as part of the Random class. The Next method looks

like this:


Random number generator2

Random Number Generator

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 generator3

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 generator4

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 that don t return a value

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 used

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

void methods can have zero or more parameters.


Methods

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

Here is the activity diagram

for the method we need to

write to display the output of

a roll.

boxcars

Display

“boxcars”

snake

eyes

Display

“snake-eyes”

What is it’s job (service provided)?

What data does it need?

What should it return?

Display

value of dice


Methods

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

The Method Prologue

// The DisplayResultsmethod

// Purpose: show the results of rolling the dice

// Parameters: two integer values, the dice

// Returns: nothing


Methods

This method

does not

return a value.

boxcars

Display

“boxcars”

snake

eyes

void DisplayResults(int d1, int d2)

{

}

Display

“snake-eyes”

Display

value of dice

This method takes two parameters,

the value of the dice that were

thrown.


Methods

boxcars

Display

“boxcars”

static void DisplayResults(int d1, int d2)

{

Console.Write("You rolled ");

if (d1 == BOX && d2 == BOX)

Console.WriteLine("Box Cars");

else if (d1 == SNAKE && d2 == SNAKE)

Console.WriteLine("Snake Eyes");

else

Console.WriteLine("{0} and {1}", d1, d2);

}

snake

eyes

Display

“snake-eyes”

Display

value of dice


Methods

ask … do you

want to play

again (y or n)?

Here is the activity diagram

for the method we need to

see if the user wants to roll

again.

Get the user’s

Input. Save it

In “again”

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

What data does it need?

What should it return?

not y or n

Display

“invalid input”


Methods

The Method Prologue

// The GoAgain method

// Purpose: get and validate the user’s input

// Parameters: none

// Returns: the computer choice as a boolean

// true – go again

// false - quit


Methods

static boolGoAgain()

{

const char YES = 'y';

const char NO = 'n';

char yn = YES;

do

{

Console.Write("Do you want to roll again (y or n)? ");

yn = char.Parse(Console.ReadLine());

yn = char.ToLower(yn);

if (yn != YES && yn != NO)

Console.WriteLine("Invalid input.");

} while (yn != YES && yn != NO);

if (yn == YES)

return true;

else

return false;

}

}

ask … do you

want to play

again (y or n)?

Get the user’s

Input. Save it

In “again”

not y or n

Display

“invalid input”


Methods

Now with these methods, our

Main( ) method just looks like this:

static void Main(string[] args)

{

int die1, die2;

Random dice = new Random( );

do

{

die1 = dice.Next(1, BOX+1);

die2 = dice.Next(1, BOX + 1);

DisplayResults(die1, die2);

} while (GoAgain( ) );

Console.WriteLine("Thanks for playing ... goodbye");

Console.ReadLine( );

} // end of Main

We could combine

these into a single

method, but we like a

method to do one thing.


Scope

Scope

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

global variables (class level variables)

local variables (method level variables)


Methods

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;

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

The PseudoCode Programming Process

From “Code Complete” by Steve McConnell


Methods

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

Step Two: Clearly state the problem that the

method will solve.

- What does it do

- What are its inputs

- What are its outputs


Methods

Step Three: Write a method prologue

- The method name

- Purpose

- Parameters

- Return value


Methods

Step Four: Think about how you will test

your method once it is written. Write down

some test cases (input and output)


Methods

Step Five: Research available code libraries

and algorithms … has someone else written the

code that you need?


Methods

Step Six: Write the Pseudocode for your

method.


Methods

Step Seven: Walk through your pseudocode

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

revisit your design.


Methods

Step Eight: Write down the method declaration

(the first line of the method)


Methods

Step Nine: Add your pseudocode to your program

as comments.


Methods

Step Ten: Fill in the actual code below

each set of comments (pseudocode)


Methods

Step Eleven: Walk through your code,

mentally check for errors.


Methods

Step Twelve: Compile your code – fix

syntax errors.


Methods

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

Some Sample Exchange Rates

$1.00 = 0.679459 Euros

$1.00 = 13.3134 Mexican Pesos

$1.00 = 1.04338 Canadian Dollars


Methods

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

Use the Pseudocode Programming Process

to develop the code for this method.


  • Login