I have to write a program that loops through pairs of integers n and k, where n runs from 1 to 10 inclusive, and, for each n, k runs from 0 to n inclusive. For each of these pairs of values, call a function that computes
n
k = (n!) / [k!(n−k)!]
and report the value (along with n and k) to the user.
I am really lost on how to do this, I just tried to put the bare bones into the program and work from there but I don't know what to do next.
#include <iostream>
#include <string>
#include <cmath>
usingnamespace std;
int main()
{
int n;
int k;
constexprdouble x = factorial(n) / factorial(k) * factorial(n-k);
for (n = 1; n <= 10; n++){
x =
}
cout << "The value of x is " << x << endl;
cout << "The value of n is " << n << endl;
cout << "The value of k is " << k << endl:
return 0;
}
I'm a bit confused on the math you are attempting to do, I don't see how "x" comes in. However, I have the looping worked out, I believe what you are looking for is:
#include <iostream>
#include <cmath>
#include <string>
usingnamespace std;
int n;
int k;
int main() {
for(n = 1; n <= 10; n++) {
// Compute k = (n!) / [k!(n−k)!]
for(k = 0; k <= n; k++) {
// Compute k = (n!) / [k!(n−k)!]
}
}
cout << "The value of n is " << n << endl;
cout << "The value of k is " << k << endl;
}
Input the math you're trying to do and you should be set, unless I misunderstand what you're trying to do. As a rule though, you should avoid nested for loops, as sometimes they might require the use of "goto" to get out of. While using goto is fine, it's really only an every once and a while thing, it really complicates debugging. I think Handy Andy has a point with his do/while loop, that would probably be better.