Assignment Two
Due Date: Monday, April 1.
Objective: These exercises will enable you to review basic concepts of control structures and
classes
Submission Details: This assignment is to be done and submitted individually. A link for
submitting your assignment will be made available on the course page as of March 28. Your
assignment will be automatically graded using a software. Therefore, you must follow the
submission guide lines exactly as they are
Your Java package for the assignment must be placed in a new folder. The folder’s name
must be your full name plus your ID number exactly as in the following format:
abebe kebede-tcr 1256 99
Inputs must be accepted in the exact order shown in the example I/O windows
No extra text must be included as part of your output. For example if the result you
want to display is 5, just display the number 5. Do NOT display
“The result is 5” since the grading software cannot match it with the expected output.
1. Write a program that accepts two integers from the user and displays their
greatest common divisor (GCD) if they have any. Otherwise it should display 1.
Some examples of the console I/O for your program is shown below:
Enter First Number: 10
Enter Second Number: 15
5
Enter First Number: 30
Enter Second Number: 15
15
Enter First Number: 3
Enter Second Number: 8
1
2. The value 𝑒 𝑥 can be approximated by the sum:
𝑥2 𝑥3 𝑥𝑛
𝑒𝑥 = 1 + 𝑥 + + + ⋯
2! 3! 𝑛!
Write a program that takes a values of x and n as inputs from the user and outputs this
sum. A sample of input/output if shown below
Enter the value of x: 3
Enter the value of n: 100
20.08553692318766
Hints:
Use variables of type double to store the factorials (or arrange your calculation to
avoid any direct calculation of factorials); otherwise, you are likely to produce integer
overflow, that is, integers larger than Java allows.
Also, you will have a neater solution if you first define a function that takes a value of
n and returns its factorial. You can add your function below the main method as
follows:
public static void main(String[] args){
//code for main method goes here
public static double factorial(int n)
{
//code for calculating and returning factorial goes here
}
Java’s pow function for calculating 𝑥 𝑖 can be accessed as follows: Math.pow(x,i).
Here both x and i must be of type double, or they have to be casted to type double.
Once you run your program, check how close your output is with a pre-computed
value.