//Amari Mosley CSC5 Chapter 6, P. 373, #15
//
/*****************************************************************
*
* Population Calculation
* _______________________________________________________________
* This program displays the size of a population for any number
* of years, based on a starting size, birth rate, and death rate.
*
* Computation is based on the formula:
* N = P + (B * P) - (D * P)
* where N = new population, P = previous population,
* B = birth rate, D = death rate
* _______________________________________________________________
* INPUT
* startSize : starting population size
* birthRate : annual birth rate as a percentage
* deathRate : annual death rate as a percentage
* years : number of years to display
*
* OUTPUT
* The population size for each year
*
*****************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototype
double calcPopulation(double prevPop, double birthRate, double deathRate);
int main()
{
double startSize; // starting population size
double birthRate; // annual birth rate
double deathRate; // annual death rate
int years; // number of years to display
double population; // population size for the current year
// Get starting size with input validation
cout << "Enter the starting size of the population: ";
cin >> startSize;
while (startSize < 2)
{
cout << "Starting size must be at least 2. Please re-enter: ";
cin >> startSize;
}
// Get birth rate with input validation
cout << "Enter the annual birth rate (as a percentage): ";
cin >> birthRate;
while (birthRate < 0)
{
cout << "Birth rate cannot be negative. Please re-enter: ";
cin >> birthRate;
}
// Get death rate with input validation
cout << "Enter the annual death rate (as a percentage): ";
cin >> deathRate;
while (deathRate < 0)
{
cout << "Death rate cannot be negative. Please re-enter: ";
cin >> deathRate;
}
// Get number of years with input validation
cout << "Enter the number of years to display: ";
cin >> years;
while (years < 1)
{
cout << "Number of years must be at least 1. Please re-enter: ";
cin >> years;
}
// Convert percentages to decimals
birthRate = birthRate / 100;
deathRate = deathRate / 100;
// Display the population for each year
cout << fixed << setprecision(2);
cout << "\nYear\tPopulation" << endl;
cout << "-----------------------" << endl;
population = startSize;
for (int year = 1; year <= years; year++)
{
population = calcPopulation(population, birthRate, deathRate);
cout << year << "\t" << population << endl;
}
return 0;
}
// calcPopulation
// Receives the previous population size, birth rate, and death
// rate (as decimals) and returns the new population size.
// Formula: N = P + BP - DP
double calcPopulation(double prevPop, double birthRate, double deathRate)
{
return prevPop + (birthRate * prevPop) - (deathRate * prevPop);
}