I’m studying the code below in my textbook. It uses the combinations method and the factorial method to calculate the possible outcomes given n and k. My question is with the factorial method specifically the content in the for loop.
I understand everything else about the program but I don’t understand the code i <=n in the for loop in the factorial method. What other part of the program is n referred to? I’m just not sure about the rationale behind i <= n or how the programmer comes up with that.
import acm.program.*;
public class combinations extends ConsoleProgram {
public void run(){
int n = readInt("Enter the number of objects in the set (n): ");
int k = readInt("Enter the number to be chosen (k): ");
println("C (" + n + ", " + k + ") = " + combinations (n, k) );
}
private int combinations (int n, int k){
return factorial (n) / (factorial (k) * factorial (n-k));
}
private int factorial (int n){
int result = 1;
for (int i = 1; i <= n; i++){
result *= i;
}
return result;
}
}
nis a parameter of the method: because the method is declared asint factorial(int n), you invoke it as (for example)factorial(5)to get the local variablenset to5. (In formal terms,nis the parameter and5is the argument, though usually people don’t bother to distinguish those two terms.)