Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 4 - Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)

Chapter 4: Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

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

• myFunction() is the name of the function


• void means that the function does not have a return value. You will learn more about
return values later in the next chapter
• inside the function (the body), add code that defines what the function should do

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

Inside main, call myFunction():

// Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"

A function can be called multiple times:

Example
void myFunction() {
cout << "I just got executed!\n";
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

Function Declaration and Definition


A C++ function consist of two parts:

• 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)

void myFunction() { // declaration


// the body of the function (definition)
}

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();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}

Lecturer: Quang-Thai Ho
YUAN ZE UNIVERSITY – Fundamental Computer Programming- C++ Lab(I)

Parameters and Arguments


Information can be passed to functions as a parameter. Parameters act as variables inside the
function.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

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

Default Parameter Value


You can also use a default parameter value, by using the equals sign (=).
If we call the function without an argument, it uses the default value ("Norway"):
Example
void myFunction(string country = "Norway") {
cout << country << "\n";
}

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

// Liam Refsnes. 3 years old.


// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.

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;

cout << "Before swap: " << "\n";


cout << firstNum << secondNum << "\n";

// Call the function, which will change the values of firstNum and
secondNum
swapNums(firstNum, secondNum);

cout << "After swap: " << "\n";


cout << firstNum << secondNum << "\n";

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)

Problem 5: Requirements as in problem 4, but based on the following properties of the


")$ "
combination formula: 𝐶!" = 𝐶!)$ + 𝐶!)$ as follows:
1 𝑖𝑓 𝑘 = 0 𝑜𝑟 𝑘 = 𝑛
𝐶(𝑛, 𝑘) = ,
𝐶 (𝑛 − 1, 𝑘 − 1) + 𝐶 (𝑛 − 1, 𝑘) 𝑖𝑓 1 < 𝑘 < 𝑛
Problem 6: Write a program to calculate the following sums using recursive:
a) 𝑆1 = 1 + 𝑥 + 𝑥 % + 𝑥 & + ⋯ + 𝑥 !
b) 𝑆2 = 1 − 𝑥 + 𝑥 % − 𝑥 & + ⋯ + (−1)! 𝑥 !
* *! *" *#
c) 𝑆3 = 1 + $! + %!
+ &!
+ ⋯+ !!

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

You might also like