This program takes 2 numbers from user input, asks them whether they’d like to find out the permutations or combinations, and then outputs the result. Here’s the code.
#include "std_lib_facilities.h"
int permutation(int first, int second)
{
int top_fac;
int bottom_fac;
for (int i = first-1; i >= 1; --i)
top_fac *=i;
for (int i2 = (first-second)-1; i2>=1; --i2)
bottom_fac *= i2;
return (top_fac/bottom_fac);
}
int combination(int first, int second)
{
int bottom_fac;
for (int i = second-1; i>=1; --i)
bottom_fac *= i;
return permutation(first, second)/(bottom_fac);
}
int main()
{
cout << "Enter two numbers.\n";
int first = 0;
int second = 0;
cin >> first >> second;
cout << "Now choose permutation(p) or combination(c).\n";
string choice;
cin >> choice;
if (choice == "p")
cout << "Number of permutations: " << permutation(first,second) << endl;
else if (choice == "c")
cout << "Number of combinations: " << combination(first,second) << endl;
else
cout << "p or c stupid.\n";
keep_window_open("q");
}
When I try to run the program, and I choose p or c, I get a “permutations_combinations.exe has stopped working” message. I tried to catch an error, but nothing is coming up. Any ideas?
Thanks in advance.
You’re not initializing the local variables
top_facandbottom_facinside of your functions. Unlike other languages, local variables are NOT initialized to anything in particular in C or C++. The values that they receive are whatever garbage happens to be on the stack when you call the function. You should explicitly initializetop_facandbottom_facto 1 at the beginning of thepermutation()andcombination()functions.I’m guessing that
bottom_facis accidentally getting initialized to 0, and then you’re dividing by 0 at the end of the function, which is causing the runtime failure you’re seeing.