Hello...
I'm learning C++ from "Programming - Principles and Practice using C++", 2nd edition.
In chapter 3, an exercise wants me to:
Write a program that prompts the user to enter three integer values,
and then outputs the values in numerical sequence separated by commas.
So, if the user enters the values 10 4 6, the output should be 4, 6, 10.
If two values are the same, they should just be ordered together.
So, the input 4 5 4 should give 4, 4, 5.
Is the following solution optimal, or can it be written in a more simple way?
Code:
#include "std_lib_facilities.h"
int main()
{
cout << "Enter three integers, separated by space: ";
int a, b, c, temp1 = 0, temp2 = 0;
cin >> a >> b >> c;
while (a > b || b > c) {
temp1 = c;
temp2 = b;
c = a;
b = temp1;
a = temp2;
}
cout << a << ", " << b << ", " << c << "\n";
return 0;
}
UPDATE: My first solution has a bug, so here's the corrected solution,
written using only features I have learned in the first three chapters:
Code:
#include "std_lib_facilities.h"
int main()
{
cout << "Enter three words, separated by space: ";
string a, b, c, temp;
cin >> a >> b >> c;
if (a > b) {
temp = a;
a = b;
b = temp;
}
if (b > c) {
temp = b;
b = c;
c = temp;
}
if (a > b) {
temp = a;
a = b;
b = temp;
}
cout << a << ", " << b << ", " << c << "\n";
return 0;
}