top of page

Java Program to add two Fraction

Writer's picture: PREETI CHOUHANPREETI CHOUHAN

In this post, we will learn how to add two fractions and calculate result in simplified form.


Implementation Using Java:

import java.util.Scanner;
public class CalFraction {
	int num;
	int den;
	CalFraction(int num, int den)
	{
		this.num=num;
		this.den=den;
	}
        public static void main(String[] args) {
		Scanner sc= new Scanner(System.in);
		System.out.println("Enter the num of f1");
		int num1=sc.nextInt();
		System.out.println("Enter the den of f1");
		int den1 =sc.nextInt();
		System.out.println("enter the num of f2");
		int num2=sc.nextInt();
		System.out.println("Enter the den of f2");
		int den2=sc.nextInt();
		CalFraction f1=new CalFraction(num1,den1);
		CalFraction f2=new CalFraction(num2,den2);
		f1.add(f2);
        }
		public void add(CalFraction f2)
		{
			this.num=this.num*f2.den+this.den*f2.num;
			this.den=this.den*f2.den;
			simplify(this.num,this.den);
		}
		public void simplify(int num,int den)
		{
			int gcd=1;
			int small=Math.min(num,den);
			for(int i=2;i<=small;i++)
			{
			if((num%i==0) && (den%i==0))
				gcd=i;
			}
			num=num/gcd;
			den=den/gcd;
			System.out.println("The addition is"+" "+num +"/"+den);
			}
}
Output:
Enter num of f1 2
Enter den of f1 5
Enter num of f2 2
Enter den of f2 5

The addition is 4/5
 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

25 views2 comments

Recent Posts

See All

2 Comments


Sudhanshu Mishra
Sudhanshu Mishra
Jun 07, 2020

Great work!

Like

Prateek Chauhan
Prateek Chauhan
Jun 07, 2020

Keep it up

Like
bottom of page