Skip to content

Doing some coding

March 3, 2011

Today, I tried to write code that involves actual problem solving

I wrote a method that calculates the factorial of a number, here’s how I did it :

public static double calculate(int number){
	if (number > 0){
		int result = 1;
		for(int i = 1; i <= number; i++){
		result *= i;
		return result;
	else if(number == 0) {
		return 0;
	} else {
		String message = "Cannot calculate factorial for a negative integer";
		throw new IllegalArgumentException(message);

Here, I used a loop to calculate the factorial if the number supplied to the method is bigger than zero.
And if it was zero, it should return zero.
If it’s a negative number, it should throw an Exception, I chose IllegalArgumentException here.
I also wrote another method to calculate Fibonacci numbers, here’s the code :

public static int getNumber(int number){
        int[] sequence = new int[number];
        sequence[0] = 0;
        sequence[1] = 1;
        for(int i = 2; i < sequence.length; i++){
            sequence[i] = sequence[i-1] + sequence[i-2];
        return sequence[sequence.length - 1];

Here, I used an array to keep track of the numbers calculated, and used indices to calculate more numbers with the help of a for loop.


From → Java

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: