Java For Android Tutorial #16: Calculating factorial using a method


Code:
package com.example;

public class java {
    public static void main(String[] str) {
        System.out.println("factorial of 4: "+factorial(4));
        System.out.println("factorial of 5: "+factorial(5));
        System.out.println("factorial of 6: "+factorial(6));
        System.out.println("factorial of 7: "+factorial(7));

    }
    public static int factorial(int number){
        int result = 1;
        for (int i = 1; i <= number; i = i + 1){
            result = result * i;
        }
        return result;
    }
}

Factorial is a recursive method, there are many approaches used in programming to calculate it. My method is consist of an integer input and output. There is just one loop, which starts from one to the number, which I am calculating the factorial of. During the call, I am taking 4 numbers and making custom calls each time.

Comments

Popular Posts