1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream> #include <iomanip> // For std::fixed and std::setprecision // Function to simulate population growth void simulatePopulationGrowth(double initialPopulation, double growthRate, int years) { double population = initialPopulation; std::cout << "Year\tPopulation" << std::endl; for (int year = 0; year <= years; ++year) { std::cout << year << "\t" << std::fixed << std::setprecision(2) << population << std::endl; population *= (1 + growthRate); } } int main() { double initialPopulation; double growthRate; int years; // Input initial population, growth rate, and number of years std::cout << "Enter the initial population: "; std::cin >> initialPopulation; std::cout << "Enter the growth rate (as a decimal, e.g., 0.05 for 5%): "; std::cin >> growthRate; std::cout << "Enter the number of years: "; std::cin >> years; // Call the simulation function simulatePopulationGrowth(initialPopulation, growthRate, years); return 0; } |
Explanation:
- Headers and Function Declaration:
- Includes
iostream
for input and output operations andiomanip
for formatting the output. - Declares the
simulatePopulationGrowth
function which handles the simulation of population growth.
- Includes
- simulatePopulationGrowth Function:
- Takes three parameters:
initialPopulation
(starting population),growthRate
(rate of population increase), andyears
(number of years to simulate). - Initializes the
population
variable withinitialPopulation
. - Prints the header for the year and population.
- Uses a loop to iterate over the number of years, updating the population each year based on the growth rate, and printing the year and updated population.
- Takes three parameters:
- main Function:
- Prompts the user to input the initial population, growth rate, and number of years.
- Calls the
simulatePopulationGrowth
function with the provided inputs to display the population growth over time.