Basic java code
Calculating Factorial in Java Using Recursion
In this post, we’ll explore how to calculate the factorial of a non-negative integer using Java. Factorial, denoted as , is the product of all positive integers up to . For instance, .
The Code
Here’s a simple Java program that prompts the user to enter a non-negative integer and calculates its factorial using a recursive method.
import java.util.Scanner;public class Factorial {public static void main(String[] args) {Scanner num = new Scanner(System.in);System.out.print("Enter a non-negative integer: ");int number = num.nextInt();if (number < 0) {System.out.print("Please enter a non-negative number.");} else {long fact = calcfact(number);System.out.print("The factorial of " + number + " is " + fact);}num.close(); // Close the scanner}public static long calcfact(int n) {if (n == 0) {return 1; // Base case: factorial of 0 is 1} else {return n * calcfact(n - 1); // Recursive case}}}
Explanation of the Code
Importing the Scanner Class:
import java.util.Scanner;
This line imports the
Scanner
class, which is used to read input from the user.Main Class:
public class Factorial {
The class is defined with the name
Factorial
.Main Method:
public static void main(String[] args) {
This is the entry point of the program. It executes the code inside it.
Creating a Scanner Object:
Scanner num = new Scanner(System.in);
This creates a
Scanner
object namednum
to read input from the console.User Input:
System.out.print("Enter a non-negative integer: "); int number = num.nextInt();
The program prompts the user to enter a non-negative integer.
Input Validation:
if (number < 0) { System.out.print("Please enter a non-negative number."); }
If the user enters a negative number, a message is displayed, and the program does not proceed to calculate the factorial.
Calculating Factorial:
long fact = calcfact(number);
If the input is valid, the program calls the
calcfact
method to calculate the factorial.Recursive Method:
public static long calcfact(int n) { if (n == 0) { return 1; // Base case } else { return n * calcfact(n - 1); // Recursive call } }
- Base Case: If is 0, the method returns 1 (since ).
- Recursive Case: If is greater than 0, it returns multiplied by the factorial of .
Closing the Scanner:
num.close();
It’s a good practice to close the
Scanner
object to free up system resources.
Comments
Post a Comment