Question

In C++. Define a class Country that stores the name of the country, its population, and...

In C++. Define a class Country that stores the name of the country, its population, and its area. Store the country name as a C-string. Write a main function that initializes an array with at least 5 objects of this class and sorts and prints this array in three different ways:

  • By population
  • By population density (people per square kilometer)

Do not ask the user to enter country data. Use qsort to sort the array.

  • Also sort alphabetically by country name, ignoring the case (upper-case or lower-case)

Also: Separately program for below;

a) Add to the class Country a method saveInFile, which gets a file object as an explicit argument and saves the Country object used as an implicit argument at the end of the corresponding file.

b) Add to the class Country a class-level method readFromFile, which will take a file object and an integer position as explicit arguments and will return a Country object with data read from the Country stored at position position in the corresponding file.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PROGRAM CODE (1)

#include <iostream>
#include <string.h>
using namespace std;

// Country class

class Country {
  
   public:
  
       // All required attributes  
      
       char *name;
       double population;
       double area;
};

// A comparator function to sort countries in ascending order according to their names

int name(const void *a, const void *b) {
  
   Country *l = (Country*)a;
   Country *r = (Country*)b;
  
   return strcmp(l->name, r->name);
}

// A comparator function to sort countries in ascending order according to their population

int pop(const void *a, const void *b) {
  
   double l = ((Country*)a)->population;
   double r = ((Country*)b)->population;
  
   return l-r;
}

// A comparator function to sort countries in ascending order according to their area

int area(const void *a, const void *b) {
  
   double l = ((Country*)a)->area;
   double r = ((Country*)b)->area;
  
   return l-r;
}

// A function to print countries

void print(Country countries[], int size) {
  
   cout << "Name\tPopulation\tArea" << endl;
  
   for(int i=0; i<size; i++) {
      
       cout << countries[i].name << "\t" << countries[i].population << " billion \t" << countries[i].area << endl;
   }
   cout << endl;
}

int main() {
  
   // Initialzing an array of 5 Country objects
  
   Country countries[] = {{"China", 13.1, 630000}, {"US", 20.0, 700000}, {"UK", 11.1, 500000},
   {"India", 18, 880000}, {"Russia", 15, 700000}};
  
   // Printing all information in 3 different ways
  
   // First of all sorting by names using qsort
   qsort((void*)countries, 5, sizeof(countries[0]), name);
  
   cout << "*** Countries according to their Names(Sorted) ***\n" << endl;
   print(countries, 5);   // Printing by calling print function
  
   // First of all sorting by population using qsort  
   qsort((void*)countries, 5, sizeof(countries[0]), pop);
  
   cout << "*** Countries according to their Population(Sorted) ***\n" << endl;
   print(countries, 5);   // Printing by calling print function
  
  
   // First of all sorting by area using qsort
   qsort((void*)countries, 5, sizeof(countries[0]), area);
  
   cout << "*** Countries according to their Area(Sorted) ***\n" << endl;
   print(countries, 5);   // Printing by calling print function
  
   return 0;
}

SAMPLE OUTPUT1

dede Name Area C:\Users\Dell OneDrive\Desktop\CPP July 2020\Country.exe *** Countries according to their Names (Sorted) Popul

SEPARATE PROGRAM CODE FOR PART a and b

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

// Country class

class Country {
  
   public:
  
       // All required attributes  
      
       char *name;
       double population;
       double area;
      
       // Adding All Required methods
      
       void saveInFile(ofstream &w) {
          
           // Saving that country object in that file
          
           w << this->name << " " << this->population << " " << this->area << endl;
       }
      
       Country readFromFile(ifstream &r, int position){
          
           Country c;
          
           // Reading from file until that position comes
          
           int count = 0;
          
           while(true) {
              
               count ++;
              
               char* name;
               double p, a;
              
               r >> name >> p >> a;

// Reading until that position in the file
                          
               if(position == count) {
                  
                   c.name = name;
                   c.population = p;
                   c.area = a;
                   break;
               }
                     
           }
          
           // Finally return that object
          
           return c;
       }
};

int main() {
  
   // A Test program to check both functions
  
   Country c1; c1.name = "US"; c1.population = 10; c1.area = 100000;
   Country c2; c2.name = "India"; c2.population = 20; c2.area = 150000;
   Country c3; c3.name = "Australia"; c3.population = 25; c3.area = 200000;
  
   // Saving all objects in file countries.txt
  
   ofstream w("countries.txt", ios::app);
//  
//   c1.saveInFile(w);
//   c2.saveInFile(w);
//   c3.saveInFile(w);
  
   w.close();
  
   // Now reading object at 2nd position in file countries.txt
  
   ifstream r("countries.txt");
  
   Country c = c1.readFromFile(r, 2);
  
   cout << "The country at position 2" << endl;
  
   cout << "Name: " << c.name << endl
   << "Population: " << c.population << endl
   << "Area: " << c.area << endl;  
   return 0;
}

countries.txt

countries.txt - Notepad File Edit Format View Help JUS 10 100000 India 20 150000 Australia 25 200000

SAMPLE OUTPUT2

C:\Users\Dell OneDrive\Desktop\CPP July 2020 Country.exe The country at position 2 Name: India Population: 20 Area: 150000 Pr

-----------------------------------------------------------------------------------------------------------

COMMENT DOWN FOR ANY QUESTIONS...........
HIT A THUMBS UP IF YOU DO LIKE IT!!!

Add a comment
Know the answer?
Add Answer to:
In C++. Define a class Country that stores the name of the country, its population, and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In C++ Define a class Country that stores the name of the country, its population, and...

    In C++ Define a class Country that stores the name of the country, its population, and its area. Store the country name as a C-string. Write a main function that initializes an array with at least 5 objects of this class and sorts and prints this array in three different ways: By population By population density (people per square kilometer) Do not ask the user to enter country data. Use qsort to sort the array. Also sort alphabetically by country...

  • The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements...

    The file Sorting.java contains the Sorting class from Listing 9.9 in the text. This class implements both the selection sort and the insertion sort algorithms for sorting any array of Comparable objects in ascending order. In this exercise, you will use the Sorting class to sort several different types of objects. 1. The file Numbers.java reads in an array of integers, invokes the selection sort algorithm to sort them, and then prints the sorted array. Save Sorting.java and Numbers.java to...

  • In Java, Implement a class MyArray as defined below, to store an array of integers (int)....

    In Java, Implement a class MyArray as defined below, to store an array of integers (int). Many of its methods will be implemented using the principle of recursion. Users can create an object by default, in which case, the array should contain enough space to store 10 integer values. Obviously, the user can specify the size of the array s/he requires. Users may choose the third way of creating an object of type MyArray by making a copy of another...

  • A. Create a class called StudentRecord that has the following private variables: year, GPA Implem...

    In Java a. Create a class called StudentRecord that has the following private variables: year, GPA Implement 2 constructors: default constructor (doesn't take any parameters, has b. an empty body) and a constructor, that initializes all variables. according to the following template: Implement Comparable interface, so that StudentRecord class has ĢompareTo c. Implement a toString() method that returns text representation of an object First name: Benoit, last name: Mandelbrot, year: 3, GPA: 3.68 d. method, that performs comparison as the...

  • PLEASE DO IN JAVA 1) Create interface named “Person” which exposes getter/setter methods for the person’s...

    PLEASE DO IN JAVA 1) Create interface named “Person” which exposes getter/setter methods for the person’s name and college ID: 1. getName 2. setName 3. getID 4. setID. The college ID is represented as “int”. Define two classes, Student and Faculty, which implement Person. Add field GPA to Student and department to faculty. Make them private and create corresponding getters (getGPA, getDepartment) and setters (setGPA, setDepartment). Use appropriate types. 2) Write a class College, which contains the name of the...

  • Please help with a source code for C++ and also need screenshot of output: Step 1:...

    Please help with a source code for C++ and also need screenshot of output: Step 1: Create a Glasses class using a separate header file and implementation file. Add the following attributes. Color (string data type) Prescription (float data type) Create a default constructor that sets default attributes. Color should be set to unknown because it is not given. Prescription should be set to 0.0 because it is not given. Create a parameterized constructor that sets the attributes to the...

  • Create a class “Person” which includes first name, last name, age, gender, salary, and haveKids (Boolean)...

    Create a class “Person” which includes first name, last name, age, gender, salary, and haveKids (Boolean) variables. You have to create constructors and properties for the class. Create a “MatchingDemo” class. In the main function, the program reads the number of people in the database from a “PersonInfo.txt” file and creates a dynamic array of the object. It also reads the peoples information from “PersonInfo.txt” file and saves them into the array. In C# Give the user the ability to...

  • Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Ini...

    Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Initialize the object properties def __init__(self, id, name, mark): # TODO # Print the object as an string def __str__(self): return ' - {}, {}, {}'.format(self.id, self.name, self.mark) # Check if the mark of the input student is greater than the student object # The output is either True or False def is_greater_than(self, another_student): # TODO # Sort the student_list # The output is the sorted...

  • The class’s needed are: - A Donor class that has class attributes of a donor’s name,...

    The class’s needed are: - A Donor class that has class attributes of a donor’s name, hometown, and a charitable point scale (this is a number between 0 and 4). This is a normal regular object that you should know how to create by now. - A Charity class that has class attributes of a charity name, its acronym, an arraylist or array of Donor’s, and probably a Decimal Formatter. Depending on how you write your code, you may need...

  • Class River describes river’s name and its length in miles. It provides accessor methods (getters) for...

    Class River describes river’s name and its length in miles. It provides accessor methods (getters) for both variables and toString() method that returns String representation of the river. Class CTRivers describes collection of CT rivers. It has no data, and it provides the following service methods. None of the methods prints anything, except method printListRec, which prints all rivers. // Prints all rivers recursively. Print them is same order as they were in the list . List can be empy...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT