Functions in C++ Eric Roberts CS 106B January 9, 2013.

Slides:



Advertisements
Similar presentations
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions.
Advertisements

Chapter 7: User-Defined Functions II
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 5 Functions.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
 Monday, 9/30/02, Slide #1 CS106 Introduction to CS1 Monday, 9/30/02  QUESTIONS (on HW02, etc.)??  Today: Libraries, program design  More on Functions!
CS 201 Functions Debzani Deb.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Recursion In general there are two approaches to writing repetitive algorithms. One uses loops(while, do while and for): the other uses recursion. Recursion.
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—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Fall 2012 Lecture 8: File I/O; Introduction to classes.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
CPS120: Introduction to Computer Science Functions.
Vectors and Grids Eric Roberts CS 106B April 8, 2009.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
1 Recursion. Objectives To define the concept of recursion as a programming strategy distinct from other forms of algorithmic decomposition. To recognize.
Concepts of Algorithms CSC-244 Unit 5 and 6 Recursion Shahid Iqbal Lone Computer College Qassim University K.S.A.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
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.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Program Development and Design Using C++, Third Edition
Looking Ahead Eric Roberts CS 106A March 7, 2016.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Functions and Libraries. The idea of a function Functions in programming A function is a block of code that has been given a name. To invoke that code.
Mechanics of Functions
User-Written Functions
Topic 6 Recursion.
Chapter 2 - Introduction to C Programming
Methods Chapter 6.
Functions in C++ Eric Roberts CS 106B January 7, 2015.
Chapter 2 - Introduction to C Programming
User-Defined Functions
User-defined Functions
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
1) C program development 2) Selection structure
Chapter 2 - Introduction to C Programming
Capitolo 1 – Introduction C++ Programming
Chapter 2 - Introduction to C Programming
Review Lab assignments Homework #3
Introduction to C Programming
Classes and Objects Systems Programming.
Presentation transcript:

Functions in C++ Eric Roberts CS 106B January 9, 2013

Administrative Essentials All handouts and course information are on the web site: Extra handouts are placed in the “Handout Hangout” in Gates.

Finding the Handout Hangout Gates Computer Science Building (ground floor)

Administrative Essentials All handouts and course information are on the web site: Extra handouts are placed in the “Handout Hangout” in Gates. All CS 106B students must sign up for a section by Sunday at 5:00 P.M. The signup form will appear on the web tomorrow: All undergraduates must take CS 106B for 5 units. The Axess default is 3 units, and we end up signing lots of petitions each year to correct this error. You need to install the appropriate C++ software for the type of computer you intend to use. The instructions for doing so are described in the appropriate version of Handout #7.

The Syntax of a Function Definition The general form of a function definition looks essentially the same as it does in Java: type name ( parameter list ) { statements in the function body } where type indicates what type the method returns, name is the name of the method, and parameter list is a list of variable declarations used to hold the values of each argument. All functions need to be declared before they are called by specifying a prototype consisting of the header line followed by a semicolon.

Computing Factorials The factorial of a number n (which is usually written as n! in mathematics) is defined to be the product of the integers from 1 up to n. Thus, 5! is equal to 120, which is 1 x 2 x 3 x 4 x 5. int fact(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } The following function definition uses a for loop to compute the factorial function:

C++ Enhancements to Functions Functions can be overloaded, which means that you can define several different functions with the same name as long as the correct version can be determined by looking at the number and types of the arguments. The pattern of arguments required for a particular function is called its signature. void setMargin(int margin = 72); Indicates that setMargin takes an optional argument that defaults to 72. Functions can specify optional parameters by including an initializer after the variable name. For example, the function prototype C++ supports call by reference, which allows functions to share data with their callers.

Call by Reference C++ indicates call by reference by adding an ampersand ( & ) before the parameter name. A single function often has both value parameters and reference parameters, as illustrated by the solveQuadratic function from Figure 2-3 on page 76, which has the following prototype: void solveQuadratic(double a, double b, double c, double & x1, double & x2); Call by reference has two primary purposes: −It creates a sharing relationship that makes it possible to pass information in both directions through the parameter list. −It increases efficiency by eliminating the need to copy an argument. This consideration becomes more important when the argument is a large object.

Call by Reference Example The following function swaps the values of two integers: void swap(int & x, int & y) { int tmp = x; x = y; y = tmp; } The arguments to swap must be assignable objects, which for the moment means variables. If you left out the & characters in the parameter declarations, calling this function would have no effect on the calling arguments because the function would exchange local copies.

Libraries and Interfaces Modern programming depends on the use of libraries. When you create a typical application, you write only a tiny fraction of the code. Libraries can be viewed from two perspectives. Code that uses a library is called a client. The code for the library itself is called the implementation. The point at which the client and the implementation meet is called the interface, which serves as both a barrier and a communication channel: interface clientimplementatio n

/* * File: simpio.h * * This interface exports a set of functions that simplify * input/output operations in C++ and provide some error-checking * on console input. */ #ifndef _simpio_h #define _simpio_h The simpio.h Interface

/* * File: simpio.h * * This interface exports a set of functions that simplify * input/output operations in C++ and provide some error-checking * on console input. */ #ifndef _simpio_h #define _simpio_h /* * Function: getInteger * Usage: int n = getInteger(); * int n = getInteger(prompt); * * Reads a complete line from cin and scans it as an integer. * If the scan succeeds, the integer value is returned. If the * argument is not a legal integer or if extraneous characters * (other than whitespace) appear in the string, the user is * given a chance to reenter the value. If supplied, the * optional prompt string is printed before reading the value. */ int getInteger(std::string prompt = ""); The simpio.h Interface

/* * Function: getInteger * Usage: int n = getInteger(); * int n = getInteger(prompt); * * Reads a complete line from cin and scans it as an integer. * If the scan succeeds, the integer value is returned. If the * argument is not a legal integer or if extraneous characters * (other than whitespace) appear in the string, the user is * given a chance to reenter the value. If supplied, the * optional prompt string is printed before reading the value. */ int getInteger(std::string prompt = ""); /* * Function: getReal * Usage: double x = getReal(); * double x = getReal(prompt); * * Reads a complete line from cin and scans it as a floating-point * number. If the scan succeeds, the floating-point value is * returned. If the input is not a legal number or if extraneous * characters (other than whitespace) appear in the string, the * user is given a chance to reenter the value. If supplied, the * optional prompt string is printed before reading the value. */ double getReal(std::string prompt = ""); The simpio.h Interface

/* * Function: getReal * Usage: double x = getReal(); * double x = getReal(prompt); * * Reads a complete line from cin and scans it as a floating-point * number. If the scan succeeds, the floating-point value is * returned. If the input is not a legal number or if extraneous * characters (other than whitespace) appear in the string, the * user is given a chance to reenter the value. If supplied, the * optional prompt string is printed before reading the value. */ double getReal(std::string prompt = ""); /* * Function: getLine * Usage: string line = getLine(); * string line = getLine(prompt); * * Reads a line of text from cin and returns that line as a string. * The newline character that terminates the input is not stored * as part of the return value. If supplied, the optional prompt * string is printed before reading the value. */ std::string getLine(std::string prompt = ""); #endif The simpio.h Interface

Exercise: Finding Perfect Numbers Greek mathematicians took a special interest in numbers that are equal to the sum of their proper divisors (a proper divisor of n is any divisor less than n itself). They called such numbers perfect numbers. For example, 6 is a perfect number because it is the sum of 1, 2, and 3, which are the integers less than 6 that divide evenly into 6. Similarly, 28 is a perfect number because it is the sum of 1, 2, 4, 7, and 14. Our first exercise today is to design and implement a C++ program that finds all the perfect numbers between two limits entered by the user, as follows: FindPerfect Enter lower limit: Enter upper limit:

Recursive Functions The easiest examples of recursion to understand are functions in which the recursion is clear from the definition. As an example, consider the factorial function, which can be defined in either of the following ways: n! = n x (n − 1) x (n − 2) x... x 3 x 2 x 1 n! = n x (n − 1)! 1 if n is 0 otherwise The second definition leads directly to the following code, which is shown in simulated execution on the next slide: int fact(int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); }

Simulating the fact Function skip simulation RecursiveFactorial Enter n: 5 5! = 120 int main() { cout << "Enter n: "; int n = getInteger(); cout << n << "! = " << fact(n) << endl; return 0; } n int fact(int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); } n 5 24 int fact(int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); } n 4 6 int fact(int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); } n 3 2 int fact(int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); } n 2 1 int fact(int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); } n 1 1 int fact(int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); } n 0 int fact(int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); } n 0

The Recursive Paradigm Most recursive methods you encounter in an introductory course have bodies that fit the following general pattern: if ( test for a simple case ) { Compute and return the simple solution without using recursion. } else { Divide the problem into one or more subproblems that have the same form. Solve each of the problems by calling this method recursively. Return the solution from the results of the various subproblems. } Finding a recursive solution is mostly a matter of figuring out how to break it down so that it fits the paradigm. When you do so, you must do two things: Identify simple cases that can be solved without recursion.1. Find a recursive decomposition that breaks each instance of the problem into simpler subproblems of the same type, which you can then solve by applying the method recursively. 2.

Exercise: Greatest Common Divisor int gcd(int x, int y) { int r = x % y; while (r != 0) { x = y; y = r; r = x % y; } return y; } One of the oldest known algorithms that is worthy of the title is Euclid’s algorithm for computing the greatest common divisor (GCD) of two integers, x and y. Euclid’s algorithm is usually implemented iteratively using code that looks like this: Rewrite this method so that it uses recursion instead of iteration, taking advantage of Euclid’s insight that the greatest common divisor of x and y is also the greatest common divisor of y and the remainder of x divided by y.

Solution: A Recursive GCD Function int gcd(int x, int y) { if (x % y == 0) { return y; } else { return gcd(y, x % y); } As is usually the case, the key to solving this problem is finding the recursive decomposition and defining appropriate simple cases. Download: Euclid.cpp

The End