Functions, Interfaces, Parameters 8.1 – 8.2. include using namespace std; int main ( ) { int cal, fatGrams, fatCal; float fatPercent; cout << “enter the.

Slides:



Advertisements
Similar presentations
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Advertisements

Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
Chapter 6: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
Chapter 6: User-Defined Functions I
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Functions Modules in C++ are called functions and classes
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: Functions.
Chapter 7 Functions.
1 Chapter 7 Functions. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 Chapter 9 Scope, Lifetime, and More on Functions.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: User-Defined Functions
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Chapter 8 Functions. Chapter 8 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 Functions. 2 Chapter 7 Topics  Writing a Program Using Functional Decomposition  Writing a Void Function for a Task  Using Function Arguments and.
CPS120: Introduction to Computer Science Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task.
Cosc175/module.ppt1 Introduction to Modularity Function/procedures void/value-returning Arguments/parameters Formal arguments/actual arguments Pass by.
1 CS161 Introduction to Computer Science Topic #9.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
CPS120 Introduction to Computer Science Iteration (Looping)
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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 ICS103 Programming in C Lecture 8: Functions I.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
1 Chapter 9 Scope, Lifetime, and More on Functions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
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 Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
User-Written Functions
Chapter 6: Modular Programming
Programmazione I a.a. 2017/2018.
Introduction to Functions
Chapter 9 Scope, Lifetime, and More on Functions
CPS120: Introduction to Computer Science
Chapter 8 Functions.
CPS125.
Presentation transcript:

Functions, Interfaces, Parameters 8.1 – 8.2

include using namespace std; int main ( ) { int cal, fatGrams, fatCal; float fatPercent; cout << “enter the number of calories”; cin >> cal; cout << “enter the number of fat grams;” cin >> fatGrams; fatCal = fatGrams * 9; fatPercent = (float(fatCal)/cal)*100; cout << “number of calories: “ << cal << endl; cout << “percent of calories from fat is: “ << fatPercent << endl; if fatCal < (.3 * cal) // or if fatCal<(fatPercent*cal/100) cout << “Your diet is lowfat!”; return 0; }

Use Indentation to Show Semantics if ( x < y) if ( y > 5) cout << “11111” << endl; else cout << “22222” << endl; cout << “33333” << endl; if ( x < y) if ( y > 5) cout << “11111” << endl; else // matches nearest “if” cout << “22222” << endl; cout << “33333” << endl;

Functions A function is a program unit Every C++ program must have a function called main() – Program execution always begins with this function Any other functions are subprograms, that must be called directly by the main program or another subprogram

Two Types of Functions Value-returning: receives data through its argument list, computes & returns a single value, is used as part of an expression. – y = 3.8 * sqrt(x); diff = fabs(x, y); Void: The function call is a separate stand-alone statement. – GetNextVal(x, y); // hypothetical function Void functions can make programs more readable and can also save coding time if you’re going to use the same code in several places.

Interfaces & Encapsulation A function’s interface is a description of what it does and how we communicate with it; i.e., – How we communicate: the parameter list, values that are “passed in” and values that may be “passed out”. – What the function does: What is the purpose of the function? How do we find out the result of executing the function? Functions as a “black box”: we don’t need to know anything about the implementation in order to use it in our programs; we only need to know how to use it.

Interfaces & Encapsulation Encapsulation: Hiding the implementation of a module in a separate unit or block with an interface, the only way a function communicates with the rest of the program. – Incoming values: passed from the caller to the function – Outgoing values: produced by the function & returned to the caller – Incoming/outgoing values: values that are passed into the function, changed by the function, and returned to the caller. If we know how to call the function and how to interpret the results, we don’t need to know any details of how the function works. (e.g., do you know how the length function works?)

Calling a Function One function calls another by using the name of the function followed by parentheses that enclose a (possibly empty) list of arguments. – Calls are either embedded in expressions, or as separate statements. A function call temporarily transfers control from the calling function to the called function – Thus functions are control statements like loops and decision statements.

Modules and Functions Functional decomposition is the process of reducing a big problem to set of smaller ones (modules) – This process may go through several levels When coded, a module is a set of instructions that has a single logical purpose (print a table, find smallest value in an array, …) When coded as a function, modules can only be executed by making a function call, which means you must know the function interface to use a function.

User-defined Functions: Control Flow (Figure 8.2 – page 360) Main Function A C B // prototypes int main() {... C(); B(); A(); C(); } void A() {... } void B() {... } void C() {... } Here is a program that has a main function and three subordinate functions (see the procedural decomposition above). Traditionally the main function is written first and the function definitions follow. Notice that the function calls, in main, aren’t necessarily in the same order as the function definitions. Also notice that the same function can be called more than once

Functional Decomposition with Void Functions A high-level algorithm is a decomposition of the program into tasks (modules) – You may have to decompose some tasks into smaller tasks – The process stops when you have identified tasks that represent a single logical operation When the process stops, each module/task is coded as a separate void function. Advantages of this approach: – Program development is easier. Write main() first – it should mostly be an outline of the program: a series of function calls – Develop functions 1 or 2 at a time, add in, test – Modular programs are easier to understand and modify – Modules may be reusable

Interfaces: Pre- and Post Conditions A good programming practice is to annotate functions with comments that explain what they do. Precondition: tells what must be true before the function is called. Postcondition: What must be true after the function completes.

Void Functions: Syntax & Semantics Function call – A function must be called in order to run: FunctionName(arguments); Function declaration & definitions – A function must be declared before it is called: FunctionName(parameters); //prototype – A function definition is similar to the prototype but also includes a header statement (similar to the prototype) & the body of the function – the actual code. Local variables

Return Statement (p. 366) Value returning functions have a return statement to tell what value is being returned. Normally, a void function doesn’t have a return value so you don’t need a return statement. Or, if you wish, you can just have a single statement: return; Exception: an abnormal exit from a function. – In case of error you may want to exit function immediately. See example on page 366 – Use of multiple function exits isn’t always considered a good practice as it can lead to confusion about function logic

Local Variables Local variables: a function can define its own variables, called local variables. – They are visible inside the function, but not otherwise – Storage for the variables is created when the function is called, destroyed when the function terminates. – Each function’s variables are private to that function, so you can use the same variable names in different functions and they will refer to different things.

//This program prints a “Welcome Home” message #include using namespace std; void PrintLines(int numLines); // function prototype // numLines = parameter representing number of lines of // asterisks to print int main() { PrintLines(2); // function call: argument = 2 cout << “Welcome Home!” << endl; PrintLines(4); // function call: argument = 4 return 0; } // ************************************************* void PrintLines(int numLines) // function definition { for (int count = 1; count <= numLines; count++) cout << “********************” endl; } // note: no return value; this is a void function.

Program to print a “welcome home” message page 361 //This program prints a “Welcome Home” message #include using namespace std; void PrintLines(int numLines); // prototype // numLines = parameter representing of lines of // asterisks to print int main() { PrintLines(2); // function call argument = 2 cout << “Welcome Home!” << endl; PrintLines(4); // function call: argument = 4 return 0; } // *********************************************** void PrintLines(int numLines) //function definition { for (int count = 1; count <= numLines; count++) cout << “********************” endl; } // note: void function means no return value. Function Prototype: declares the function name, gives parameters so the compiler will know how to process function calls. Prototype: followed by ‘;’ – but not in function definition. The parameter name is optional in the prototype Main function: notice how it gives an outline of what the program does, without giving details. PrintLines is called twice, with a different parameter each time Function definition: this is a void function; it does not return a value. Instead, it performs an operation (printing some lines of asterisks. The definition includes the function header with parameter list: data type, parameter name.

Function Names Since a void function is used like a program command, make the name sound like a command by including a verb – for example PrintLines() Follow the naming convention outlined earlier: user-defined functions capitalize the first letter of each word in the function name.

Parameters Make a function versatile, reusable The user supplies values/variables that will be used by the function when it executes Parameters are part of the interface to the function; you must understand what the parameters represent in order to use the function.

Parameters and Arguments Parameters are used in writing the function (for example numLines in the “welcome home” program). In a function call, arguments specify the actual variables/values that will be used when the function executes. There should be one argument for each parameter, and the types should match

Parameter Types Value parameter: A parameter that receives a copy of the value of the matching argument. Reference parameter: A parameter that receives the location (memory address) of the caller’s argument. How to declare in your program: void Example(int& param1,//reference int param2,//value float param3)// value

Value Parameters The parameter in the “Welcome Home” program is a value parameter. Possible ways to pass an argument to a value parameter: – PrintLines(2); // pass a literal value – PrintLines(num); //pass an int variable – PrintLines(2*x + y); // an expression In other words, anything that has a value can be passed; (i.e. ; any expression) The expression is evaluated and copied into the function parameter.

Parameter Correspondence Arguments and parameters must correspond in number and type. void myFun(int p1, float p2, char ltr) myFun(intVar, 15.25, charVar) For value parameters, the compiler will coerce an argument to match the parameter type if necessary. – E.g.: parameter is an int but your argument is a float. The argument will be coerced to an int.

Reference Parameters A reference parameter is declared with an ampersand (&) at the end of the parameter Instead of a value, the location (address) of the argument is passed to the function. In other words, the argument and the parameter refer to the same location in memory When the function completes, whatever value is in that location is available to the calling function. Reference parameters must match in type – no coercion will be done

#include using namespace std; void f1(float& fl, int x); int main() { float sal = ; int value = 10; fl( sal, value); cout << “sal = “ << sal << “ “; cout << “value = “ << value; return 0; } void f1(float& fl, int x) { f1 = f ; x = x * x; ) sal = value = 10

Arrays as Parameters pages Arrays are automatically passed as reference variables; don’t use the ampersand. When an array is passed its base address is passed – the address of the 1 st element. The function can then access all the elements. But … you must also tell it how many elements

Function with Array Parameter void ZeroOut(int anArray[ ], int n) Pre: anArray: int array with n elements Post: all elements of anArray are zero. { int i; // local variable for (i = 0; i < numElts; i++) anArray[i] = 0; } // Store 0 in all array elements

Passing Arrays as Arguments When you pass an array to a function you just use the array name (no index) For example, if your program has an array values that has MAX_SIZE elements, you would call zeroOut on it as follows: zeroOut(values, MAX_SIZE); NOT zeroOut(values[ ], MAX_SIZE);

Passing Individual Elements Sometimes you will only want to pass one or a few array elements. You can treat them as if they are any simple variables For a function with the following prototype: void f1(int x, int& y); and an array int myArray[10] the following function call is legal: f1(myArray[0], myArray[9])

Things to Remember Be sure you understand the interface to the functions: match parameters and arguments accurately. Also pay attention to semantics; Given the following function and function call void divide(int num, int div, int& quot) { quot = num / div; } & divide (bottom, top, answer); The call is syntactically correct, but if you meant to compute top/bottom it’s semantically incorrect.

More Things to Remember Parameter list in function definition must give data type of each variable and, if the parameter is a reference parameter, it must also have the ampersand. The function call does not have types or ampersands. A parameter should be a value parameter unless the function is designed to change the parameter permanently.