• + 0 comments

    My 2 cents in Java:

    public class Day9Recursion {
    
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int n = Integer.parseInt(br.readLine().trim());
            int result = Result.factorial(n);
            System.out.println(result);
            br.close();
        }
    
    }
    
    
    class Result {
    
        /*
         * Complete the 'factorial' function below.
         *
         * The function is expected to return an INTEGER.
         * The function accepts INTEGER n as parameter.
         */
    
        public static int factorial(int n) {
            // Base case
            if (n <= 1) {
                return n;
            } else {
                // Recursion
                // ie: 5
                // 5 * factorial(4)
                // 5 * 4 * factorial(3)
                // 5 * 4 * 3 * factorial(2)
                // 5 * 4 * 3 * 2 * factorial(1)
                // 5 * 4 * 3 * 2 * 1 => 120
                return n * factorial(n -1);
            }
        }
    
    }