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

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


View

Two numbers are entered by the user, x and n. Write a function to find the value of one number raised to the power of another i.e. x^n.


View

Write a function that takes in the radius as input and returns the circumference of a circle.


View

Print the spiral order matrix as output for a given matrix of numbers.


View

Input an email from the user. You have to create a username from the email by deleting the part that comes after ‘@’. Display that username to the user.

Example : 

email = “mejona@gmail.com” ; username = “mejona” 

email = “helloWorld123@gmail.com”; username = “helloWorld123”


View

Reverse a String (using StringBuilder class) in java.


View

Take an array of names as input from the user and print them on the screen.


View