The Fibonacci sequence is given in the following order [latex] Fibonacci = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 . . .[/latex]. The algorithm for calculating the nth element is given by: [latex] N = N – 1 + N – 2 [/latex], i.e. the nth element is equal to the sum of the two elements preceding it, for example:
Given the Fibonnaci sequence [latex] 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. . .[/latex] calculate the 3rd element of the sequence:
We always take into account the value of the first two terms, such that [latex]X = 0[/latex] (first element) and [latex]Z = 1[/latex]. Then the third element of the sequence will be equal to the sum of the two previous elements, in which case [latex] N = X + Z [/latex], [latex]N = 0 + 1 [/latex], [latex]N[/latex]= 1.
C language program that calculates the nth term of the Fibonacci sequence:
#includelong int fibonacci(int n); void main() { //Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55... int n; printf ("Choose position: "); scanf("%d", &n); printf("Position %d of fibonnaci sequence: %d", n, fibonacci(n)); } long fibonacci(int n) { int cont; long int x = 0, z = 1; if(n % 2 == 0) { for(cont = 2; cont != n; cont = cont + 2) { x = x + z; z = x + z; } return z; } else { for(cont = 1; cont != n; cont = cont + 2) { x = x + z; z = x + z; } return x; } }