DEV Community

Cover image for Fibonacci Day!
Matt Ryan
Matt Ryan

Posted on

Fibonacci Day!

Fibonacci Day is celebrated today, on November 23, because the date formation of today is 11/23 (1, 1, 2, 3), which represents the Fibonacci sequence!

Here are some simple scripts to print the Fibonacci sequence in python, java and javascript.

Python:

nterms = int(input("Enter the value of n: "))

n1, n2 = 0, 1
count = 0

if nterms <= 0:
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1
Enter fullscreen mode Exit fullscreen mode

Java:

import java.util.Scanner;

public class FibonacciSeries {
   public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
       System.out.print("Enter the value of n: ");
       int n = s.nextInt();
       fibonacci(n);
   }
   public static void fibonacci(int n) {
       System.out.print("Fibonacci sequence:");
       if (n == 0) {
           System.out.println("0");
       } else if (n == 1) {
           System.out.println("0 1");
       } else {
           System.out.print("0 1 ");
           int a = 0;
           int b = 1;
           for (int i = 1; i < n; i++) {
               int nextNumber = a + b;
               System.out.print(nextNumber + " ");
               a = b;
               b = nextNumber;
           }
       }
   }
}
Enter fullscreen mode Exit fullscreen mode

Javascript:

const number = parseInt(prompt('Enter the value of n: '));
let n1 = 0, n2 = 1, nextTerm;

console.log('Fibonacci sequence:');

for (let i = 1; i <= number; i++) {
    console.log(n1);
    nextTerm = n1 + n2;
    n1 = n2;
    n2 = nextTerm;
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)