Navigation

Wednesday, December 8, 2010

Java: Fibonacci & Inverted Pyramid

Fibonacci.java

This class displays numbers following the Fibonacci sequence. A Fibonacci number is a number which is a sum of the previous two numbers in the sequence. By definition, the first and second numbers of Fibonacci are 0 and 1, respectively.

The number of numbers depends on the user's input. An integer is expected to be the input. The code will not catch errors and will instead terminate upon wrong input.

import java.io.IOException;

publicclass Fibonacci {

publicstaticvoid main(String[] args) throws IOException {

int input, x, y, z;

x = 1;

y = 0;

z = 0;

System.out.println( "Enter a number: " );

input = System.in.read() - 48;

for (int i = 0; i <= input; i++) {

System.out.println( "F( " + i + " ) = " + z);

z = x + y;

x = y;

y = z;

} } }

InvertedPyramid.java

This class displays an inverted pyramid or triangle, consisting of asterisks per block, depending on the number given by the user.

An integer is expected to be the input, which determines the height of the pyramid. The code will not catch errors and will instead terminate upon wrong input.

import java.io.IOException;

publicclass InvertedPyramid {

publicstaticvoid main(String[] args) throws IOException {

int input, n;

System.out.println( "Enter a number: " );

input = System.in.read() - 48;

n = 1;

for (int i = input; i > 0; i--) {

for (int j = 1; j <= n; j++) {

System.out.print( " " );

}

for (int k = i; k > 0; k--) {

System.out.print( "* " );

}

System.out.println();

n++;

} } }

The code are best viewed in a programming editors, such as Eclipse for Java IDE and ConText, where indentations are possible.