Slip No 18 Q A

Write a java program to calculate factorial of a number. (Use sleep () method).

import java.util.Scanner;

public class FactorialWithSleep {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number to calculate factorial: ");
        int num = sc.nextInt();

        long factorial = 1;

        System.out.println("Calculating factorial of " + num + " ...\n");

        for (int i = 1; i <= num; i++) {
            factorial *= i;
            System.out.println("Step " + i + ": " + factorial);

            try {
                // Pause for 1 second after each step
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Thread interrupted: " + e);
            }
        }

        System.out.println("\nFactorial of " + num + " is: " + factorial);

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top