[go: up one dir, main page]

0% found this document useful (0 votes)
17 views4 pages

Program 1:: Design A Class Factorial To Compute The Factorial of A Number

factorial of a number

Uploaded by

alex rodrigo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views4 pages

Program 1:: Design A Class Factorial To Compute The Factorial of A Number

factorial of a number

Uploaded by

alex rodrigo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

 

Program 1:
Design a class Factorial to compute the factorial of a number.

Class name: Factorial


Data members:
n: integer whose factorial is to be found
f: long store the factorial
Member Functions:
factorial(): constructor to give the initial value to the instance variables
void read(): to accept the value of the number
void fact(): to calculate the factorial of the number recursively
void display(): to display the number and its factorial
Specify the class Factorial giving details of void read() and void fact() and
display()
Define main method() function to create an object and call the method to print
the factorial.
Algorithm:
Algorithm for Class: Factorial
Algorithm for Factorial():
Step 1: Start of algorithm.
Step 2: Initializing n to 0 and f to 1.
Step 3: End of algorithm.

Algorithm for void read():


Step 1: Start of algorithm.
Step 2: To accept value of n from user.
Step 3: End of algorithm.

Algorithm for void fact():


Step 1: Start of algorithm.
Step 2: To calculate factorial using recursion.
Step 3: End of algorithm.

Algorithm for void display():


Step 1: Start of algorithm.
Step 2: To display the number and its factorial.
Step 3: End of algorithm.

Algorithm for void main():


Step 1: Start of algorithm.
Step 2: instatiation of ob
Step 3: To call the methods
Step 4: End of algorithm.
Program

import java.util.*;
public class Factorial
{
int n; // stores number whose factorial to be calculated
long f; // stores factorial of number

Factorial() // assigning values


{
n = 0;
f = 1;
}
public void read()
{
Scanner sc = new Scanner(System.in);
System.out.println("enter a number");
n = sc.nextInt();
}

public void fact()


{
// calculate factorial using recursion
if (n == 1)
{
f*=1;
}
else
{
f *= n--;
this.fact();
}
}

public void display()


{
System.out.println("Number is " + n);
this.fact();
System.out.println("Factorial is " + f);
}

public static void main()


{
Factorial ob= new Factorial(); //instatiation of object ob
ob.read();
ob.display();
}

You might also like