Skip to content

[C++] Tutorial(7): Functions

The functions can divide the code of different purpose in a program, and use the defined code repeatedly by calling the function if we need.

But remember, main() function is the entry point of the program. all functions must be declared completed before main().

In addition, function need to comply with the declared data type. For example, you cannot use char to declare a function and return a numeric variable.

Next, I will introduce how to define a function.


We can define a function to implement the function we want

For example, if we want a function to add two arrays, we can write:

#include <iostream>
using namespace std;


void sum(int a[], int b[]) {
    for (int i=0; i<5; i++) {
        a[i] += b[i];
    }
}


int main() {
    int a[5] = {1, 2, 3, 4, 5};
    int b[5] = {6, 7, 8, 9, 10};

    // Sum
    sum(a, b);

    // Print
    for (int i=0; i<5; i++) {
        cout << a[i] << endl;
    }

    return 0;
}



Output:

7
9
11
13
15

As you can see, we did add the value of the b array to the a array through sum().


Fibonacci (Recursive)

說到函式,就不得不提到函式的常用功能之一 —— 遞迴式的建構。透過函式自己呼叫自己,可以逐步將複雜的問題一層層地簡化,直到完成。

在這裡,我簡單介紹何謂費氏數列Fibonacci numbers)。

In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F0 = 0, F1 = 1,

and

Fn = Fn-1 + Fn-2,

for n > 1.

The beginning of the sequence os thus:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

—— From Wikipedia

The above is a simple introduction to the Fibonacci sequence. The most important thing is the three math formulas in the middle. And these three math formulas, we can use three judgment formulas to complete, and write them as functions, in order to achieve recursion.

The following is the implementation:

#include <iostream>
using namespace std;


int fibo(int n) {
    if (n == 0) {
        return 0;
    }
    else if (n == 1) {
        return 1;
    }
    else {
        return fibo(n-1) + fibo(n-2);
    }
}


int main() {
    // Print
    cout << fibo(5) << endl;

    return 0;
}



Output:

5

You can try another value.


References


Read More

Tags:

Leave a Reply