Lab 3
Lab 3
Lab 3
Lab 3
Functions
In this lab, we will learn about functions, which allow us to divide the program into smaller,
reusable components, make the source code more modular, easier to read and maintain.
Instructions
1. Function Definition, Declaration and Call
A function is a block of code that performs a specific task. To use a function, it must be declared
(prototype) and then defined.
• Function declaration: Specifies the function’s name, return type, and parameters.
For example:
1 int sum ( int a , int b ) ;
• Function definition: Contains the actual body of the function where the task is performed.
For example:
1 // Function definition
2 int sum ( int a , int b )
3 {
4 int ans = a + b ;
5 return ans ; // Return statement ( the outcome of the function )
6 }
• Function call: After function is defined, you can call it by its name and passing arguments.
For example:
1 int main ()
2 {
3 int a , b ;
4 cin >> a >> b ;
5 cout << " a + b = " << sum (a , b ) << endl ; // Function call
6 return 0;
7 }
2. Return Type
Functions can return a value, which is specified by the returnType in the function declaration.
When the function does not return anything, use void as the return type.
• Return a value:
1 int sum ( int a , int b )
2 {
3 return a + b ; // Returns the sum of a and b
4 }
• Pass by value: The function gets a copy of the argument, and changes made inside the
function do not affect the original variable.
1 void increment ( int x )
2 {
3 x = x + 1; // Does not change the original value
4 }
• Pass by reference: The function gets a reference to the argument, and changes made inside
the function will affect the original variable. Indicated by attaching the ampersand sign (&).
1 void increment ( int & x )
2 {
3 x = x + 1; // Changes the original value
4 }
Exercises
Exercise 1. Swap two numbers
Implement a function swap that exchanges the values of two integers. Then, write a program to
input two integers, use the swap function to exchange their values, and print the swapped values.
Example:
Input Output
10 20 20 10
W
BM I =
H2
Write a program to input weight and height, print BMI result using calculateBMI function.
Example:
Input Output
70 1.75 22.8571
S = 1 + 2 + 3 + ... + n
Write a program to input n, calls the sumUpToN function, and prints the result.
Example:
Input Output
5 15
n! = n × (n − 1) × ... × 1
Example:
Input Output
5 120
Exercise 5. Fibonacci
Implement a function fibonacci that returns the nth Fibonacci number which is defined as follow:
• F0 = 0
• F1 = 1
Write a program to input n, calls the fibonacci function, and prints the result.
Example:
Input Output
7 13
Example:
Input Output
16 true
Example:
Input Output
12345 5
Example:
Input Output
12345 15
Example:
Input Output
24 36 12
Example:
Input Output
10 1010