Name: Nisarg Anand Chhoda
UID: 2024200020
Experiment No. 2
AIM:
Program 1
PROBLEM Create a four-function calculator for fractions. Here are the formulas for the four arithmetic
operations applied to fractions:
STATEMENT :
Addition: a/b + c/d = (a*d + b*c) / (b*d)
Subtraction: a/b - c/d = (a*d - b*c) / (b*d)
Multiplication: a/b * c/d = (a*c) / (b*d)
Division: a/b / c/d = (a*d) / (b*c)
Create the class fraction. Use default constructor to set numerator and denominator to 1.
a) There are methods to print the four functions for fractions.
b)Program generates a multiplication table for fractions. Let the user input a denominator, and
then generate all combinations of two such fractions that are between 0 and 1, and multiply
them together. Here’s an example of the output if the denominator is 6:
PROGRAM:
import java.util.*;
class Practice {
int num;
int den;
Practice() {
num = 1;
den = 1;
Practice(int num, int den) {
int gcd = gcd(num, den);
this.num = num / gcd;
this.den = den / gcd;
}
int gcd(int n1, int n2) {
while (n2 != 0) {
int temp = n2;
n2 = n1 % n2;
n1 = temp;
return n1;
void addition(Practice f1, Practice f2) {
num = (f1.num * f2.den) + (f2.num * f1.den);
den = f1.den * f2.den;
simplify();
System.out.println(f1.num + "/" + f1.den + " + " + f2.num + "/" + f2.den + " =
" + num + "/" + den);
void subtraction(Practice f1, Practice f2) {
num = (f1.num * f2.den) - (f2.num * f1.den);
den = f1.den * f2.den;
simplify();
System.out.println(f1.num + "/" + f1.den + " - " + f2.num + "/" + f2.den + " =
" + num + "/" + den);
void multiplication(Practice f1, Practice f2) {
num = f1.num * f2.num;
den = f1.den * f2.den;
simplify();
System.out.println(f1.num + "/" + f1.den + " * " + f2.num + "/" + f2.den + " =
" + num + "/" + den);
void division(Practice f1, Practice f2) {
if (f2.num == 0) {
throw new ArithmeticException("Cannot divide by zero!");
num = f1.num * f2.den;
den = f1.den * f2.num;
simplify();
System.out.println(f1.num + "/" + f1.den + " / " + f2.num + "/" + f2.den + " = "
+ num + "/" + den);
void simplify() {
int gcd = gcd(num, den);
num /= gcd;
den /= gcd;
class operation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a, b, c, d for fraction operations:");
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int d = scan.nextInt();
Practice f1 = new Practice(a, b);
Practice f2 = new Practice(c, d);
Practice result = new Practice();
result.addition(f1, f2);
result.subtraction(f1, f2);
result.multiplication(f1, f2);
result.division(f1, f2);
RESULT:
Program 2
PROBLEM
STATEMENT :
PROGRAM:
RESULT:
Program 3
PROBLEM
STATEMENT:
PROGRAM:
RESULT:
Program 4
PROBLEM
STATEMENT:
PROGRAM:
RESULT:
CONCLUSION: