Computer Applications
Write a program by using a class with the following specifications:
Class name — Factorial
Data members — private int n
Member functions:
- void input() — to input a number
- 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.
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
Related Questions
Show with the help of an example how the following base classes can be derived in class bill to fulfill the given requirement:
class elect { String n; float units; public void setvalue() { n = "SOURABH"; units = 6879; } }Class bill uses data members charge and a member function to calculate the bill at the rate of 3.25 per unit and displays the charge. Class elect is inherited by class bill by using private visibility.
Write a program by using a class with the following specifications:
Class name — Prime
Data members — private int n
Member functions:
- void input() — to input a number
- void checkprime() — to check and display whether the number is prime or not
Use a main function to create an object and call member methods of the class.
Write a program by using a class with the following specifications:
Class name — Salary
Data members — private int basic
Member functions:
- void input() — to input basic pay
- void display() — to find and print the following:
da = 30% of basic
hra = 10% of basic
gross = basic + da + hra
Use a main function to create an object and call member methods of the class.
Write a class program with the following specifications:
Class name — Matrix
Data members — int array m[][] with 3 rows and 3 columns
Member functions:
- void getdata() — to accept the numbers in the array
- void rowsum() — to find and print the sum of the numbers of each row
- void colsum() — to find and print the sum of numbers of each column
Use a main function to create an object and call member methods of the class.