Suppose we want to print out the word MISSISSIPPI in big letters.

Slides:



Advertisements
Similar presentations
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 5 Functions.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Overview creating your own functions calling your own functions.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Introduction to Java Programming, 4E Y. Daniel Liang.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
1 Topic 04 Methods Programming II/A CMC2522 / CIM2561 Bavy Li.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Chapter 5: Methods 1. Objectives To declare methods, invoke methods, and pass arguments to a method (§ ). To use method overloading and know ambiguous.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science Functions.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 6 Functions.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Methods. Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Variables  A piece of memory set aside to store data  When declared, the memory is given a name  by using the name, we can access the data that sits.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 5 Functions Lecturer: Mrs Rohani Hassan.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods.
Reference: COS240 Syllabus
Suppose we want to print out the word MISSISSIPPI in big letters.
Chapter 7: User-Defined Functions II
Chapter 6: Methods CS1: Java Programming Colorado State University
Variables A piece of memory set aside to store data
Chapter 5 Functions DDC 2133 Programming II.
Chapter 5 Function Basics
Chapter 5 Functions.
Chapter 6 Methods 1.
Programmazione I a.a. 2017/2018.
User-Defined Functions
Chapter 5 – Part 2 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Object Oriented Programming COP3330 / CGS5409
Chapter 5 Function Basics
Group Status Project Status.
Functions, Part 1 of 3 Topics Using Predefined Functions
Chapter 6 Methods.
Chapter 5 Methods.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Review for Final Exam.
Week 4 Lecture-2 Chapter 6 (Methods).
Functions, Part 1 of 3 Topics Using Predefined Functions
Functions, Part 1 of 3 Topics Using Predefined Functions
Corresponds with Chapter 5
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Suppose we want to print out the word MISSISSIPPI in big letters. Functions! Suppose we want to print out the word MISSISSIPPI in big letters. * * ** ** * * * * * * * * * * * ********* *

We only really need to describe how to create 4 letters -- M, I, S, P We could write a function for each letter! A function in C++ is a named chunk of statements that performs a single well-defined task. The function’s name is a C++ identifier Same rules as for variable names Choose a name that reflects the task performed by the method Function names typically sound like action verbs or phrases printM Function bodies are placed in the definition of the program, right before the main function. OR Function prototypes can be declared above the main function and function implementations can go after the main function Variables and objects declared in a function can only be used within that function!

So now we need 4 functions: printM printI printS printP void printM() { cout << “* *\n”; cout << “** **\n”; cout << “* * * *\n”; cout << “* * * *\n”; cout << “* * *\n”; cout << endl; } //printM

We call or invoke a function simply by stating its name. printM(); tells the computer to run the function. This causes the following actions to take place: The computer remembers the line where the call took place Control is passed to the function (which means that the entire function is executed). When the function is completed, control is passed back to where the call occurred. Program execution continues there.

We would also define the other functions. The body of main will look like: void main() { printM(); printI(); printS(); printP(); } //main

A C++ program printing the big letter word “Simple” int main () { printS(); printI(); printM(); printP(); printL(); printE(); } //main void printS() { }\\printS void printI() {}\\printI void printM() {}\\printM void printP() {}\\printP void printL() {}\\printL void printE() {}\\printE }

Method Examples Example 1. print 5-star method void print5Stars( ) { int i = 1; while(i <= 5) cout << ‘*’; i++; } Example 2. print 10-star method void print10Stars( ) while(i <= 10)

Method Parameter Example. print N-star method, where N can be ANY integer greater than 1 void printStars(int n) { int i = 1; while(i <= n) cout << ‘*’; i++; }

Calling with Parameters void main() { printStars(5); printStars(10); } Tell the method how many stars you want when you call it.

void printStars(int n) { int i = 1; while(i <= n) cout << ‘*’; i++; } printStars(5); // the above method call specifies that n=5. printStars(10); // the above method call specifies that n=10. printStars(); // the above method call DOES NOT work. Exercise: Write a void method that will print “Simple” with N letters ‘E’ attached to it, where N>0. For example: N=1, print Simplee.

printMax void printMax(double x, double y) { if(x > y) cout << x << “ is bigger”; else cout << y << “ is bigger”; } Write the statement that will call the method printMax to print out the maximum number between 76 and 100.

Most of the time, we want to give function certain values to work with Most of the time, we want to give function certain values to work with. The values that functions accept are called parameters. In order to use a function with parameters, we must know the name of the function and the features of the parameters. These items describe the interface of the function. the number, order, and data type of parameters in the parameter list must match the number and order of the values used when calling the function. the parameters in the function header are called formal parameters the parameters in the call are called actual parameters or arguments we do not use the same variable names for formal and actual parameters!!!!!!! The function name and the parameter list together make up the method signature

void printEcho(string mess, int n) { int i = 1; while(i <= n) cout << mess << endl; i++; } In main method: string message = "Hello"; printEcho(message, 3); Parameters must match. None of these works: printEcho(); printEcho(5, “C++”); printEcho(“C++”); printEcho(4.0, “C++”); printEcho(3, “abc”, 1);

Information Hiding Calling or using a function only requires the caller to know the information in the “signature” or first line of a function definition. The caller or user of a function does not need to know what goes on inside the body of the method. A function can be viewed as a black box (Can’t see inside it) What does this suggest about who can use variables declared inside the body of a function?

A return statement is required for a nonvoid method. A function may return a value. The returnValueType is the data type of the value the function returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is int. A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the C++ compiler thinks it possible that this method does not return any value. int findSign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } To fix this problem, declare a local variable to hold the answer, then return that variable.

Write the function named findMax, which accepts two integers and returns the larger value of the two integers. int findMax(int a, int b) { int bigger; if(a >= b) bigger = a; else bigger = b; return bigger; } Write the method named findAvg, which accepts three integers and returns the average of those three integers.

The Scope of a Variable Think of the entire program as a block. Think of functions as sub-blocks. Each (sub)block can contain a parameter list a declaration section a body (of code) Basically, you can “see” variables/constants in your block, or in any containing or surrounding block. The scope of an identifier refers to the block in which it was declared or defined. Identifiers are available only within their block; they are never available outside their block. Identifiers declared within a function are called local variables.

A local variable: a variable defined inside a function. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. It is legal to declare a local variable with the same name multiple times in different non-nesting blocks in a function, but you cannot declare a local variable twice in nested blocks.

Example A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable.

It is fine to declare the variable i in two non-nesting blocks. // Fine with no errors public static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) x += i; } //for i // i is declared again y += i; } //correctMethod

It is wrong to declare a variable in two nesting blocks. void badIdea() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) int x = 0; x += i; } //for i cout << x; } //badIdea int i = 1;

When an identifier is encountered, its scope determines its value. We do not use the same variable names for formal and actual parameters. We can use the same variable names as the formal parameters of different methods. int max(int a, int b, int c) . . . int min(int a, int b, int c) float avg(int a, int b, int c) high = max(num1, num2, num3); low = min(num1, num2, num3);

Chapter 5 Skip 5.3.1 (for now) Skip 5.6 (for now) Skip 5.9-5.11 Review Exercises 5.1-5.2 5.6-5.11 5.15

The factorial of a positive integer n is defined as n! = n * (n - 1) * (n - 2) * . . . * 2 * 1 for n > 1. Write the function. int factorial(int n) { int ans=1; for (int i = n; i > 1; i--) ans = ans * i; return ans; } Suppose that n>=0. int ans = 1; if (n > 1) for (int i=n; i>1; i--) ans*=i;

Write a function called Arithmetic that accepts 3 parameters (2 integers and one character, which will be either ‘+’, ‘-’, ‘*’, or ‘/’). It returns the result of applying the operator to the two integers. double operateTwoNum(int n1, int n2, char operator) { double ans = 1; switch (operator) case '+': ans = n1 + n2; break; case '-': ans = n1 - n2; case '*': ans = n1 * n2; case '/': ans = (double) n1 / n2; } return ans;