You are on page 1of 17

The Islamic University of Gaza

Engineering Faculty

Department of Computer Engineering

Fall 2021

ECOM 2003

Eng. Baraa Alastal

Computer Programming: C++


Lab#7: Functions

Contents
❖ Introduction
❖ Defining a function
❖ Passing Arguments to Function
❖ Overloading functions
❖ Passing Arguments by Reference and by Value
❖ Local, Global, and Static Local Variables

Introduction
Functions can be used to define reusable code and organize and simplify code. And
it refers to a segment that group's code to perform a specific task.
Suppose that you need to find the sum of integers from 1 to 10, from 20 to 37, and
from 35 to 49, respectively. You may write the code as follows:
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
cout << "Sum from 1 to 10 is " << sum << endl;

sum = 0;
for (int i = 20; i <= 37; i++)
sum += i;
cout << "Sum from 20 to 37 is " << sum << endl;

sum = 0;
for (int i = 35; i <= 49; i++)
sum += i;
cout << "Sum from 35 to 49 is " << sum << endl;

2
Lab#7: Functions

You may have observed that computing these sums from 1 to 10, from 20 to 37, and
from 35 to 49 are very similar except that the starting and ending integers are
different. Wouldn’t it be nice if we could write the common code once and reuse it?
We can do so by defining a function and invoking it

Depending on whether a function is predefined or created by programmer; there


are two types of function:
1. Library Function
2. User-defined Function

• Library Function
Library functions are the built-in function in C++ programming.

3
Lab#7: Functions

Programmer can use library function by invoking function directly; they don't need
to write it themselves

In the above example, sqrt() library function is invoked to calculate the square
root of a number.
Notice code #include <cmath> in the above program. Here, cmath is a header file.
The function definition of sqrt()(body of that function) is present in the cmath
header file.
Some functions in cmath :
pow: Raise to power (function )
sqrt: Compute square root (function )
cbrt: Compute cubic root (function )
ceil: Round up value (function )
floor: Round down value (function )
exp: Compute exponential function (function )
abs: Compute absolute value (function )

4
Lab#7: Functions

• User-defined Function
C++ allows programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of
code is given a name(identifier).
When the function is invoked from any part of program, it all executes the codes
defined in the body of function.

Defining a function
A function definition consists of its function name, parameters, return value type,
and body.

❖ Syntax
The most common syntax to define a function is:
type name ( parameter1, parameter2, ...) { statements }
Where:
- type: is the type of the value returned by the function.
- name: is the identifier by which the function can be called.
- parameters: (as many as needed): Each parameter consists of a type followed
by an identifier, with each parameter being separated from the next by a
comma.
- statements are the function's body. It is a block of statements surrounded by
braces {} that specify what the function actually does.

Function Calling
Int x =add(num1,num2)

5
Lab#7: Functions

A function may return a value. The returnValueType is the data type of that value.
Some functions perform desired operations without returning a value. In this case,
the returnValueType is the keyword void.

❖ Calling a Function
How user-defined function works in C++ Programming?

When a program begins running, the system calls the main() function, that is, the
system starts executing codes from main() function.
When control of the program reaches to function_name() inside main(), it moves
to void function_name() and all codes inside void function_name() is executed.
Then, control of the program moves back to the main function where the code
after the call to the function_name() is executed as shown in the above figure.

Passing Arguments to Function

In programming, argument (parameter) refers to the data which is passed to a


function (function definition) while calling it.
In the above example, two variables, num1 and num2 are passed to function
during function call. These arguments are known as actual arguments.
The value of num1 and num2 are initialized to variables a and b respectively.
These arguments a and b are called formal arguments.

This is demonstrated in figure below:

6
Lab#7: Functions

❖ Notes on passing arguments


1. The numbers of actual arguments and formals argument should be the same.
(Exception: Function Overloading)
2. The type of first actual argument should match the type of first formal argument.
Similarly, type of second actual argument should match the type of second formal
argument and so on.
3. You may call function a without passing any argument. The number(s) of
argument passed to a function depends on how programmer want to solve the
problem.
4. You may assign default values to the argument. These arguments are known as
default arguments.
5. In the above program, both arguments are of int type. But it's not necessary to
have both arguments of same type.

❖ Return Statement
A function can return a single value to the calling program using return statement.
In the above program, the value of add is returned from user-defined function to
the calling program using statement below:
return add;
The figure below demonstrates the working of return statement.

7
Lab#7: Functions

In the above program, the value of add inside user-defined function is returned to
the calling function. The value is then stored to a variable sum.
Notice that the variable returned, i.e., add is of type int and sum is also of int type.

Also, notice that the return type of a function is defined in function declarator int
add (int a, int b). The int before add (int a, int b) means the function should return
a value of type int.
If no value is returned to the calling function, then, void should be used.
For better understanding of arguments and return in functions, user-defined
functions can be categorized as:

▪ Function with no argument and no return value


▪ Function with no argument but return value
▪ Function with argument but no return value
▪ Function with argument and return value

❖ Example's
▪ Example 1: No arguments passed and no return value

8
Lab#7: Functions

In the above program, prime() is called from the main() with no arguments.
prime() takes the positive number from the user and checks whether the number is
a prime number or not.
Since, return type of prime() is void, no value is returned from the function.

▪ Example 2: No arguments passed but a return value

9
Lab#7: Functions

In the above program, prime() function is called from the main() with no arguments.
prime() takes a positive integer from the user. Since, return type of the function is
an int, it returns the inputted number from the user back to the calling main()
function.
Then, whether the number is prime or not is checked in the main() itself and printed
onto the screen.

▪ Example 3: Arguments passed but no return value

10
Lab#7: Functions

In the above program, positive number is first asked from the user which is stored in
the variable n.
Then, n is passed to the prime() function where, whether the number is prime or
not is checked and printed.
Since, the return type of prime() is a void, no value is returned from the function.

▪ Example 4: Arguments passed and a return value

11
Lab#7: Functions

In the above program, a positive integer is asked from the user and stored in the
variable num. Then, num is passed to the function prime() where, whether the
number is prime or not is checked.
Since, the return type of prime() is an int, 1 or 0 is returned to the main() calling
function. If the number is a prime number, 1 is returned. If not, 0 is returned.
Back in the main() function, the returned 1 or 0 is stored in the variable flag, and the
corresponding text is printed onto the screen.
Which method is better?
All four programs above give the same output and all are technically correct
program.
There is no hard and fast rule on which method should be chosen.

12
Lab#7: Functions

The particular method is chosen depending upon the situation and how you want to
solve a problem.

Overloading Functions
Two or more functions having same name but different argument(s) are known as
overloaded functions.

Here, all 4 functions are overloaded functions because argument(s) passed to these
functions are different.
Notice that, the return type of all these 4 functions are not same. Overloaded
functions may or may not have different return type but it should have different
argument(s).
// Error code
int test (int a) { }
double test(int b){ }
The number and type of arguments passed to these two functions are same even
though the return type is different. Hence, the compiler will throw error.
▪ Example 5: Overloading Function

13
Lab#7: Functions

Passing Arguments by Reference and by Value


By default, the arguments are passed by value to parameters when invoking a
function.
Parameters can be passed by reference, which makes the formal parameter an alias
of the actual argument. Thus, changes made to the parameters inside the function
also made to the arguments.
The difference between pass-by-reference and pass-by-value is that modifications
made to arguments passed in by reference in the called function have effect in the
calling function, whereas modifications made to arguments passed in by value in the
called function cannot affect the calling function.
Use pass-by-reference if you want to modify the argument value in the calling
function. Otherwise, use pass-by-value to pass arguments.

14
Lab#7: Functions

Local, Global, and Static Local Variables

A variable defined inside a function is referred to as


a local variable. C++ also allows you to use global variables. They are declared
outside all functions and are accessible to all functions in their scope.
For example:

15
Lab#7: Functions

❖ Static Local Variables


After a function completes its execution, all its local variables are destroyed.
Sometimes it is desirable to retain the values stored in local variables so that they
can be used in the next call. C++ allows you to declare static local
variables. Static local variables are permanently allocated in the memory for the
lifetime of the program.
For example:

16
Lab#7: Functions

❖ Lab work:

1- Write a function that computes the average of the digits in an integer.


Use the following function header:
double averageDigits(long n)
(Hint: Use the % operator to extract digits, and the / operator to
remove the extracted digit).
Write a test program that prompts the user to enter an integer and
displays the sum of all its digits.

❖ Home work:

1- Implement the following integer function:


a) Function Celsius return the Celsius equivalent of a Fahrenheit temperature.
b) Function Fahrenheit return the Fahrenheit equivalent of a Celsius temperature.
c) Use these functions to write a program that prints charts showing the
Fahrenheit equivalents of all Celsius temperatures from 0 to 10 degrees, and
the Fahrenheit temperatures from 32 to 42 degrees. Print the outputs in a neat
tabular format.
celsius = (5.0 / 9.0) * (Fahrenheit - 32.0)
fahrenheit = 32.0 + (Celsius *(9.0/5.0))

2- The Fibonacci series


0,1,2,3,5,8,13,21,….
Begins with the term 0 and 1 and has the property that each succeeding term
is sum of the two preceding terms.
Write a recursive function Fibonacci(n)that calculates the nth Fibonacci
number.

3- Write a function distance that calculates the distance between two


points (x1, y1) and (x2, y2). all numbers and return values should be of
type float.
Then call the function in the main, receive the values from keyboard to
calculate the distance.

17

You might also like