In: Computer Science
Write a program that will ask the user for three words (strings). Re-arranges them in ascending order by using a function (it should return void). Global variables are forbidden. Hint: You don't need to exchange the values among variables. You can just print them in the correct order. (C++ Please)
Example of Output:
Word 1: apple Word 2: orange Word 3: strawberry -------- orange apple strawberry |
Program:
#include <iostream>
using namespace std;
void orderingWords(string word1, string word2, string word3) {
// Ascending order of words by comparing given three words
if (word1 <= word2 && word2 <= word3)
{
// Printing the ascending order of words
cout << "Word1: " << word1 << endl;
cout << "Word2: " << word2 << endl;
cout << "Word3: " << word3 << endl;
}
else if (word1 <= word3 && word3 <= word2)
{
cout << "Word1: " << word1 << endl;
cout << "Word2: " << word3 << endl;
cout << "Word3: " << word2 << endl;
}
else if (word2 <= word1 && word1 <= word3)
{
cout << "Word1: " << word2 << endl;
cout << "Word2: " << word1 << endl;
cout << "Word3: " << word3 << endl;
}
else if (word2 <= word3 && word3 <= word1)
{
cout << "Word1: " << word2 << endl;
cout << "Word2: " << word3 << endl;
cout << "Word3: " << word1 << endl;
}
else if (word3 <= word1 && word1 <= word2)
{
cout << "Word1: " << word3 << endl;
cout << "Word2: " << word1 << endl;
cout << "Word3: " << word2 << endl;
}
else if (word3 <= word2 && word2 <= word1)
{
cout << "Word1: " << word3 << endl;
cout << "Word2: " << word2 << endl;
cout << "Word3: " << word1 << endl;
}
}
int main()
{
string word1, word2, word3;
// Taking input for three words
cout<<"Enter 3 words : ";
cin >> word1 >> word2 >> word3;
// Calling method for ordering words in ascending order
orderingWords(word1, word2, word3);
return 0;
}
Output: