Originally posted by joe shmo
Does anyone know a general code that can be used to print combinations using basic programming loops? I'm completely stuck on this.
Given user parameters of n and r, I would like a simple code to explicitly print out C(n,r) in 1's and 0's perhaps using For, Do, While Loops ( or other rudimentery language structures) etc...
I don't know whether this counts as "simple" with you, but the most convenient and IME easiest way to do this is using recursion, not simple loops.
The easiest way to implement it is probably to add a helper function which takes a prefix. Your main function then calls this with an empty prefix and lets it do all the work. (You can do without this, but then all calling code has to pass the empty prefix.) E.g.:
printcombhelper(n, r, "" )
printcombhelper(n, r, prefix)
If n=0 then print prefix: return
If r>0 then printcombhelper(n-1, r-1, prefix+"1" )
If r<n then printcombhelper(n-1, r, prefix+"0" )
(Apologies if that doesn't indent properly.)
It's possible to do that using only loops and hand-managed stacks, but all you'd be doing is emulate recursion anyway, and that the hard way.