Sunday, 17 July 2011

Write a program to calculate the sum of n rational numbers using array of objects

import java.io.*;
class rational25
{
int num;
int den;
public void input()
throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the numerator");
num=Integer.parseInt(br.readLine());
System.out.println("enter the numerator");
den=Integer.parseInt(br.readLine());
}
public void hcf()
{
int temp=0;
if(num<den)
temp=num;
else
temp=den;
while(temp>=2)
{
if(num%temp==0&&den%temp==0)
{

num=num/temp;
den=den/temp;

}
temp--;
}
System.out.println(num+"/"+den);
}


public void sum(rational25 c[])
{
num=c[0].num;
den=c[0].den;
for(int i=1;i<c.length;i++)
{
num=num*c[i].den+den*c[i].num;
den=den*c[i].den;
}


}
}

class rational25main
{
public static void main(String[] arg)
throws IOException
{
int n=0;
rational25 s=new rational25();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number of rational numbers");
n=Integer.parseInt(br.readLine());
rational25[] c=new rational25[n];
for(int i=0;i<n;i++)
{
c[i]=new rational25();
c[i].input();
}
s.sum(c);
s.hcf();
}
}

No comments:

Post a Comment

 

About The Author


I am a B.Tech Computer Science Student. I love Programming and blogging. I am Oracle certified Java Professional. Read More
Indian Blogger

Teachers Jobs

Footer 3

Twitter Facebook RSS YouTube Google
​

All Rights Reserved ©Sun Java Masters 2013