COM255 - Part 05 - Functions
COM255 - Part 05 - Functions
Programming I
Fall 2023
3
Functions in Mathematics
In algebra, a function is defined as a rule or
correspondence between values, called the function’s
arguments, and the unique value of the function
associated with the arguments
If f(x) = 2x + 5, then
f(1) = 7, f(2) = 9, and f(3) = 11
1, 2, and 3 are arguments
7, 9, and 11 are the corresponding values
4
Predefined Functions
Some of the predefined mathematical functions are:
sqrt(x)
pow(x,y)
floor(x)
Predefined functions are organized into separate libraries
I/O functions are in iostream header
Math functions are in cmath header
5
Predefined Functions Examples
pow(x,y) calculates xy
pow(2, 3) = 8.0
Returns a value of type double
x and y are the parameters (or arguments)
sqrt(x) calculates the nonnegative square root of x, for x
>= 0.0
sqrt(2.25) is 1.5
Type double
The floor function floor(x) calculates largest whole
number not greater than x
floor(48.79) is 48.0
Type double
6
Example
Sample run:
7
User-defined Functions
Now, let us see how to build our own functions.
First, consider the following program which sums the
numbers from 1 to n, where n is an integer provided by the
user.
#include <iostream>
using namespace std;
int main()
{
int n;
int sum = 0;
cout << “Please, enter an integer: ”;
cin >> n;
for (int i = 1; i <= n; i++)
sum = sum + i;
cout << “Sum of integers from 1 to ” << n << “ is: ” <<
sum;
8 return 0;
}
Implementation using function
Now, let us see how to rewrite the program using a user
defined function whose role will be to read and find the sum
of integers.
#include <iostream>
using namespace std;
int calc(int); // Function Prototype
int main()
{
int n;
int s;
cout << “Please, enter an integer: ”;
cin >> n;
s = calc(n); // Function Call
cout << “The sum of integers from 1 to ” << n << “ is: ” << s;
return 0;
}
int calc(int a) // Function Definition
{
int sum = 0;
for (int i = 1; i <= a; i++)
sum = sum + i;
return sum;
}
9
User-Defined Functions
The prototype
int calc(int)
Function call
s = calc(n)
n is called argument
s is used to store the return value
Function definition
int calc(int a) // a is parameter
{
int sum = 0;
for (int i = 1; i <= a; i++)
sum = sum + i;
return sum;
10 }
Function Prototype
In C++, identifiers must be defined before they may be
invoked or referenced.
Since the main function is the entry point for the application,
we like to have it appear near the beginning of the program.
But for it to be able to call functions, defining all the
functions it calls first is a problem.
A function prototype provides sufficient information for the
compiler to process references to the function.
The definition may then be provided later in the code.
Function prototype: function heading without the body of the
function
Example: int calc(int);
It is not necessary to specify the variable name in the parameter
list
11 The data type of each parameter must be specified
User-Defined Functions
Value-returning functions: have a return type
12
Syntax: return Statement
Once a value-returning function computes the value, the
function returns this value via the return statement
It passes this value outside the function via the return
statement
The return statement has the following syntax:
14
Flow of Execution
Execution always begins at the first statement in the function
main
Other functions are executed only when they are called
Function prototypes appear before any function definition
The compiler translates these first
The compiler can then correctly translate a function call
A function call results in transfer of control to the first
statement in the body of the called function
After the last statement of a function is executed, control is
passed back to the point immediately following the function
call
A value-returning function returns a value
15
After executing the function, the returned value replaces the
Scope of a variable
Scope refers to the portion of the program in which it
is valid to reference a function or a variable
Local scope - a local variable is defined within a
function or a block and can be accessed only within the
function or block that defines it
16
Example
Write a function to return the largest number between 2 numbers
17
Example, continued
The complete program
#include <iostream>
using namespace std;
int larger(int, int);
int main()
{
int A, B, L;
cout << "\nPlease enter two integers: ";
cin >> A >> B ;
L = larger(A, B);
cout << "\n The largest value among " << A << " and " << B
20
Example: Pass by Value
• Pointers may be passed to a function in the
same way as other types of variables.
#include <iostream.h>
void swap(int, int); void swap(int a, int b)
int main () {
{ int temp;
int v = 5, x = 10; temp = a;
cout << v << x << endl; a = b;
b = temp;
swap(v,x);
cout << v << x << endl; }
}
• The output is: 5 10 (the original variables are
21 not swapped)
Reference Variables
Reference variable is an alias for another variable.
int x = 5;
int &z = x; // z is another name for x
cout << x << endl; // prints 5
cout << z << endl; // prints 5
22
Example: Pass by Reference
#include <iostream.h>
// Function prototypes
void rswap(int &a, int &b)
void rswap(int&, int&);
{
int temp;
int main (void){ temp = a; (2)
int v = 5, x = 10; a = b; (3)
cout << v << x << endl; b = temp;
rswap(v,x); }
cout << v << x << endl;
}
24
Programming Example:
Classify Numbers
The program functions include:
initialize: initialize the variables, such as zeros, odds,
and evens
getNumber: get the number
classifyNumber: determine if number is odd or even
(and whether it is also zero); this function also increments
the appropriate count
printResults: print the results
25
26
Programming Example:
Main Algorithm
Call initialize to initialize variables
Prompt the user to enter 20 numbers
For each number in the list
Call getNumber to read a number
Output the number
Call classifyNumber to classify the number and
increment the appropriate count
Call printResults to print the final results
27
28
Example - Factorial
//function definition: n! = n*(n-1)*(n-2)*…*1
// 0! is 1 by definition
//Function factorial returns n!
//Function factorial assumes n is non-negative int
29
Example –
Calling Factorial Function
int factorial(int); //function prototype
int main() {
int m;
cin >> n;
if (m>=0)
cout << m << "! is “ << factorial(m) << endl;
//m is the argument of the
//factorial function call
else
cout <<“Not defined for negative numbers” << endl;
return 0;
} //end main
30
Recursive Functions
Recursion is a powerful tool for solving certain problems
where the problem solution can be expressed in terms of the
solution to a similar, yet smaller problem.
Programming languages that support recursion allow functions
to call themselves.
A recursive function requires two blocks:
a recursive block that reduces the problem solution to a
similar but smaller version of the problem.
a block that defines a terminating condition, or return point,
where a unique solution to a smaller version of the problem
is returned.
31
Example: Recursive Function
1 n 0,
f (n) n!
n * f (n 1) n 1
f(0) = f(1) = 1 Unique solution(s) or base case.
f(n) = n*f(n-1) recursive definition.
Thus f(n) can be determined for all integer values of n >=
0;
32
Recursive Factorial Function
long factorial(int n) {
//termination condition
if (n < 2)
return 1; // base case
return n*factorial(n-1); // recurse
}
33