Write a program to find the factorial of a number using (the four forms of methods).
(FULL PROGRAM) AND USING BLUE J NOT JAVA.
NO SPAM OR REPORT
Share
Write a program to find the factorial of a number using (the four forms of methods).
(FULL PROGRAM) AND USING BLUE J NOT JAVA.
NO SPAM OR REPORT
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
[tex]answer[/tex]
Sure! Here's a full program to find the factorial of a number using the four forms of methods in BlueJ:
```java
public class Factorial {
// Method 1: Non-recursive method
public static int factorialNonRecursive(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Method 2: Recursive method
public static int factorialRecursive(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
// Method 3: Tail-recursive method
public static int factorialTailRecursive(int n, int result) {
if (n == 0 || n == 1) {
return result;
}
return factorialTailRecursive(n - 1, n * result);
}
// Method 4: Iterative method
public static int factorialIterative(int n) {
int result = 1;
while (n > 1) {
result *= n;
n--;
}
return result;
}
public static void main(String[] args) {
int num = 5;
int result1 = factorialNonRecursive(num);
System.out.println("Factorial (Non-recursive): " + result1);
int result2 = factorialRecursive(num);
System.out.println("Factorial (Recursive): " + result2);
int result3 = factorialTailRecursive(num, 1);
System.out.println("Factorial (Tail-recursive): " + result3);
int result4 = factorialIterative(num);
System.out.println("Factorial (Iterative): " + result4);
}
}
```
To run this program in BlueJ, follow these steps:
1. Open BlueJ and create a new project.
2. Create a new class called "Factorial".
3. Copy and paste the above code into the "Factorial" class.
4. Click on the "Compile" button in BlueJ to compile the code.
5. Right-click on the "Factorial" class and select "void main(String[] args)" to run the program.
6. The program will calculate and display the factorial of the number 5 using the four different methods.
The output will be:
```
Factorial (Non-recursive): 120
Factorial (Recursive): 120
Factorial (Tail-recursive): 120
Factorial (Iterative): 120
```
Each method will calculate the factorial of the given number (5 in this case) and display the result.