CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
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.
Chapter 5 Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Chapter 7: User-Defined Methods
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
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.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
CMSC 202 Lesson 8 Classes II. Warmup Declare a class (.h part) named “Cup” It has a data member that says how full it is One method called “Drink” that.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Chapter 6 CS 3370 – C++ Functions.
Why exception handling in C++?
CMPT 201 Functions.
CSC113: Computer Programming (Theory = 03, Lab = 01)
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 9 Scope, Lifetime, and More on Functions
CMSC 202 Lesson 6 Functions II.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
FOR statement a compact notation for a WHILE e.g. sumgrades = 0;
CMSC 202 Lesson 20 Exceptions 1.
CMSC 202 Lesson 5 Functions I.
Presentation transcript:

CMSC 202 Lesson 5 Functions I

Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

C++ Functions Predefined Functions  cmath library sqrt(x) – takes the sqrt of x pow(x, n) – computes x n  cstdlib library abs(x) – integer absolute value exit(x) – end program  assert library assert(z) – ends program if z is false  Tip: pay attention to the parameter types for these! The libraries are VERY particular

Functions You are familiar with functions that…  Return a value  Do not return a value (void)  Have parameters (primitives, structs, arrays)  Have no parameters  Call other functions

Functions New stuff  Scope (partial review…)  Parameters Call by value Call by reference Constant Default  Function return types  Function overloading

Functions - Design Abstraction  Hiding the details…  Do not need to know how a function works to use it Pre-conditions  Comment describing constraints on parameter values to ensure proper function execution Post-conditions  Comment describing state of the program after function execution VERY IMPORTANT!!!

Pre/Post-condition Example // // Function: ShowInterest // PreCondition: // balance is a nonnegative savings account balance // rate is the interest rate expressed as a percent // such as 5 for 5% // PostCondition: // the amount of interest for the given balance at the // given rate is displayed to cout. // if the parameters are invalid, "No Interest" is displayed // void ShowInterest( double balance, double rate ) { if (balance >= 0 && rate >=0) { // code to calculate and display interest } else { cout << "No Interest\n"; }

Preconditions How to write a good precondition?  Describe assumptions/limitations of each parameter Ex: denominator cannot be equal to zero  Describe assumptions/limitations of the program state Ex: global array “students” must have at least one student in it What must the function do?  Test every precondition!!! Ex: if (denominator == 0) cerr << “Error: Denom == 0” << endl; Ex: if (NbrOfStudents < 1) cerr << “Error: NbrOfStud < 1” << endl;

Preconditions How to deal with unmet preconditions?  Handle the error by returning a “safe” value or printing an error Prefer NOT to print errors from functions!  Return a status value  Throw an exception (later…)  Last resort: Abort the program (exit or assert)

Postconditions How to write a good postcondition?  Describe all possible message from the function Ex: Error message is printed if preconditions are violated  Describe all possible return values Ex: Return value is 0 if an error is encountered, otherwise, a positive value representing the current rate calculated is returned What must the function do?  Functionality must match postcondition claims!

Scope Area of a program where a variable is defined  Denoted with { }  Can be nested Types of Scope  Global Scope Outside of all functions Entire file can use global variables  Local Scope Within a pair of { } Only other code within the { } can use these If name conflict, overrides the outer-scope Getting back to global?  :: scope resolution operator  Accesses global variable if name conflict

Scope Issues int a = 1; int doubleVal(int a) { return 2 * a; } int main() { a = doubleVal(a + 7); { char a = ‘a’; a = a + 1;// ‘a’ + 1 => ‘b’ ::a = ::a + 1;// => 17 } return 0; }

Scope Rules Variables can be declared anywhere  Declare them when you need them… Global variables should always be constant!  Not all constants should be global For loops – initializer list is scoped inside the for loop  for (int i = 0; …)// i is INSIDE the loop Try to avoid reusing variable names…

Function Parameters Argument  Value/variable passed IN to a function Parameter (or Formal Parameter)  Variable name INSIDE the function Call-by-Value  Changes to the parameter do not affect the argument  Syntax: retType funcName( type varName, … ){ … }

Call by Value Example void mystery(int b) { b++; cout << b << endl; } int main() { int a = 7; mystery(a); cout << a << endl; return 0; } b : 7 a : 7 Copy value Allocate

Call by Reference  Changes to the parameter change the argument Function declares that it will change argument  Share memory Essentially a pointer  Syntax: retType funcName( type &varName, … ){ … } Look familiar? Works “backwards”

Call by Reference Example void mystery(int &b) { b++; cout << b << endl; } int main() { int a = 7; mystery(a); cout << a << endl; return 0; } a : 7 Allocate Use this space b:

Value versus Reference? Why choose value or reference?  Value Data going in, nothing coming out Only one piece of data coming out (return it!)  Reference Need to modify a value Need to return more than one piece of data Passed an array (by default are by reference, no ‘&’ needed)

Call-by-Reference – Issue! What happens in the following? void mystery(int &b) { b++; cout << b << endl; } int main() { mystery(6); return 0; }

Practice What is printed in the following code block? void mystery(int a, int &b) { a++; b++; cout << a << “ “ << b << endl; } int main() { int a = 1; int b = 1; mystery(a, b); mystery(b, a); mystery(a, a); cout << a << “ “ << b << endl; return 0; }

Challenge Write a function named “getInfo”  Accepts 3 parameters: First name Last name Age  Ask the user to give you these 3 pieces of information Write a main function that will use getInfo to retrieve this information Think about:  Will you use value or reference?