### Looping through pair of integers

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.

 ``123456789101112131415161718192021`` ``````#include #include #include using namespace std; int main() { int n; int k; constexpr double 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; }``````
Hello shimshim96,

First I would write the function "factorial" that is passe a number an woul return the result.

I would not define "x" as a "constexpr" because you might want to use it again.

I believe the formula to figure the value of "x" is wrong, mostly the part for the divisor. I believe it is missing a call to "factorial".

In place of the for loop I am thinking of a do/while loop, so that you could use the program more than once.

I will need to work on the program a bit to see what else I can find.

Hope that helps,

Andy

P.S. The subject talks about a pair of integers, but I only see you using one.
Last edited on
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:

 ``123456789101112131415161718192021`` ``````#include #include #include using namespace 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.
Last edited on
Topic archived. No new replies allowed.