Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Saturday, 2 February 2019

FIRST WEEK TERM WORK Program 5

5) Write a Java Program for the following problem scenario: Create a package named “BasicMath” which has a class named Basic and has methods to perform following computations: 

a. Addition of two numbers 

b. Subtraction of two numbers 

c. Multiplication of two numbers

d. Division of two numbers

 Create another package named “AdvancedMath” which has a class named Advanced and has methods to perform following computations: 

a. Find sine of an angle 

b. Find ab 

c. Find log10 of a number

 Create a class named TestDemo defined inside a default package. This class must invoke all the methods of Basic and Advanced classes.


Default Package(Main class):

import AdvanceMath.Advance;
import BasicMath.Basic;

public class TestDemo {
public static void main(String[] args) {
Basic obj = new Basic();
Advance obj1 = new Advance();
int a;
double d;
a = obj.add(4, 5);
System.out.println("Sum= " + a);
a = obj.sub(4, 5);
System.out.println("Sub= " + a);
a = obj.mult(4, 5);
System.out.println("mult= " + a);
a = obj.div(4, 5);
System.out.println("div= " + a);
d = obj1.sin(30);
System.out.println("Sin= " + d);
d = obj1.exppow(2, 3);
System.out.println("Pow= " + d);
d = obj1.log(10);
System.out.println("Log= " + d);
}

}


BasicMath Package:

package BasicMath;

public class Basic {
int sum;

public int add(int a, int b) {
sum = a + b;
return sum;
}

public int sub(int a, int b) {
sum = a - b;
return sum;
}

public int mult(int a, int b) {
sum = a * b;
return sum;
}

public int div(int a, int b) {
if (b == 0) {
System.out.println("Error");
return -1;
} else {
sum = a / b;
return sum;
}
}
}

AdvanceMath Package:


package AdvanceMath;

public class Advance {
public double sin(double a) {
double x = 3.14 * a / 180;

// convert x to an angle between -2 PI and 2 PI
x = x % (2 * 3.14);

// compute the Taylor series approximation
double term = 1.0; // ith term = x^i / i!
double sum = 0.0; // sum of first i terms in taylor series

for (int i = 1; term != 0.0; i++) {
term *= (x / i);
if (i % 4 == 1)
sum += term;
if (i % 4 == 3)
sum -= term;
}
return sum;
}

public double exppow(int a, int b) {
double sum = 1;
for (int i = 1; i <= b; i++) {
sum = sum * a;
}
return sum;
}

public double log(int x) {
double sum = Math.log10(x);
return sum;
}
}

0 comments:

Post a Comment