Answer: The c++ program is given below.
#include <iostream>
using namespace std;
int main() {
float townA, townB, growthA, growthB, populationA, populationB;
int year=0;
cout<<"Enter present population of town A : ";
cin >> townA;
cout<<endl<<"Enter present growth rate of town A : ";
cin >> growthA;
growthA = growthA/100;
cout<<endl<<"Enter present population of town B : ";
cin >> townB;
cout<<endl<<"Enter present growth rate of town B : ";
cin >> growthB;
growthB = growthB/100;
do
{
populationA = townA + (townA * growthA);
populationB = townB + (townB * growthB);
townA = populationA;
townB = populationB;
year++;
}while(populationA < populationB);
cout<<endl<<"After " <<year<< " years, population of town A is "<<populationA << " and population of town B is "<< population<<endl;
return 0;
}
Explanation:
All the variables for population and growth rate are declared with float datatype.
The user inputs the present population of both the towns.
The growth rate entered by the user is the percentage growth.
For example, town A has 10% growth rate as shown in the output image.
The program converts 10% into float as 10/100.
growthA = growthA/100;
growthB = growthB/100;
The above conversion is done to ease the calculations.
The year variable is declared as integer and initialized to 0.
The growth in population is computed in a do-while loop. After each growth is calculated, the year variable is incremented by 1.
The loop continues until population of town A becomes greater than or equal to population of town B as mentioned in the question.
Once the loop discontinues, the final populations of town A and town B and the years needed for this growth is displayed.
The new line is introduced using endl keyword.
The function main has return type int hence, 0 is returned at the end of the program.