0% found this document useful (0 votes)
22 views33 pages

COM255 - Part 05 - Functions

Uploaded by

Anas Elden
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views33 pages

COM255 - Part 05 - Functions

Uploaded by

Anas Elden
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

COM255

Programming I
Fall 2023

Part 05 – User-Defined Functions


Instructor: Dr. Ahmed Alenany
Credits to: Dr. Tarek Abdul Hamid
Introduction
Complex problems can be broken down into sub
tasks.
Each sub task can be implemented in C++ using a
separate module or function.
Modular programs have significant advantages
over writing the entire solution in main():
Multiple programmers can work in parallel,
reducing the development time of software while
increasing quality.
Functions can be re-used (even in different
programs)
Reduce duplication of code; tend to yield shorter
2
programs and, therefore, enhance program
Modularity
A C++ program contains numerous functions.
Pre-defined
standard libraries
User defined
main() is a programmer defined function.
main() often references or calls functions from
standard libraries or programmer-defined functions.

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

Return a value of a specific data type using the


return statement
Void functions: do not have a return type

Do not use a return statement to return a value

Example: void calc(int n)

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:

In C++, return is a reserved word


When a return statement executes
Function immediately terminates
Control goes back to the caller
When a return statement executes in the function main,
13
the program terminates
Void Functions without Parameters
Formal parameters are optional
Function definition syntax:

void is a reserved word


Function call 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

Global scope - a global variable is defined outside the


main function and any other function and can be
accessed by any function within the program file.

16
Example
 Write a function to return the largest number between 2 numbers

int larger(int x, int y)


{
if(x>y)
return x;
else
return y;
}

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

<< " is: " << L;


}

int larger(int x, int y)


{
if(x>y)
return x;
else
18
return y;
Passing Parameters

There are two methods to pass parameters between


functions:
1) Pass by Value: a formal parameter that receives a copy
of the content of actual parameter
Here, the called function doesn’t change the original
variable.
2) Pass by Reference: a formal parameter that receives the
location (memory address) of the corresponding actual
parameter
Here, the called function can change the original
19
variable.
Why Reference Variables?
Reference parameters are useful in three situations:

Returning more than one value

Changing the actual parameter

When passing the address would save memory space and


time

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

 Reference must be initialized when it is declared


int &y; // Error

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;
}

• The output is: 10 5 (the original variables are


23 swapped)
Programming Example:
Classify Numbers
In this example, we use functions to rewrite the program
that determines the number of odds and evens from a
given list of integers
Main algorithm remains the same:
Initialize variables, zeros, odds, evens to 0
Read a number
If number is even, increment the even count
If number is also zero, increment the zero count; else
increment the odd count
Repeat Steps 2-3 for each number in the list

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

int factorial(int n) //function header


{ int nfactorial = 1;
while (n>1) {
nfactorial = nfactorial * n;
n--;
} //end while block
return nfactorial;
} //end factorial

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

You might also like