Fibonacci Project

Fibonacci in Java

Sunday, January 6th, 2008

So we’ve seen lots of examples of our Fibonacci program in scripting languages, but other than C, I haven’t touched on many compiled languages. So here is a version in Java, probably one of the most common and popular languages in use today. Considered by advocates to be the among the best enterprise application development languages, we’ll see here how to write our simple program.

/*
 * Much like C's stdio.h, the java.io.* classes will let us access stdin and stdout.
 */

import java.io.*;

/*
 * Like Ruby, in java, everything is an object. To write a program, you'll need to
 * start by declaring a class. As in C, our program execution starts with the main
 * function. Also like C, Java is a compiled language, so you'll need to compile 
 * the code and then run the class using the java interpreter.
 */

class Fibonacci {

  /*
   * So here we are defining the main function. Remember that this is supposed to
   * actually run this program, so the function needs to be `public`, in addition,
   * it's `static`, meaning we can call this method without an object of the Fibonacci
   * class being instantiated, and it doesn't need to return anything, as it will
   * run by the interpreter, which will handle the exit status. 
   */

  public static void main(String args[]) {

    /* 
     * We are using System.out.println here, but newer versions of Java have the printf method.
     */

    System.out.println("How many numbers of the sequence would you like?");

    /*
     * I'm sure there's more than one way to skin a cat, but to read stdin here, we
     * are creating a new BufferedReader, which will read one line of input.
     */

    InputStreamReader sr = new InputStreamReader(System.in);
    BufferedReader br    = new BufferedReader(sr);

    /*
     * Now here is a concept we haven't addressed yet. The java compiler complains if
     * you try to call a method that could throw an exception (error), so I've included
     * an example here of how to handle the exceptions that could be thrown. Also, like
     * in our previous examples, we are casting the input to an integer.
     */

    try {
      String input = br.readLine();
      int n = Integer.valueOf(input).intValue();
      fibonacci(n);
    } catch (NumberFormatException e){
      System.out.println("That is not an integer. Please enter an integer value");
    } catch (IOException e) {
      System.out.println("I did not recieve an input");
    }
  }

  /*
   * So here is our Fibonacci function. like the main function, it is public and can be
   * called without creating a Fibonacci object. We've also introduced a new method of 
   * calculating the sequence without using a temporary variable. In a later post, I will
   * examine the different algorithms used to calculate the Fibonacci sequence, and compare
   * performance in multiple languages.
   */

  public static void fibonacci(int n){
    int a=0,b=1;

    for (int i=0;i<n;i++){
      System.out.println(a);
      a=a+b;
      b=a-b;
    }
  }
}

HTML code generated by vim-color-improved v.0.4.0.Download this code: fibonacci.java

Fibonacci in Ruby

Saturday, January 5th, 2008

So finally we get to Ruby. Is it a ghetto? I don’t know about that, but I do know that writing our simple Fibonacci program in Ruby was a piece of cake. Before we get to the good stuff, though, I’d like to recap where we are, and what we’ve done so far. Here’s a list of the Fibonacci project programs so far:

So this is our sixth version of the simple sequence generator, this time in Ruby

#!/usr/local/bin/ruby

# In Ruby, we define a function with def...end functions can accept parameters,
# but don't have to, and you can leave off the parenthesis if your function does
# not need them.

def main
  printf "\nHow many numbers of the sequence would you like?\n"

  # Here, STDIN is a constant, but like everything in Ruby, it's also a class, so
  # we use the readline method to get our input. to_i casts our input to an integer

  n = STDIN.readline.to_i
  fibonacci(n)
end

# Here is a good example of something that is cool about Ruby. The times method
# works just like it sounds, it will do something n times. As in Perl and Python,
# we don't need a temp variable here to swap the values for a and b.

def fibonacci(n)
  a,b = 0,1
  n.times do
    printf("%d\n", a)
    a,b = b,a+b
  end
end

main

HTML code generated by vim-color-improved v.0.4.0.Download this code: fibonacci.rb

The next installment will be another popular language. Stay tuned to see Fibonacci in Java.

Fibonacci in Python

Saturday, January 5th, 2008

In our latest installment of the Fibonacci project, we’ll write our simple program in Python. For those of you who are unfamiliar with what we are doing here, please read the first post here. Python is a newer, but increasingly popular scripting language. I suppose the most interesting difference here is that Python is dependent on indentation to define blocks, rather than braces or other language constructs.

#!/usr/bin/python

# Import the system library. This allows us to access stdin later.
import sys

# Here's our main function. Python is pretty efficient here. You
# should notice that there are no braces. Python is dependant on
# whitespace to define blocks.

def main():
  print "\nHow many numbers of the sequence would you like?"
  n = int(sys.stdin.readline())
  fibonacci(n)

# Here's the fibonacci function. Like in Perl, you can assign multiple
# variables on a line without using a temporary variable. Also, the for 
# loop here works more like a foreach loop by setting a range from 0 to n.

def fibonacci(n):
  a,b = 0,1
  for i in range(0,n):
    print a
    a,b, = b,a+b

main()

HTML code generated by vim-color-improved v.0.4.0.Download this code: fibonacci.py

Fibonacci in Perl

Thursday, January 3rd, 2008

So this is our fourth post of the Fibonacci project, and in this installment, we are going to take on Perl. For those of you who don’t know about the Fibonacci project, you should read the first post, Fibonacci in C. Also, you may want to check out the other posts in the series. The comments in the code will make more sense if you have seen the other examples.

#!/usr/bin/perl

# Functions in Perl are called subroutines. Like bash, you don't define the 
# parameters in the function declaration. We'll see how to access the parameters
# when we look at the Fibonacci subroutine below.

sub main {

# Again, the ubiquitous printf function. Apparently a staple of programming
printf "\nHow many numbers of the sequence would you like?\n";

# Once again, we don't need to declare variables before using them.
# Perl's scalar variables, prefaced with $, can be either strings or numbers
# We use <STDIN> to get the data from stdin here

$n = <STDIN>;

# As in PHP, we need to remove the newline at the end

chop $n;

&fibonacci($n);

exit 0;
}

# Except for the first line declaring the subroutine, and the different way that
# parameters passed to the subroutine are passed, this is identical to the PHP version

sub fibonacci {
  $a = 0;
  $b = 1;

  # So now we see the parameter being used here. For clarity, I have written the for
  # loop using $n like the other examples. To set $n using the first parameter passed
  # to the subroutine, I access the scalar variable $_[0], which is the first element
  # of the parameter array @_

  $n = $_[0];

  for ($i=0;$i<$n;$i++){
    printf "%d\n", $a;
    $sum = $a + $b;
    $a = $b;
    $b = $sum;
  }
}

&main;

HTML code generated by vim-color-improved v.0.4.0.Download this code: fibonacci.pl

Any Perl gurus want to critique my work here? Like most of the examples, this is a simplified version, but one that works.

Fibonacci in BASH

Thursday, January 3rd, 2008

So here’s the big surprise. Shell scripting! It’s not what most people think of when they think of programming, but systems administrators are still doing lots of scripting work to automate tasks. Shell scripting can tackle some pretty serious and complicated problems, so running our Fibonacci program is no sweat. If you haven’t seen the Fibonacci in C and the Fibonacci in PHP, now might be a good time to review them.

#!/bin/bash

#
# Here is our main function. Like PHP, I could have simply placed this in the script
# rather than having a function. You notice that like C and PHP, the printf function
# still exists. Unlike C and PHP function calls do not enclose the parameters with 
# paraenthsis.

function main {
  printf "\nHow many numbers of the sequence would you like?\n"

  # Bash lets us use a function "read" to get input from stdin
  # Notice that we are not using a dollar sign in front of the variables when
  # we set them, but we need to when we use them.

  read n
  fibonacci $n

  # Again, I'm exiting with status 0

  exit 0
}

# Starting to look familiar? This function is actually a little different than the 
# C style for loop that we've used before. Instead we use while..do..done to accomplish
# the same thing. You'll also see that rather than specifying parameters in the 
# function;s declaration, we simply reference the variable "$1" to get the first parameter
# passed when the function was called.

function fibonacci {
  a=0
  b=1
  i=0

  while [ $i -lt $1 ]
  do
    printf "%d\n" $a
    let sum=$a+$b
    let a=$b
    let b=$sum
    let i=$i+1
  done
}

main

HTML code generated by vim-color-improved v.0.4.0.Download this code: fibonacci.sh

So what are the gotchas for scripting in BASH? What killed me is whitespace! (a=1 is not the same as a = 1). Once you get the hang of it, it’s not a big deal, but if you are used to working in PHP or another language that ignores whitespace, you’ll run through a few syntax errors before figuring it out. Using an editor like Vim that has syntax highlighting will help a lot there.So there is the third version of our Fibonacci project. Coming soon, I’ll take on the popular scripting languages perl, python, and ruby.

Fibonacci in PHP

Thursday, January 3rd, 2008

So here is my second post in the Fibonacci project. For those of you that have not seen the first post here, the Fibonacci project is a learning experiment designed to highlight the similarities and differences between programming languages. In our C Fibonacci example, we learned that we need to declare variables and types, even the return type of a function. In this PHP example, we’ll see that PHP, while different, is very similar to C in syntax.

#!/usr/bin/php -q

<?php
/**
 * This is our main function. In PHP, there isn't really a need for this to be
 * a function, but to keep consistant, I've placed it there anyway, and called
 * it from the script. In keeping with good programming practices, this script
 * exits with a status 0. Any other status would indicate an error condition.
 */

function main(){

  printf("How many numbers of the sequence would you like?\n");

  /*
   * To read from stdin in php, you open it as a file handle, and use
   * the standard file reading functions
   */

  $fr=fopen("php://stdin","r");
  $n = rtrim(fgets($fr,128));
  fclose ($fr);

  /* Then we call the fibonacci function */
  fibonacci($n);
  exit(0);
}

/**
 * The fibonacci function should look familiar.
 */

function fibonacci($n){
  /* 
   * Notice that in PHP, we do not have to declare our variables, nor must we
   * declare their types. Also see how variables in PHP are prefaced with the 
   * dollar sign. Other than that, this is identical to the C version of this function.
   */
  $a = 0;
  $b = 1;
  for ($i = 0; $i < $n; $i++){
    printf("%d\n",$a);
    $sum = $a+$b;
    $a = $b;
    $b = $sum;
  }
}

/**
 * In PHP, program execution starts here. It isn't neccessary to place functions 
 * ahead of the program, but it's a good practice. In a larger application, these
 * functions would be in seperate files. Again, since PHP is a procedural language,
 * I could have simply included the contents of the main function here, rather than
 * defining a function and calling it.
 */

main();

?>

HTML code generated by vim-color-improved v.0.4.0.Download this code: fibonacci.php

You’ll notice a couple of things about this version of the Fibonacci program. Because it’s intended to be run on the command line, the first line tells the shell which interpretor to use. In addition, I have been careful here to return an exit code so that the shell knows that the program completed successfully.Stay tuned for our next installment, I’ll keep it a surprise, and even though everyone thinks it will be Ruby, I’m going to save that one for later.

Fibonacci in C

Thursday, January 3rd, 2008

Welcome to the first post of the Fibonacci project. In the following weeks, I am going to write this simple program in as many languages as possible, to highlight the similarities and differences between them. Today I will start with C, a classic language that is still in use today, and a good foundation for everything else that we will see. Rather than writing a lengthy post with each language, I’ll try to comment the code to point out the important things. Hopefully, this learning experiment will teach me something, and hopefully it will provide a handy resource for people to compare languages, even if it’s in a limited capacity.

So before I started, I gave myself the following “spec sheet” for writing the code:

The purpose of the Fibonacci project is to create a simple programming example in as many languages as possible, to provide a clear demonstration of the differences and similarities between them.

The sample code should:

  • Accept an input “x” (A value to progress up to)
  • Starting at 0 and 1, output the Fibonacci sequence up to “x” permutations.
  • There should be two functions, for clarity.
    • (main) Accepts the input and calls the fibonacci function.
    • (fibonacci) One that accepts the value of x and outputs the sequence.

The code should accept input from the console (stdin), with a prompt, and output to the console (stdout). This is so we keep everything simple. All of the code should be thoroughly commented.

/**
 * You'll notice that we need to include a header file that
 * contains functions we need to use. Being a compiled language,
 * it's inefficient to include functions that aren't needed.
 * stdio.h contains functions for reading from and writing to the console
 */

#include <stdio.h>

/**
 * In C, the program executes the main function. You should also take note
 * that we must declare a return type for the function. In this case, it's
 * an integer, and we return 0 to indicate successful completion of the 
 * program.
 */

int main ()
{
  /* Notice that we need to declare our variables, and their type */

  int n;

  /* printf prints a formated string to the stdout */

  printf("\nHow many numbers of the sequence would you like?\n");

  /* scanf reads a formated string from the stdin. We are expecting an integer here. */

  scanf("%d",&n);

  /* Here we call the fibonacci function */

  fibonacci(n);

  /* Finally, return 0 */

  return 0;
}

/**
 * This is the simple fibonacci sequence generator. Notice also, we
 * declare the type of variable we expect to be passed to the function.
 */

int fibonacci(int n)
{
  /**
   * Here we declare and set our variables.
   */
  int a = 0;
  int b = 1;
  int sum;
  int i;

  /**
   * Here is the standard for loop. This will step through, performing the code
   * inside the braces until i is equal to n.
   */
  for (i=0;i<n;i++)
  {
    printf("%d\n",a);
    sum = a + b;
    a = b;
    b = sum;
  }
  return 0;
}

HTML code generated by vim-color-improved v.0.4.0.Download this code: fibonacci.c

So there’s my version of the Fibonacci sequence generator in C. I’m sure there are some problems with it, but the above code works. What would you change to make it better? Stay tuned for the next installment … PHP.