Chapter 4 - Functions
Chapter 4 - Functions
Chapter 4 - Functions
Chapter 4: Functions
A function is a block of code which only runs when it is called.
Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But
you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed
by parentheses ():
Syntax
void myFunction() {
// code to be executed
}
Example Explained
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Example
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
• Declaration: the return type, the name of the function, and parameters (if any)
• Definition: the body of the function (code to be executed)
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Note: If a user-defined function, such as myFunction() is declared after the main() function, an
error will occur:
Example
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error
However, it is possible to separate the declaration and the definition of the function - for code
optimization.
You will often see C++ programs that have function declaration above main(), and function
definition below main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
The following example has a function that takes a string called fname as parameter. When
the function is called, we pass along a first name, which is used inside the function to print the
full name:
Example
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Return Values
The void keyword, used in the previous examples, indicates that the function should not return
a value. If you want the function to return a value, you can use a data type (such as int, string,
etc.) instead of void, and use the return keyword inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
Pass By Reference
In the examples from the previous page, we used normal variables when we passed parameters
to a function. You can also pass a reference to the function. This can be useful when you need
to change the value of the arguments:
Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
// Call the function, which will change the values of firstNum and
secondNum
swapNums(firstNum, secondNum);
return 0;
}
Recursion
Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to
experiment with it.
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Recursion Example
Adding two numbers together is easy to do but adding a range of numbers is more complicated.
In the following example, recursion is used to add a range of numbers together by breaking it
down into the simple task of adding two numbers:
Example
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
}
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller
than k and returns the result. When k becomes 0, the function just returns 0. When running,
the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0
Since the function does not call itself when k is 0, the program stops there and returns the
result.
Note: The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically elegant approach to programming.
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Problem 1: Write a function to find the maximum of two numbers. Apply to find the maximum
number among three numbers a, b, c with a, b, c entered from the keyboard.
Input: 4 9 3 Output: 9
Problem 2: Write a function to find the greatest common divisor of two numbers a and b.
Apply: enter the numerator and denominator of a fraction, check if the fraction is simplified or
not.
Input: 2 4 Output: The greatest common divisor is 2. The simplified fraction is 1/2
Input: 3 7 Output: The fraction is already simplified.
Problem 3: Write a function that sums the digits of an integer. Write a program to input an
integer and use the function above to check if the number is divisible by 3. A number is divisible
by 3 when the sum of its digits is divisible by 3.
Input: 123456 Output: Sum of digits is 21, so 123456 is divisible by 3
Problem 4: Pascal's triangle is a table of numbers, where the 0-th row equals 1, each term of
the (n+1)-th row is a k-combination of n which can be calculated by formula:
𝑛!
𝐶!" =
𝑘! (𝑛 − 𝑘)!
Pascal's triangle has the following form:
Line 0: 𝐶##
Line 1: 𝐶$# 𝐶$$
Line 2: 𝐶%# 𝐶%$ 𝐶%%
Line 3: 𝐶&# 𝐶&$ 𝐶&% 𝐶&&
Line 4: 𝐶'# 𝐶'$ 𝐶'% 𝐶'& 𝐶''
Line 5: 𝐶(# 𝐶($ 𝐶(% 𝐶(& 𝐶(' 𝐶((
Write a program that prints to the screen Pascal's triangle with n rows (n is entered from user)
by creating two functions for factorial and combination.
Input: 6
Output: Line 0: 1
Line 1: 1 1
Line 2: 1 2 1
Line 3: 1 3 3 1
Line 4: 1 4 6 4 1
Line 5: 1 5 10 10 5 1
Line 6: 1 6 15 20 15 6 1
Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)
Where n is a positive integer and x is any number entered from the keyboard when running
the program.
Input: Please input n and x: 3 2
Output: 𝑆1 = 15 (1 + 2 + 2% + 2& )
𝑆2 = −5 (1 − 2 + 2% − 2& )
% %! %"
𝑆3 = 6.33 (1 + $! + %!
+ &!
)
Problem 7: Write a program to print to the screen Fibonacci sequence using a recursive
Fibonacci function F.
1 𝑖𝑓 𝑛 = 0 𝑜𝑟 𝑛 = 1
𝐹! = ,
𝐹!)% + 𝐹!)$ 𝑖𝑓 𝑛 ≥ 2
Input: 6
Output: 1 1 2 3 5 8
Problem 8: Write a program to factor a positive integer into prime factors using recursive.
Input: 100
Output: 100 = 2 * 2 * 5 * 5
Lecturer: Quang-Thai Ho