Write a program in java to determine the coefficients of binomials in the form o
ID: 3688895 • Letter: W
Question
Write a program in java to determine the coefficients of binomials in the form of (A+B)n. Only use, if, for, do, and while in your program. Do not use Arrays or other advanced methods. Only use one main method. Do not use multiple methods. A sample session: Will calculate the coefficients for the expansion of (A+B) to the power of n. What are the coefficients of A and B? 2-1 What is the value of n? 5 The coefficients are: 32 -80 80 -40 10-1 Continue? Y What are the coefficients of A and B? 1 1 What is the value of n? 2 The coefficients are: 12 1 Continue? N Goodbye!Explanation / Answer
SolutionDemo1.java
import java.util.Scanner;//Scanner class for keyboard inputting
public class SolutionDemo1 {
// Main Method
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a, b, n;
String ch;
System.out.println(" Will calculate the coefficients for the expansion of (A+B) to the power of n.");
System.out.println("");
// Read a, b, n values from the user
// Loop till user wants to quit
do {
System.out.println("What are the coefficients of A and B? ");
a = input.nextInt();
b = input.nextInt();
System.out.println(" What is the value of n? ");
n = input.nextInt();
// Call this function to determines coefficients of binomials
input.nextLine();
int coefficient = 0;
System.out.print(" The Coefficients are: ");
// Calculating binomial coefficients by applying Binomial Theorem
for (int i = 0; i <= n; i++) {
int prod = 0;
// First calculate coefficient
// System.out.println("facti" + fact(i));
// System.out.println("factn-i" + fact(n - i));
coefficient = fact(n) / (fact(i) * fact(n - i));
// Second calculate product
prod = (int) (coefficient * Math.pow(a, n - i) * Math.pow(b, i));
// Print product
System.out.print(prod + " ");
}
System.out.println(" Continue? ");
ch = input.nextLine();
} while (ch.equals("Y"));//util ch equals to Y the loop continues
System.out.println(" Good Bye! ");
// this determines coefficients of binomials
}
// calculates the factorial of a number
public static int fact(int num) {
int fact = 1;
if (num > 0) {
for (int i = 1; i <= num; i++) {
fact = fact * i;
}
} else {
return 1;
}
return fact;
}
}
output
run:
Will calculate the coefficients for the expansion of (A+B) to the power of n.
What are the coefficients of A and B?
2 1
What is the value of n?
5
The Coefficients are: 32 80 80 40 10 1
Continue?
Y
What are the coefficients of A and B?
1 1
What is the value of n?
2
The Coefficients are: 1 2 1
Continue?
N
Good Bye!
BUILD SUCCESSFUL (total time: 26 seconds)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.