KnowledgeBoat Logo
|

Computer Applications

Write a program by using a class with the following specifications:

Class name — Factorial

Data members — private int n

Member functions:

  1. void input() — to input a number
  2. void fact() — to find and print the factorial of the number

Use a main function to create an object and call member methods of the class.

Java

Encapsulation & Inheritance in Java

28 Likes

Answer

import java.util.Scanner;

public class Factorial
{
    private int n;
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        n = in.nextInt();
    }
    
    public void fact() {
        int f = 1;
        for (int i = 1; i <= n; i++)
            f *= i;
        System.out.println("Factorial of " + n 
            + " = " + f);
    }
    
    public static void main(String args[]) {
        Factorial obj = new Factorial();
        obj.input();
        obj.fact();
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program by using a class with the following specifications: Class name — Factorial Data members — private int n Member functions: (a) void input() — to input a number (b) void fact() — to find and print the factorial of the number Use a main function to create an object and call member methods of the class.

Answered By

12 Likes


Related Questions