JAVA program to add , subtract two Rational Number

class Ration
{
int num,den;

Ration(int n,int d)
{
if(d<n)
{
num=d;
den=n;
}
else
{
num=n;
den=d;
}
}

Ration()
{
den=0;
num=0;
}

void disp()
{
System.out.println("Value is : "+num+"/"+den);
}

void adjust()
{
int a,b,t;

b=num;
a=den;

while(a%b!=0)
{
t=a%b;
a=b;
b=t;
}
num=num/b;
den=den/b;
}

Ration subRation(Ration ob)
{
Ration ob1=new Ration();
int t;
t=den*ob.den;
ob1.num=num*(t/den)-ob.num*(t/ob.den);
ob1.den=t;
ob1.adjust();
return ob1;
}

Ration addRation(Ration ob)
{
Ration ob1=new Ration();
int t;
t=den*ob.den;
ob1.num=ob.num*(t/ob.den)+num*(t/den);
ob1.den=t;
ob1.adjust();
return ob1;
}
}


class Rational
{
public static void main(String p[])
{
Ration ob=new Ration(4,6);
Ration ob1=new Ration(2,4);
Ration ob2;

ob.adjust();
ob1.adjust();
ob.disp();
ob1.disp();
ob2=ob.addRation(ob1);
ob2.disp();
ob2=ob.subRation(ob1);
ob2.disp();
}
}

Comments

Popular posts from this blog

Pascal Triangle using 2D array

JAVA program to add two distance