Write a program that displays the name of each month in a year and its rainfall amount, sorted in order of rainfall from highest to lowest. The program should use an array of objects, where each object holds the name of a month and its rainfall amount.

 

Use a constructor to set the month names and the rainfall amount. Make the program modular by using different functions

  1. to input the rainfall amounts
  2. to sort the data, and
  3. to display the data.

 

Solution

 

#include <iostream>

using namespace std;

 

class Rainfall {

private:

string month;

int amount;

public:

Rainfall(string m, int a)

{

month = m;

amount = a;

}

 

Rainfall()

{

 

}

 

void setMonth(string m) { month = m; }

string getMonth() { return month; }

 

void setAmount(int a) { amount = a; }

int getAmount() { return amount; }

};

 

void sortData(Rainfall[]);

void displayData(Rainfall[]);

Rainfall obs[12];

Rainfall tmp;

 

int main()

{

//input the data

Rainfall obs[12] = { Rainfall(“January”,35),

Rainfall(“February”,42),

Rainfall(“March”,33),

Rainfall(“April”,24),

Rainfall(“May”,26),

Rainfall(“June”,11),

Rainfall(“July”,7),

Rainfall(“August”,15),

Rainfall(“September”,29),

Rainfall(“October”,27),

Rainfall(“November”,31),

Rainfall(“December”,34)};

 

//sort the data

sortData(obs);

 

//diplay the data

displayData(obs);

 

return 0;

}

 

 

//function to sort data

void sortData(Rainfall obs[]){

for (int i = 0; i < 12; i++) {

int minIndex = i;

for (int j = i + 1; j < 12; j++)

if (obs[j].getAmount() > obs[minIndex].getAmount())

minIndex = j;

if (minIndex != i) {

tmp = obs[i];

obs[i] = obs[minIndex];

obs[minIndex] = tmp;

}

}

}

 

//function to display data

void displayData(Rainfall obs[]){

for(int i=0; i < 12; i++)

cout << obs[i].getMonth() << “, the amount of rainfall: ” << obs[i].getAmount() << “\n”;

}