Write a program in C that uses nested loops to read data fro

Write a program in C++ that uses nested loops to read data from a file and calculate the average rainfall per year and the overall average for all 5 years. The outer loop will iterate once per year, the inner loop will iterate 12 times for each month.

See rain.txt for input data

Output:

The Average rainfall for Year 2012 was: x.x

The Average rainfall for Year 2013 was: x.x

The Average rainfall for Year 2014 was: x.x

The Average rainfall for Year 2015 was: x.x

The Average rainfall for Year 2016 was: x.x

The average over the last 5 years was: x.x

rain.txt

2012 0.2 0.5 1.4 2.0 2.5 0.02 0.01 0.7 0.9 3.0 1.2 2.7
2013 0.25 1.5 2.4 3.0 4.5 5.02 1.01 1.7 1.9 2.0 2.2 4.7
2014 1.6 2.5 1.0 1.0 2.1 0.25 2.8 5.2 1.3 3.3 1.0 2.3
2015 2.2 0.75 2.7 2.4 1.6 4.9 0.50 0.9 0.8 0.6 3.8 1.0
2016 3.2 1.4 1.7 1.0 2.5 1.2 1.3 1.7 1.9 3.0 1.2 1.7

Solution

// C++ code

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <stdlib.h>   
#include <math.h>
#include <string.h>
#include <algorithm>
#include <iomanip> // std::setprecision

using namespace std;

int main()
{
int year;
double avg = 0.0;
double avgrainfall;
int countyear = 0;
double rain;

// open file
ifstream inputFile (\"rain.txt\");

if (inputFile.is_open())
{
while ( true )
{
avgrainfall = 0.0;

inputFile >> year;
countyear++;

for (int i = 0; i < 12; ++i)
{
inputFile >> rain;
avgrainfall = avgrainfall + rain;
avg = avg + rain;

}

avgrainfall = avgrainfall/12;
cout << \"The Average rainfall for Year \" << year << \" was: \" << setprecision(3) <<avgrainfall << endl;

if(inputFile.eof())
break;
}
inputFile.close();
}

else cout << \"Unable to open file\";

avg = avg/(countyear*12);
cout << \"The average over the last \" << countyear << \" years was: \" << setprecision(3) <<avg << endl;
}

/*
rain.txt
2012 0.2 0.5 1.4 2.0 2.5 0.02 0.01 0.7 0.9 3.0 1.2 2.7
2013 0.25 1.5 2.4 3.0 4.5 5.02 1.01 1.7 1.9 2.0 2.2 4.7
2014 1.6 2.5 1.0 1.0 2.1 0.25 2.8 5.2 1.3 3.3 1.0 2.3
2015 2.2 0.75 2.7 2.4 1.6 4.9 0.50 0.9 0.8 0.6 3.8 1.0
2016 3.2 1.4 1.7 1.0 2.5 1.2 1.3 1.7 1.9 3.0 1.2 1.7


output:
The Average rainfall for Year 2012 was: 1.26
The Average rainfall for Year 2013 was: 2.52
The Average rainfall for Year 2014 was: 2.03
The Average rainfall for Year 2015 was: 1.85
The Average rainfall for Year 2016 was: 1.82
The average over the last 5 years was: 1.89

*/

Write a program in C++ that uses nested loops to read data from a file and calculate the average rainfall per year and the overall average for all 5 years. The
Write a program in C++ that uses nested loops to read data from a file and calculate the average rainfall per year and the overall average for all 5 years. The

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site