You are on page 1of 97

CS 31:

Introduction to Computer Science I


Topic 3

Functions
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-1

Functions

Function Definition
A function is a single unit of computation Other words for function
Procedure Method Subprogram (that returns a value)
9/2010 John A. Rohr All Rights Reserved

CS 31: Introduction To CS I Topic 3: Functions

JAR 3-2

Functions

Function Characterization
Accomplishes one thing May use other functions May produce a result Sequence of statements

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-3

Functions

Function Inputs
Called arguments or actual parameters Provides values for calculation Not needed by all functions
Display text Generate random number

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-4

Functions

Function Outputs
Called the return value Reports the results of the processing Not produced by all functions
Functions that perform an action only

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-5

Functions

Function Processing
Apply defined algorithm Use inputs Generate outputs

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-6

Functions

Function Example
Square Root Input: Value: Processing: Calculate square root Output: Square root of value:

9 3

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-7

Functions

Two Function Dichotomies


Function definition dichotomy
Predefined functions Programmer-written functions

Function return value dichotomy


void Typed (int, float, double, char, bool, etc.)
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-8

Functions

Function Definition Types


Predefined functions
Function library Commercial product Other programmers

Programmer defined functions


Written by programmer
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-9

Functions

Function Return Value Types


Functions that return a value (typed)
Perform a calculation (e.g. Square root) Deliver (return) the result

Functions that do not return a value (void)


Perform an action (e.g. set an output format) Do not have a result to return
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-10

Functions

C++ Predefined Functions


Provided by the compiler Organized in libraries Referenced by #include statements Included in program using #include

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-11

Functions

Some Predefined Libraries


iostream cmath cstdlib cctype string
CS 31: Introduction To CS I Topic 3: Functions

Stream input and output Mathematical functions Some standard functions Character operations String capabilities
9/2010 John A. Rohr All Rights Reserved JAR 3-12

Functions

Some Predefined Functions


Library iostream (#include <iostream>)
cin cout precision width setf
CS 31: Introduction To CS I Topic 3: Functions

Stream input Stream output Stream precision Stream width Stream formatting
9/2010 John A. Rohr All Rights Reserved JAR 3-13

Functions

Some Predefined Functions


Library cmath (#include <cmath>)
double sqrt(double) double exp(double) double sin(double) double log(double) double floor(double)
CS 31: Introduction To CS I Topic 3: Functions

Square root Exponential (ex) Trigonometric sine Natural logarithm (ln) Floor
JAR 3-14

9/2010 John A. Rohr All Rights Reserved

Functions

Some Predefined Functions


Library cstdlib (#include <cstdlib>)
int abs(int) Absolute value int rand() Random number void srand(unsigned int) Seed random number void exit(int) Exit program

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-15

Functions

Some Predefined Functions


Library cctype (#include <cctype>)
bool isdigit(char) bool isupper(char) bool isspace (char) bool ispunct(char) int toupper(char)
CS 31: Introduction To CS I Topic 3: Functions

Digit Upper case White space Punctuation To upper case


JAR 3-16

9/2010 John A. Rohr All Rights Reserved

Functions

Some Predefined Functions


Library string (#include <string>)
String declaration (with/without initialization) String assignment String input and output String character selection Substring
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-17

Functions

Function Call
Invokes the use of a function Specifies input arguments Return result value, if any
void function: Typed function: No return value Return value
Exactly one value Value is function type
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-18

Functions

Function Call Syntax


name(arg1, arg2, arg3, . . . argn); variable = name(arg1, arg2, arg3, . . . argn); name: Function name argi: Argument i variable: Place to put function value (if any)
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-19

Functions

Function Calls
void function: No value is returned typed function: One value is returned
Cannot be no value Cannot be more than one value Must be exactly one value

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-20

Functions

Type Conversion
Input arguments: For literals only
Will be converted if necessary and possible

Return values
Always returned as function type May be converted by an assignment statement after return
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-21

Functions

Function Example
root = sqrt(value);
Function name: Library location: Function action: Argument: Output:
CS 31: Introduction To CS I Topic 3: Functions

sqrt cmath Square root value (e.g. 25) Square root of value (e.g.5)
9/2010 John A. Rohr All Rights Reserved JAR 3-22

Functions

Literal Argument
root = sqrt(64);
Argument is an integer Parameter is a double Automatic upconversion of literal value from integer to double

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-23

Functions

Variable Argument
double value = 64; root = sqrt(value);
Argument is a double Argument must match type No conversion

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-24

Functions

Function Use
#include <cmath> #include <iostream> using namespace std; int main() { double value; double root;
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-25

Functions

Function Use
cout << "Enter a value:"; cin >> value; root = sqrt(value); cout << "The square root of \"" << value << "\" is \"" << root << "\"" << endl; return 0; }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-26

Functions

Function Execution
Enter a value:5.76 The square root of "5.76" is "2.4"

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-27

Functions

Exit Function
exit(integer);
Useful for stopping program early on error Takes integer value for identification
0 for special exit without error 1 or other for error exit

In library cstdlib
9/2010 John A. Rohr All Rights Reserved

CS 31: Introduction To CS I Topic 3: Functions

JAR 3-28

Functions

Exit Use
#include <cstdlib> using namespace std; int main() { exit(0); }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-29

Functions

Time Function
now = time(0);
Returns current time Seconds since January 1, 1970 Useful to obtain a random number In library ctime

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-30

Functions

Time Use
#include <ctime> #include <iostream> using namespace std; int main() { cout << "Time:" << time(0) << endl; return 0; }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-31

Functions

Random Number Generation


Sequence of pseudorandom numbers
Not completely random Generated by algorithm

Initialized by an integer seed number Will repeat same sequence for same seed Use random seed for random sequence
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-32

Functions

Random Number Function


rand();
Does not take any argument Generates a pseudorandom number
Value is between 0 and RAND_MAX (>=32,767) Can be scaled for other ranges

Function and RAND_MAX in library cstdlib


9/2010 John A. Rohr All Rights Reserved

CS 31: Introduction To CS I Topic 3: Functions

JAR 3-33

Functions

Random Number Use


#include <cstdlib> #include <iostream> using namespace std; int main() { cout << "Random #:" << rand() << endl; return 0; }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-34

Functions

Random Number Scaling


rand() value is between 0 and RAND_MAX Value can be scaled to any range Select number of values using modulus Shift range by addition Scale by multiplication
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-35

Functions

Scaling Example
Find result of throwing two dice Minimum value is 2 Maximum value is 12 count = (rand() % 11) + 2;

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-36

Functions

Another Scaling Example


Find a probability Minimum value is 0 Maximum value is 1.0 count = (RAND_MAX - rand()) / (RAND_MAX * 1.0);
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-37

Functions

Seeded Random Numbers


srand(seed); Initializes random number generator Used unsigned integer for seed Generate same sequence for same seed Generate different numbers with different seed
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-38

Functions

Seeded Random Numbers


#include <ctime> #include <cstdlib> #include <iostream> using namespace std; int main()
{

srand(time(0)); cout << "Random #:" << rand() << endl; return 0;
}
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-39

C++ Strings

string Library
#include <string> Provides C++ strings Not part of language itself Cannot be used without #include <string> One of many extensions to the language
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-40

C++ Strings

C++ String Declaration


string st1; string st2 = "Initial string"; String is initialized to empty string by default String can be initialized with declaration Characters are numbered beginning with 0
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved

JAR 3-41

C++ Strings

C++ String Length


string st = "Example text"; st.length() or st.size() (Integer 12) Length of the string Function with no parameters Return value is integer Syntax uses string name followed by period
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-42

C++ Strings

C++ String Access


string st = "Example text"; st[3] (Character m) One character of the string Position can be any integer expression Must not access past last character Syntax uses position in square brackets
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-43

C++ Strings

Alternate C++ String Access


string st = "Example text"; st[3] (Character m) st.at(3) (Character m) Both access one character at checks for beyond end of string at throws an exception on error
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-44

C++ Strings

C++ Substring
string st = "Example text"; st.substr(8) (String "text") Part of the string Position can be any integer expression Must not begin past last character Result is string from position specified
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-45

C++ Strings

C++ Substring
string st = "Example text"; st.substr(2, 5) (String "ample") Part of the string Start can be any integer expression Length can be any integer expression Must not extend past last character Result string from position with length given
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-46

C++ Strings

C++ String Comparison


Strings can be compared like numbers Operators are ==, !=, >, <, >=, and <= Comparison is based on character values Character values are defined by hardware

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-47

C++ Strings

C++ String Comparison


Comparisons are character by character First differing character determines result Comparisons also depend on length Longer string is greater than shorter string if identical up to the end of the shorter

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-48

C++ Strings

C++ String Comparison


string st1 = "On"; string st2 = "Once"; string st3 = "Once more"; st1 == st2 is false st1 == st2.substr(0,2) is true st2 != st3 is true
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-49

C++ Strings

C++ String Comparison


string st1 = "On"; string st2 = "Once"; string st3 = "Once more"; st2 < st3 is true st2 >= st3.substr(0,4) is true st1 > st3 is false
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-50

C++ Strings

C++ String Concatenation


string st1 = "One string"; string st2 = " extended"; st1 + st2 ("One string extended") First string followed by second No characters inserted between Plus sign (+) defined by #include <string>
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-51

C++ Strings

C++ String Insertion


string st1 = "One string"; string st2 = " more"; string st3, st4; st3 = st1.insert(3, st2); ("One more string") st4 = st1.insert(3, st2, 1, 2 ) ("Onemo string")
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-52

C++ Strings

C++ String Removal


string st1 = "One string"; string st2 = "op"; string st3, st4, st5; st2 = st1.erase(3); ("One") st3 = st1.erase(0, 6); ("ring")
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-53

C++ Strings

C++ String Replacement


string st1 = "One string"; string st2 = "person"; string st3 = "weather"; string st4, st5; st4 = st1.replace(4, 6, st2); ("One person") st5 = st1.replace(0, 7, st3, 3, 2); ("thing")
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-54

C++ Strings

C++ String Find


string st = "One string"; st.find("in", 0) is 7 st.find("in", 5) is 7 st.find(' ', 0) is 3 st.find(' ', 5) is string::npos Returns string::npos if no find (Constant defined in the string library)
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-55

C++ Strings

Digit Value
Characters are represented by integers The code is defined by the hardware Several code standards are used Each character has a different code

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-56

C++ Strings

ASCII Digit Value


ASCII: American Standard Code for Information Interchange Most common character code Uses first 32 values for control characters e.g. Tab, Backspace, Return Digits begin at 48, NOT 0
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-57

C++ Strings

ASCII Digit Value


Digit values range from 48 to 57 Never need to use numeric values '0' = 48 '5' = 53 '1' = 49 '6' = 54 '2' = 50 '7' = 55 '3' = 51 '8' = 56 '4' = 52 '9' = 57
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-58

C++ Strings

ASCII Digit Value


Subtract digit 0 value from digit character char digit = '3'; int number; number = digit - '0'; Numerical value of digit is 51 Numerical value of number is 3
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-59

Functions

Programmer-Defined Functions
Custom functions for specific uses Can be used to provide needed capability Can be used to modularize programs
Limit size of each module Organize in hierarchy of modules

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-60

Functions

Programmer-Defined Functions
Three required items
Function prototype (declaration) Function definition (code) Function call (use)

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-61

Functions

Function Return Value


None if void Any valid type if typed
int float double bool char string
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-62

Functions

Function Name
Valid C++ identifier Uniquely identifies function Should indicate the action of the function Used to call the function

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-63

Functions

Function Parameters
Called parameters or formal parameters Are placeholders for arguments of calls Specify the type & number of parameters Specify the name of each parameter
Name not required in prototype Should be included for completeness Are required in the function header
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-64

Functions

Prototype Example
void aFunction(int p1, float p2, char p3);
Return type (None) Name (aFunction) Parameters
p1 p2 p3 (Integer) (Float) (Character)

Note required semicolon at end!


CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-65

Functions

Prototype Example
int anotherFunction(double value);
Return type (Integer) Name (anotherFunction) Parameter
value (Double)

Note required semicolon at end!


CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-66

Functions

Function Call
Same as for predefined functions
Function name Arguments
Must match the number of prototype parameters Must match the types prototype parameters Must be in the correct order Exception: Automatic upconversion
9/2010 John A. Rohr All Rights Reserved JAR 3-67

CS 31: Introduction To CS I Topic 3: Functions

Functions

Function Call Examples


aFunction (3, 80.24, 'J'); int x; x = anotherFunction(816.42);

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-68

Functions

Function Definition
Not required for predefined functions
Provided by #include statement

Consists of two separate parts


Function header Function body

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-69

Functions

Function Header
Same format as prototype
Specifies type, name, and parameters Does not have terminating semicolon Must have names for parameters

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-70

Functions

Function Body
Defines the action of the function Can include declarations Must include statements No return statement if void Must return value if not void
Value must match type of function Value is returned with a return statement
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-71

Functions

Function Definition Example


#include <iostream> using namespace std; void aFunction(int p1, float p2, char p3) { cout << "Integer: " << p1 << endl; cout << "Float: " << p2 << endl; cout << "Character:" << p3 << endl; }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-72

Functions

Function Definition Example


int anotherFunction(double value)
{

int result; if (value >= 0) result = 0; else result = 1; return result;


}
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-73

Functions

Function Return
Void functions
Return statement is optional If used, return cannot return any value Will return at final close brace if no return

Typed functions
Return statement is required Must return value of function type
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-74

Functions

Functions Calling Functions


Statements in function definitions can be any valid C++ statements A function call from within a function is valid Every C++ program is a function (main) Therefore all C++ function calls are actually inside other functions
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-75

Functions

Preconditions
Specify conditions which must be true when a function is called Guarantee correct results if all true Result not guaranteed if not all true Provide limits for arguments Use assert() to check (in cassert library)
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-76

Functions

Postconditions
Describes the value returned by a function Valid only if all preconditions are true

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-77

Functions

Pre/postcondition Example
For square root function Precondition
Argument is a real number >= 0

Postcondition
Result will be the square root of the argument

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-78

Functions

Pre/postcondition Example
For sin function (in cmath) Precondition
Argument is a real number in radians

Postcondition
Result will be the sine of the angle Result will be be in the range -1.0 to +1.0
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-79

Functions

Scope Rules
Define the valid range of a variable Minimize variable name conflicts Provide for global variables Provide for local variables

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-80

Functions

Local Variables
Define within a function Exist between opening and closing braces Do not exist outside the function except Static variables are preserved call to call Cannot conflict with local variables in other functions, even if the name is the same
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-81

Functions

Global Variables
Exist for an entire program Defined before the first function Good use is for global constants Use of global variables should be limited
Use function parameters to pass data Use function returns to return data
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-82

Functions

Blocks
Define scopes for variables Delimited by open and close brace Variables defined in block are local to the block in which they are defined Block may be an entire function

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-83

Functions

Nested Blocks
Blocks defined inside other blocks Resolves variables names Based on static structure Variable name redefined
New instance valid within new block Old instance revived when the new block ends
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-84

Functions

Nested Block Example


{

int var = 5;
{

float var = 2.4; cout << "Inner var:" << var << endl; (2.4)
}

cout << "Outer var:" << var << endl;


}
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved

(5)
JAR 3-85

Functions

For Loop Variables


for (int index = 0; index < 10; index++) Variable can be declared in for statement Better practice to declare at beginning Defined in scope of for statement only Some older compilers may not follow rule
May allow variable to exist after loop ends
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-86

Mathematical Induction

Concept
Mathematical induction is a method that can be used to prove numerical formulas. A proof requires two parts:
Show the formula is true for an initial value; Show that if the formula is true for some value, then it is also true for the next value.
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-87

Mathematical Induction

Example
The formula for the sum of the positive integers from 1 to n is as follows:

i=1

S i = n * (n + 1) / 2

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-88

Mathematical Induction

Proof
Step 1: Show that the sum of the integers 1 from 1 to 1 is 1: iS i = 1. =1

Proof:

i=1

S i = 1 * (1 + 1) / 2
= 1*2/2 = 1 which is true.

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-89

Mathematical Induction

Proof
Step 2: Proof:
Show that if the sum of the integers from 1 to m is m * (m + 1) / 2 then the sum of the integers from m to m+1 is (m + 1) * (m + 2) / 2.
m+1

i=1

Si=

1 * (1 + 1) / 2
m

= S i + (m + 1) i=1 = m * (m + 1) / 2 + (m + 1) = (m2 + m) / 2 + 2m / 2 + 2 / 2 = (m2 + 3m + 2)/2 = (m+1)*(m+2)


9/2010 John A. Rohr All Rights Reserved JAR 3-90

CS 31: Introduction To CS I Topic 3: Functions

Recursion

Concept
Recursion is a method where an algorithm is defined in terms of itself. There must be two cases in the algorithm:
A base case that does not use the algorithm; A recursive case that uses the algorithm.

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-91

Recursion

Example
The formula for the product of the positive integers from 1 to n is as follows:
i=1

pi = 1
n

for n = 0;
n-1 i=1

= n *

p for n > 0
JAR 3-92

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

Recursion

Recursive Factorial Function


double factor(double num) { if (num == 0) return 1; else return factor (n 1); }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-93

Recursion

Recursion vs.Iteration
Recursion
Function calls itself Must have base case Must be supported by the language used

Iteration
Function does not call itself Computation is based on a loop Does not require any special language support
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-94

Recursion

Recursion vs.Iteration
Recursion
More elegant Less efficient Not practical for production use

Iteration
More common More efficient Usually used instead of recursion
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-95

Recursion

Iterative Factorial Function


double factor(double num) { double fact; for (fact = 1.0; num > 0.0; num -= 1.0) fact *= num; return fact; }
CS 31: Introduction To CS I Topic 3: Functions 9/2010 John A. Rohr All Rights Reserved JAR 3-96

UPDATES
More Examples

CS 31: Introduction To CS I Topic 3: Functions

9/2010 John A. Rohr All Rights Reserved

JAR 3-97

You might also like