C/Java - Fibonacci Sequence
In this C and Java tutorial, you'll learn how to count and display the first N Fibonacci numbers.The Fibonacci sequence is defined by:
n ≥ 1 such as U1=U2=1
and
The program below prints the first 20 numbers of the Fibonacci sequence with the iterative method. Each term is formed by adding the previous two terms in the sequence. Starting with terms 1 and 1.
Output:#include< stdio.h>
#include< stdlib.h>
main() {
int n1 = 1, n2 = 1, n3;
printf("%d %d ", n1 ,n2 );
for (int i = 0; i < 18; i++) { //Loop for the next 18 terms
n3= n2 + n1; //the next term is the sum of the previous two
printf("%d ", n3);
n1 = n2; First previous becomes 2nd previous
n2 = n3; And the current number becomes the previous
}
printf("\n");
system("pause");
}
2- Fibonacci in Java:
We have chosen to do a recursive treatment, as input an integer n and as output the term of the rank n of the sequence. Here are the two cases of recursion:
- If n is less than or equal to 1, n takes two values 0 or 1. fib(0)=0 and fib(1)=1.
- otherwise the recurrence starts from n which decrements to the second term.
import java.io.InputStreamReader;
import java.util.Scanner;
/*
* Count and display the first N Fibonacci numbers.
*/
public class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
//display the first N Fibonacci number
for(int i = 1 ; i <= N ; i++)//start from n=1
System.out.println(i + ": " + fib(i));
}
private static int fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
}
Output:20
fib(1)= : 1
fib(2)= : 1
fib(3)= : 2
fib(4)= : 3
fib(5)= : 5
fib(6)= : 8
fib(7)= : 13
fib(8)= : 21
fib(9)= : 34
fib(10)= : 55
fib(11)= : 89
fib(12)= : 144
fib(13)= : 233
fib(14)= : 377
fib(15)= : 610
fib(16)= : 987
fib(17)= : 1597
fib(18)= : 2584
fib(19)= : 4181
fib(20)=: 6765