In: Computer Science
Write a C++ program that asks for the name and age of three people. The program should then print out the name and age of each person on a separate line from youngest to oldest.
Hint: Start with a program that just asks for the names and ages then prints them out in the same order they are entered. Then modify the program so it prints out the list of names in every possible order. Note that one of these will be the correct result. Then add conditions to each set of results so that only one set of results is true.
For example; part of my program will print:
name2
name1
name3
Therefore the condition for this output would be: (age2
< age1) && (age2 < age3) && (age1 <
age3)
You can assume that all three ages will be different but consider what your program would do if two or more ages were the same. (If your program is written correctly - it should not matter)
Use if, else if and else statements in order to minimize the total number of comparisons. (See Rubric for how you will be graded on use of conditionals)
HINT: Plan out you approach ahead of time. Use pseudocode or flow chart if that helps.
Example Output:
Peter 2 Paul 20 Mary 54
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#include<iostream>
using namespace std;
int main(){
//declaring needed variables
string name1,name2,name3, tempStr;
int age1, age2, age3, tempInt;
//prompting and reading names and ages
cout<<"Enter name and age of first person: ";
cin>>name1>>age1;
cout<<"Enter name and age of second person: ";
cin>>name2>>age2;
cout<<"Enter name and age of third person: ";
cin>>name3>>age3;
//we are now arranging names and ages, so that age1 <= age2 <= age3
//if age1>age3, swapping age1 & age3, also name1 and name3
if(age1>age3){
//swapping age1 & age3 using a temporary variable
tempInt=age1;
age1=age3;
age3=tempInt;
//swapping name1 and name3 using a temporary variable
tempStr=name1;
name1=name3;
name3=tempStr;
}
//if age1>age2, swapping age1 & age2, also name1 and name2
if(age1>age2){
tempInt=age1;
age1=age2;
age2=tempInt;
tempStr=name1;
name1=name2;
name2=tempStr;
}
//now if age2>age3, swapping age2 & age3, also name2 and name3
if(age2>age3){
tempInt=age2;
age2=age3;
age3=tempInt;
tempStr=name2;
name2=name3;
name3=tempStr;
}
//now the elements must be in sorted order of ages, simply displaying names and ages
cout<<name1<<" "<<age1<<endl;
cout<<name2<<" "<<age2<<endl;
cout<<name3<<" "<<age3<<endl;
return 0;
}
/*OUTPUT*/
Enter name and age of first person: Oliver 23
Enter name and age of second person: John 29
Enter name and age of third person: Barry 17
Barry 17
Oliver 23
John 29