In: Computer Science
Your textbook mentions that relational operators can be used to compare letters and words, thanks to ASCII. This simple program will ask the user to enter two letters and then two words to see if we can really "sort" these entries alphabetically with relational operators.
Prompts:
This is a Letter and Word sorting program
Enter two different letters separated by a space: [assume user
inputs: b a]
Enter two different words separated by a space: [assume user inputs: bob alex]
Output:
a goes before b
alex goes before bob
Notes and Hints:
1) Do NOT convert the user's entry to uppercase. Some of the test cases will be comparing lowercase to uppercase letters (the results are interesting!)
2) Don't worry about the possibility of the user entering the same letters/words or entering something else. Keep this program simple.
// VARIABLES
// INITIAL INPUT
cout << "This is a Letter and Word sorting program" <<
endl;
cout << "Enter two different letters separated by a space:
";
cout <<endl; // For Mimir
cout << "Enter two different words separated by a space:
";
cout << endl; // For Mimir
//Processing// LETTER ANALYSIS
// The < means letter1 is alphabetically before letter2
cout << letter1 << " goes before " << letter2
<<endl;
cout << letter2 << " goes before " << letter1
<< endl;
// WORD ANALYSIS
// The < means word1 is alphabetically before word2
cout << word1 << " goes before " << word2
<< endl;
cout << word2 << " goes before " << word1
<< endl;
Please find your solution below and do upvote if any doubt or need change comment.
CODE:
#include <iostream>
using namespace std;
int main()
{
// VARIABLES
char letter1,letter2;
string word1,word2;
// INITIAL INPUT
cout<<"This is a Letter and Word sorting program"<<endl;
cout<<"Enter two different letters separated by a space:";
cin>>letter1>>letter2;
cout <<endl; // For Mimir
cout<<"Enter two different words separated by a space:";
cin>>word1>>word2;
cout << endl; // For Mimir
//Processing// LETTER ANALYSIS
// The < means letter1 is alphabetically before letter2
if(letter1<letter2)
{
cout << letter1 << " goes before " << letter2 <<endl;
}
else
{
cout << letter2 << " goes before " << letter1 << endl;
}
// WORD ANALYSIS
// The < means word1 is alphabetically before word2
if(word1<word2)
{
cout << word1 << " goes before " << word2 << endl;
}
else
{
cout << word2 << " goes before " << word1 << endl;
}
return 0;
}
OUTPUT: