C++ , Thank you so much!! Sorting Youngest to Oldest Implement a class Person wi
ID: 3687377 • Letter: C
Question
C++ , Thank you so much!!
Sorting Youngest to Oldest
Implement a class Person with the following data members:
name (string) - name of this person
age (integer) – age of this person
Write a program that reads in a list of names and ages and stores them in a one-dimensional array of Person objects. The maximum number of names that will be entered is 100 names. After reading in the list of names and ages, sort the list of people from the youngest (lowest age) to oldest (highest age) using the Bubble Sort. Then print out the name and age for each person in the sorted list.
Sample Output (user input is bold) :
Enter name (-1 to stop): Bart
Enter age of Bart: 10
Enter name (-1 to stop): Lisa
Enter age of Lisa: 8
Enter name (-1 to stop): Maggie
Enter age of Maggie: 1
Enter name (-1 to stop): Homer
Enter age of Homer: 36
Enter name (-1 to stop): Marge
Enter age of Marge: 34
Enter name (-1 to stop): -1
Name: Maggie, age: 1
Name: Lisa, age: 8
Name: Bart, age: 10
Name: Marge, age: 34
Name: Homer, age: 3
Explanation / Answer
/*
* File: main.cpp
* Author: ramesh
*
* Created on April 8, 2016, 1:47 AM
*/
#include <iostream>
using namespace std;
// define person class
class Person
{
// define class variable
private:
int i;
string temp2;
int j,temp;
// define class method
public:
void int_data(string name[100], int age[100]){
// this code use for Bubble Sort in C++ start here
for(i=1;i<100;++i)
{
for(j=0;j<(100-i);++j)
if(age[j]>age[j+1])
{
temp=age[j];
temp2=name[j];
age[j]=age[j+1];
name[j]=name[j+1];
age[j+1]=temp;
name[j+1]=temp2;
}
}
// this code use for Bubble Sort in C++ end here
// this loop use for print final array value. code start here
for(i=0;i<100;++i){
// check if value exit and not
if(age[i]){
cout << "Name: " << name[i];
cout << ", age: " << age[i] << " ";
}
}
// end loop here
}
// end class method here
};
int main(){
// define name and age array here
string name[100] ;
int age[100] ;
int i;
// this loop use for get user input data
for(i=0; i<100; i++)
{
cout << "Enter name (-1 to stop):" << endl;
cin >> name[i];
// check user want stop. if user enter -1 then stop
if(name[i] != "-1"){
cout << "Enter age of " << name[i] << " : " << endl;
cin >> age[i];
}else{
break;
}
}
// create class object here
Person obj1;
// call call method here and pass array. if you want user input code also in method then cute input code and add in method
obj1.int_data(name, age);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.