Skip to main content

Practical-2

Write a Java Program that will display factorial of the given number.

Introduction

This task is designed to introduce you to programming, specifically Java programming. The program you will be writing will be a Java program that displays the factorial of a given number. A factorial is a mathematical operation that multiplies a number by every integer preceding it, for example if given the number 5, the factorial of 5 is 5x4x3x2x1 = 120. By completing this task, you will gain an introduction to writing Java code and understanding the fundamentals of Java programming.

Code

public class Factorial {
public static void main(String[] args) {
// Create a variable to store the input number
int number = 5;

// Calculate the factorial
int result = 1;
for (int i = number; i >= 1; i--) {
// Multiply each number against the result
result = result * i;
}

// Print out the result
System.out.println("The factorial of " + number + " is " + result);
}
}

Output

The factorial of 5 is 120
Explanation

In this Java program, we first created an integer variable called 'number' and declared it as 5. This variable will store our input number whose factorial we will be calculating later.

We then created a for loop where the variable i is initialized at the value of our input number and decrements the value of i each time the loop is run.

In the body of the loop, we are calculating the factorial. We initialize the 'result' variable with a value of 1, and then multiply it with the value of 'i'. This will ensure that the result keeps incrementing with the value of 'i' every time the loop is run.

Finally, we print out the result to the console.