The midyear population of the United States, in thousands, during the years 1950
ID: 3666198 • Letter: T
Question
The midyear population of the United States, in thousands, during the years 1950 through 1990, appear at the end of this question. The first line contains the population for 1950, the second line contains the population for 1951, and so forth. Create an application in C# that reads the midyear population contents (from a .txt file) into an array or a List. The application should display the following data:
• The average annual change in population during the time period
• The year with the greatest increase in population during the time period
• The year with the least increase in population during the time period
MIDYEAR POPULATION
151868
153982
156393
158956
161884
165069
168088
171187
174149
177135
179979
182992
185771
188483
191141
193526
195576
197457
199399
201385
203984
206827
209284
211357
213342
215465
217563
219760
222095
224567
227225
229466
231664
233792
235825
237924
240133
242289
244499
246819
249623
Explanation / Answer
Please find below your program that will do the needull. It is simple and easy to understand,as i have added the comments. Good luck !!
def main():
#setup variables
yearly_change = []
change=0.0
total_change=0
average_change=0
greatest_increase=0
smallest_increase=0
greatest_year=0
smallest_year=0
BASE_YEAR=1950
try:
#open the file for reading
input_file = open("USPopulation.txt", "r")
#read all the lines in the in file into a list
yearly_population= input_file.readlines()
#turn all read lines into a number
for i in range(len(yearly_population)):
yearly_population[i] = float(yearly_population[i])
#calculate the change in population size for each two years
for i in range(1,len(yearly_population)): // You may use xrange,for a BIG file//
change = yearly_population[i] - yearly_population[i-1]
yearly_change.append(change)
#if this is the first year, set trackers to its value
if i==1:
greatest_increase = change
smallest_increase = change
greatest_year = 1
smallest_year = 1
#this is not the first change in population size
#update the trackers if relevent
else:
if change>greatest_increase:
greatest_increase = change
greatest_year = i
elif change<smallest_increase:
smallest_increase = change
smallest_year = i
total_change = float(sum(yearly_change))
average_change = total_change/40
print("The average annual change in population during the time period is",
format(average_change, '.2f'))
print("The year with the greatest increase in population was",
BASE_YEAR+greatest_year)
print("The year with the least increase in population was",
BASE_YEAR+smallest_year)
input_file.close()
except IOError:
print("The file could not be found")
except IndexError:
print("There was an indexing error")
except:
print("An error occurred")
main()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.