Chapter 3
Chapter 3
Intro to Programming
Chapter 3:
Functions
Introduction
Functions
• Functions
– Modularize a program
– Software reusability
• Call function multiple times
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local
variables
• Parameters
– Local variables passed to function when called
– Provide outside information
Function Definitions
• Function prototype
– Tells compiler argument type and return type of function
– int square( int );
• Function takes an int and returns an int
– Explained in more detail later
• Calling/invoking a function
– square(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
Function Definitions
Function Definitions
• Example function
int square( int y )
{
return y * y;
}
• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
• Functions cannot be defined inside other functions
• Next: program examples
2003 Prentice Hall, Inc. All rights reserved.
11
1 // Fig. 3.3: fig03_03.cpp
2 // Creating and using a programmer-defined function.
Outline
3 #include <iostream>
4 Function prototype: specifies fig03_03.cpp
5 using std::cout; data types of arguments and (1 of 2)
6 using std::endl; return values. square
7
expects and int, and returns
8 int square( int ); // function prototype
an int.
9
10 int main()
11 { Parentheses () cause function
12 // loop 10 times and calculate and output
to be called. When done, it
13 // square of x each time
returns the result.
14 for ( int x = 1; x <= 10; x++ )
15 cout << square( x ) << " "; // function call
16
17 cout << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main
22
Function Prototypes
Function Prototypes
• Function signature
– Part of prototype with name and parameters
• double maximum( double, double, double );
Function signature
• Argument Coercion
– Force arguments to be of proper type
• Converting int (4) to double (4.0)
cout << sqrt(4)
– Conversion rules
• Arguments usually converted automatically
• Changing from double to int can truncate data
– 3.4 to 3
– Mixed type goes to highest type (promotion)
• int * double
Function Prototypes
Da ta typ e s
long double
double
float
unsigned long int (synonymous with unsigned long)
long int (synonymous with long)
unsigned int (synonymous with unsigned)
int
unsigned short int (synonymous with unsigned short)
short int (synonymous with short)
unsigned char
char
bool (false becomes 0, true becomes 1)
Fig . 3.5 Pro m o tio n h ie ra rc h y fo r b u ilt-in d a ta typ e s.
Header Files
Storage Classes
Storage Classes
Storage Classes
• Static storage class
– Variables exist for entire program
• For functions, name exists for entire program
– May not be accessible, scope rules still apply (more later)
• static keyword
– Local variables in function
– Initialized to zero
– Keeps value between function calls
– Only known in own function
Scope Rules
• Scope
– Portion of program where identifier can be used
• File scope
– Defined outside a function, known in all functions
– Global variables, function definitions and prototypes
• Function scope
– Can only be referenced inside defining function
Scope Rules
• Block scope
– Begins at declaration, ends at right brace }
• Can only be referenced in this range
– Local variables, function parameters
• Function-prototype scope
– Parameter list of prototype
– Names in prototype optional
• Compiler ignores
– In a single prototype, name can be used once
int i = 8;
fig03_12.cpp
int square(int i);
(1 of 5)
int main()
{
cout << "Value of i is: " << i << endl;
{
int i = 6;
cout << "Value of i is: " << i << endl;
}
int i = 7;
cout << "Value of i is: " << i << endl;
i = square(i);
cout << "Value of i is: " << i << endl;
return 0;
}
local x in main is 5
• Call by value
– Copy of data passed to function
– Changes to copy do not change original
– Prevent unwanted side effects
• Call by reference
– Function can directly access data
– Changes affect original
• Reference parameter
– Alias for argument in function call
• Passes parameter by reference
– Use & after data type in prototype
• void myFunction( int &data )
• Read “data is a reference to an int”
– Function call format the same
• However, original can now be changed
fig03_20.cpp
z = 4 before squareByReference
output (1 of 1)
z = 16 after squareByReference
• Pointers (chapter 5)
– Another way to pass-by-refernce
• References as aliases to other variables
– Refer to same variable
– Can be used within a function
int count = 1; // declare integer variable count
Int &cRef = count; // create cRef as an alias for count
++cRef; // increment count (using its alias)
x = 3
y = 3
x = 7
y = 7
Default Arguments
Function Overloading
• Function overloading
– Functions with same name and different parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
Recursion
• Recursive functions
– Functions that call themselves
– Can only solve a base case
• If not base case
– Break problem into smaller problem(s)
– Launch new copy of function to work on the smaller
problem (recursive call/recursive step)
• Slowly converges towards base case
• Function makes call to itself inside the return statement
– Eventually base case gets solved
• Answer works way back up, solves entire problem
Recursion
• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
– Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
– Base case (1! = 0! = 1)
fig03_14.cpp
int main()
(1 of 2)
{
int x,y;
cin >> x;
y = factorial(x);
cout << "factorial " << x << " is " << y << endl;
return 0;
}
f( 3 )
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
• Order of operations
– return fibonacci( n - 1 ) + fibonacci( n - 2 );
Enter an integer: 0
Fibonacci(0) = 0
Enter an integer: 1
Fibonacci(1) = 1
Enter an integer: 2
Fibonacci(2) = 1
Enter an integer: 3
Fibonacci(3) = 2
Enter an integer: 5
fig03_15.cpp
Fibonacci(5) = 5
output (2 of 2)
Enter an integer: 6
Fibonacci(6) = 8
Enter an integer: 10
Fibonacci(10) = 55
Enter an integer: 20
Fibonacci(20) = 6765
Enter an integer: 30
Fibonacci(30) = 832040
Enter an integer: 35
Fibonacci(35) = 9227465
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance between performance (iteration) and good
software engineering (recursion)
• Assignment:
– Rewrite the fibonacci series program without using recursion
(using iterations):