Hi I need help trying to figure out what I am doing wrong here. My assignment is to generate permutations and combinations of 4 people. However, when I run it and I ask the user to enter 4 names, it stops. Can someone help me figure out what is wrong? Or is there a better way to write it? Thanks
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
string names[4];
for (int i = 1; i <= 4; i++)
{
cout << "Enter the first name: ";
cin >> names[i];
for (int j = 2; j <= 4; j++)
{
cout << "Enter the second name: ";
cin >> names[j ];
for (int k = 3; k <= 4; k++)
{
cout << "Enter the third name: ";
cin >> names[k];
for (int l = 4; l <= 4; l++)
{
cout << "Enter the fourth name: ";
cin >> names[l];
}
}
}
}
// PRINTS ALL COMBINATIONs OF FOUR PEOPLE //
cout << "All Combinations including four people" << endl;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
for (int k = 0; k < 4; k++)
{
for (int l = 0; l < 4; l++)
{
cout << names[i] << " " << names[j] << " " << names[k] << " " << names[l] << " " << endl;
}
}
}
}
// PRINTS ALL COMBINATIONs OF TWO PEOPLE //
cout << "All Combinations including two people" << endl;
for (int i = 0; i<4; i++)
{
for (int j = 0; j<4; j++)
{
cout << names[i] << " " << names[j] << endl;
}
}
// PRINTS ALL COMBINATIONs OF THREE PEOPLE //
cout << "All Combinations including three people" << endl;
for (int i = 0; i<4; i++)
{
for (int j = 0; j<4; j++)
{
for (int k = 0; k<4; k++)
{
cout << names[i] << " " << names[j] << " " << names[k] << endl;
}
}
}
// PRINTS ALL PERMUTATIONS OF FOUR PEOPLE //
cout << "All Permutations including four people" << endl;
for (int i = 0; i<4; i++)
{
for (int j = 0; j<4; j++)
{
if (j == i)
continue;
for (int k = 0; k<4; k++)
{
if (k == j || k == i)
continue;
for (int l = 0; l<4; l++)
{
if (l == i || l == k || l == j)
continue;
else
cout << names[i] << " " << names[j] << " " << names[k] << " " << names[l] << " " << endl;
}
}
}
}
system("Pause");
return 0;
}
C++ arrays are accessed starting at index 0, not 1. So if there are 4 items in the array, you access them with indices 0,1,2,3, not 1,2,3,4. This is usually coded in a for loop as: for (i=0; i<4; ++i)
Learn it. Know it. Love it. Always think of the range from A through B as the range that includes A, and goes up to but not including B+1. This is the way the standard library always does it.
You only want to enter the first name once, so why do you prompt for it inside a loop that runs 4 times? The same point holds for entering the other names. Right now, your code attempts to prompt for the 4th name 256 times.