If and Else Statements

I'm taking an introductory class to C++ for this summer.
The Lab assignment was to make a program that prompts the user to enter their first, middle and last names; and outputs the names in alphabetical order.
But with my current code the output only gives me the middle name. Can I get some pointers please, I've been trying to debug this thing for a good 2 hours but I'm dull at this kind of stuff. Thank you in advance!

#include <iostream>
#include <string>

using namespace std;

int main()
{

string n1, n2, n3;

cout << "Enter your first name, middle name, and last name: ";

cin >> n1 >> n2 >> n3;

cout << "Your Name is alphabetical order is: ";

if (n1 <= n2 && n1 <= n3)
{cout << n1 << " ";}
else if (n2 <= n3)
{cout << n2 << " ";}
else (n3 <= n2)
{cout << n3 << " ";}

if (n2 <= n1 && n2 <= n3)
{cout << n2 << " ";}
else if (n1 <= n3)
{cout << n1 << " ";}
else (n3 <=n1)
{cout << n3 << " ";}

if (n3 <= n2 && n3 <= n1)
{cout << n3 << " ";}
else if (n2 <= n1)
{cout << n2 << " ";}
else (n1 <= n2)
{cout << n1 << " ";}

cout << endl;

return 0;

}
Well, let assume that n2 is the smallest string in lexicographical order. Then

in this group of if-else

if (n1 <= n2 && n1 <= n3)
{cout << n1 << " ";}
else if (n2 <= n3)
{cout << n2 << " ";}
else (n3 <= n2)
{cout << n3 << " ";}

will be executed the second else if

else if (n2 <= n3)
{cout << n2 << " ";}


Now let consider the next group of if-else

if (n2 <= n1 && n2 <= n3)
{cout << n2 << " ";}
else if (n1 <= n3)
{cout << n1 << " ";}
else (n3 <=n1)
{cout << n3 << " ";}

As the n2 is the smallest then it will be printed by the first if.

Now consider the third group of if-else

if (n3 <= n2 && n3 <= n1)
{cout << n3 << " ";}
else if (n2 <= n1)
{cout << n2 << " ";}
else (n1 <= n2)
{cout << n1 << " ";}

Here the second else if will be equal to true and again n2 will be printed. So you printed n2 thre times!:)
YOU should put else if instead of else
Topic archived. No new replies allowed.