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

Input a string from the user. Create a new string called ‘result’ in which you will replace the letter ‘e’ in the original string with letter ‘i’. 

Example : 

original = “eabcdef’ ; result = “iabcdif”

Original = “xyz” ; result = “xyz”


View

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


View

Searching for an element x in a matrix.


View

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


View

Write a function to multiply 2 numbers.


View

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


View

Write an infinite loop using do while condition.


View