Write a function to calculate the factorial of a number.


​​import java.util.*;

 

public class Functions {

   public static void printFactorial(int n) {

       //loop

       if(n < 0) {

           System.out.println("Invalid Number");

           return;

       }

       int factorial = 1;

 

       for(int i=n; i>=1; i--) {

           factorial = factorial * i;

       }

 

       System.out.println(factorial);

       return;

   }

   public static void main(String args[]) {

       Scanner sc = new Scanner(System.in);

       int n = sc.nextInt();

 

       printFactorial(n);

   }

}

 



Share to whatsapp

More Questions from Java Basic Codes Module 0

For a given matrix of N x M, print its transpose in java.


View

Take an array of numbers as input and check if it is an array sorted in ascending order.

Eg : { 1, 2, 4, 7 } is sorted in ascending order.

       {3, 4, 6, 2} is not sorted in ascending order.


View

Reverse a String (using StringBuilder class) in java.


View

Write an infinite loop using do while condition.


View

Write a function to calculate the factorial of a number.


View

Find the maximum & minimum number in an array of integers.

[HINT : Read about Integer.MIN_VALUE & Integer.MAX_VALUE in Java]


View

Write a function which takes in 2 numbers and returns the greater of those two.


View