Methods.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Modular Programming With Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
Chapter 6: User-Defined Functions I
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Chapter 6: User-Defined Functions I
Introduction to Methods
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Input, Output, and Processing
Methods Version 1.1. Topics Built-in methods Methods that return a value void methods Random number generators Programmer defined methods Scope.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
CPS120: Introduction to Computer Science Lecture 14 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
1 CS161 Introduction to Computer Science Topic #9.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
Topics Designing a Program Input, Processing, and Output
User-Written Functions
Topics Introduction to Functions Defining and Calling a Void Function
Chapter 6: User-Defined Functions I
Learning to Program D is for Digital.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Iterative Constructs Review
JavaScript: Functions
CMPT 201 Functions.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Functions CIS 40 – Introduction to Programming in Python
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 4 – Control Structures Part 1
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
Functions Declarations CSCI 230
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter 4 void Functions
Chapter 6 - Functions Outline 5.1 Introduction
CHAPTER 6 GENERAL-PURPOSE METHODS
Chapter 6: User-Defined Functions I
Chapter 9: Value-Returning Functions
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Lesson #6 Modular Programming and Functions.
Topics Designing a Program Input, Processing, and Output
In C Programming Language
Topics Designing a Program Input, Processing, and Output
CS 144 Advanced C++ Programming January 31 Class Meeting
Presentation transcript:

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

You have already seen methods used as Event Handlers in GUI programs.

Methods allow us to break a program into small pieces where each piece is easier to solve than the program as a whole. Methods also provide us with a way of using the same code over and over again in the same program, or even re-using the code in a different program. Method parameters allow us to us methods with different sets of data each time the method is called.

So far the programs you have written have been quite small, and not overly complex. But what if I gave you an assignment to write a complex console program that would contain 50,000 lines of code?

A big Problem that’s hard to solve

A smaller problem that is easier to solve A smaller problem that is easier to solve A smaller problem that is easier to solve

We often write a program as a series of pieces or blocks we call this functional decomposition -- breaking the program down into more manageable blocks (pieces). in C# these smaller blocks (pieces) are called 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 because it allows a team of programmers to work on different part of a program in parallel

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.

As an example, consider a program that you might write that works with a speed detection radar system.

A radar gun emits a beam of microwaves at some frequency f0. The beam bounces off an approaching car and is reflected back to the radar gun. The frequency of the returned beam is shifted slightly from f0 to f1 due to the motion of the car.

The speed of the car, v, can be calculated using the formula v = (6.685 X 108)(f1 – f0)/(f1 + f0)

Let’s do a top-down design. Tell the user what we are going to do Declare some variables Get the transmitted frequency Get the received frequency Calculate the speed Display the results

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. Get the transmitted frequency Get the received frequency Calculate the speed Display the results

Let’s do a top-down design. Tell the user what we are going to do Declare some variables Get the transmitted frequency Or … you can break the problem up into smaller pieces, and write a method to do each piece. Get the received frequency Calculate the speed Display the results

Let’s do a top-down design. Tell the user what we are going to do Declare some variables Get the transmitted frequency We can write a Simple method for each step. Get the received frequency Calculate the speed Display the results

Writing the methods A method will have one well defined thing that it does. We will have the ability to give a method any data that it needs to do its job. If appropriate, a method can return the results of its work.

Method Syntax int WiggleYourEars( int parameter1, int parameter2) { 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 int WiggleYourEars( int parameter1, int parameter2) { // statements } The body of the method is made up of valid C# statements that provide a service, enclosed in curly braces. method block (body)

Just as a reminder … Main( ) is a method which satisfies all the conditions specified earlier. Header static void Main( ) Block { (body) }

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 .Net library, accessed via using statements.

Methods that return a value As an example of a method that returns a value, consider the Sqrt method 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 Sqrt method is found in the Math class. Other common functions in the Math class: name function (service) return type 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

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

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

Consider the method we will use to prompt the user and get the user’s input. What is it’s job (service provided)? What data does it need? What should it return?

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

The Method Prologue // The getDouble Method // Purpose: Prompt the user and get a double value // Parameters: The user prompt // Returns: the double value entered by the user

static double GetDouble(string prompt) { This method returns a double. static double GetDouble(string prompt) { } This method takes one parameter. This is the string we will use to prompt the user.

// The getDouble Method // Purpose: Prompt the user and get a double value // Parameters: The user prompt // Returns: the double value entered by the user static double GetDouble(string prompt) { // declare a double to sore user input double value; // prompt the user WriteLine(prompt); // get the input and return it value = double.Parse(ReadLine()); return value; }

Now consider the method that displays the output. What is it’s job (service it provides)? What data does it need? What should it return?

The Method Prologue // The outPutDouble method // Purpose: Outputs a double with 2 digits after the decimal // Parameters: then value to output // Returns: none

// The outPutDouble method // Purpose: Outputs a double with 2 digits after the decimal // Parameters: then value to output // Returns: none static void outputDouble(double value) { WriteLine($"{value:f2}"); }

Now consider the method that calculates the speed of the car. What is it’s job (service it provides)? What data does it need? What should it return?

The Method Prologue // The findSpeed Method // Purpose: Calculate the speed of an oncoming car // Parameters: The frequency of the sent signal and the // frequency of the received signal // Returns: the speed of the car

// The findSpeed Method // Purpose: Calculate the speed of an oncoming car // Parameters: The frequency of the sent signal and // the frequency of the received signal // Returns: the speed of the car static double findSpeed(double f0, double f1) { // declarations const double SPEED_FACTOR = 6.685e8; double speed = 0; // formula for calculating speed speed = SPEED_FACTOR * (f1 - f0) / (f1 + f0); // return it return speed; }

Now with these methods, our Main( ) method just looks like this: static void Main() { // Tell the user what the program does WriteLine("This program finds the speed of an oncoming car,"); WriteLine("given the frequency of the transmitted radar beam and"); WriteLine("the frequency of the received radar beam."); // declare some variables double transmittedFreq, receivedFreq; // prompt the user and get the transmitted frequency transmittedFreq = GetDouble("\nEnter transmitted frequency: “); // prompt the user and get the received frequency receivedFreq = GetDouble("\nEnter received frequency: "); // call the method to compute the speed double speedOfCar = findSpeed(transmittedFreq, receivedFreq); // output the result Write("\nThe speed of the oncoming car in mph: "); outputDouble(speedOfCar); Console.ReadLine(); }//End Main()

Scope Scope has to do with where a variable can be seen. global variables (class level variables) local variables (method level variables)

A related term is storage class or lifetime, which defines how long a variable exists within a program. automatic variables – come into existence when they are declared, and exist until the block in which they are declared 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)

Example global variables must be declared outside of any method. They need to be declared within a class as static. Constants are automatically static. using System; class Program { static string globalValue = "I was declared outside any method"; static void Main() WriteLine("Entering main( ) ..."); string localValue = "I was declared in Main( )"; SomeMethod( ); WriteLine("Local value = {0}", localValue); ReadKey(true); }//End Main() static void SomeMethod( ) WriteLine("Entering SomeMethod( )..."); string localValue = "I was declared in SomeMethod( )"; WriteLine("Global value = {0}", globalValue); }//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 local variable. 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 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 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.

The PseudoCode Programming Process From “Code Complete” by Steve McConnell

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!

Step Two: Clearly state the problem that the method will solve. - What does it do - What are its inputs - What are its outputs

Step Three: Write a method prologue - The method name - Purpose - Parameters - Return value

Step Four: Think about how you will test your method once it is written. Write down some test cases (input and output)

Step Five: Research available code libraries and algorithms … has someone else written the code that you need?

Step Six: Write the Pseudocode for your method.

Step Seven: Walk through your pseudocode and see if it makes sense. Does it work? If not -- revisit your design.

Step Eight: Write down the method declaration (the first line of the method)

Step Nine: Add your pseudocode to your program as comments.

Step Ten: Fill in the actual code below each set of comments (pseudocode)

Step Eleven: Walk through your code, mentally check for errors.

Step Twelve: Compile your code – fix syntax errors.

Step Thirteen: Use your test cases to see if your method works correctly.

Practice Write the prologue for a method named CalcRatio that takes two integer parameters and returns a double.

Practice Write the code for this method. The ratio is found by dividing the first parameter by the second.

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

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 -- Write a method to do the currency calculation

Some Sample Exchange Rates $1.00 = 0.679459 Euros $1.00 = 13.3134 Mexican Pesos $1.00 = 1.04338 Canadian Dollars

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.

Use the Pseudo-code Programming Process to develop the code for this method.