Question

Program 7 File Processing and Arrays (100 points) Overview: For this assignment, write a program that...

Program 7
File Processing and Arrays
(100 points)

Overview: For this assignment, write a program that will process monthly sales data for a small company. The data will be used to calculate total sales for each month in a year. The monthly sales totals will be needed for later processing, so it will be stored in an array.

Basic Logic for main()
Note:
all of the functions mentioned in this logic are described below.
Declare an array of 12 float/doubles and any other variables that are needed.
Initialize the array so that it contains a value of 0.0 in all twelve of its elements.
Fill the array by calling the buildSalesArray() function.
Display the contents of the array by calling the printSalesArray() function.
Call the findSalesTotal() function to find the total sales amount for the year. Display the result that is returned from the function with an identifying label and exactly two digits after the decimal point.
Call the findAverageSales() function to find the average sales amount for the twelve months of the year. Display the result that is returned from the function with an identifying label and exactly two digits after the decimal point.
Call the findHighMonth() function to find the subscript of the month with the highest amount of sales. Display the NAME of the month with the highest amount of sales.
Call the findLowMonth() function to find the subscript of the month with the lowest amount of sales. Display the NAME of the month with the lowest amount of sales.

Input:
Unlike the previous assignments, the input data for this program will be read from a file rather than having the user input the information or using the random number generator.
[Numbers]

5  923.45
10 155.89
2  1000.00
1  345.88
5  3005.00
6  222.22
5  4578.40
7  875.55
8  3435.66
5  4579.77
7  345.11
9  122.54
2  3473.44
2  2345.21
5  997.55
3  7564.49
1  7483.54
2  444.44
5  212.66
6  8884.50
7  975.36
8  6758.50
8  2223.49
8  543.48
6  244.79
12 1000.00
12 237.99
11 4567.51
1  485.66
8  3444.32
5  189.62
5  1222.44
7  2144.66
6  323.55
8  764.92
9  2111.88
10 2311.44
4  273.46
2  121.44
4  5786.99
3  2333.55

The file consists of an unknown number of records, each representing a single sale. Each record consists of a month number (integer) followed by a sale amount (double/float). The first few records in the file look like this:
5 923.45
10 155.89
2 1000.00
1 345.88
5 3005.00
The month number is an integer from 1 - 12. There can be multiple records in the input file with the same month number (representing multiple sales made during that month).

Functions to write and use:
Write and use the following 6 functions in the program.
void buildSalesArray(double salesArray[])
This function will fill an array of doubles.
It takes as its argument an array of doubles: the array that will hold the sales total for each month of the year. It returns nothing.
The function should start by declaring any variables that are needed. At a minimum, there should be three variables: an integer that will be used to hold the month number that is read from the input file, a double that will be used to hold the sales amount that is read from the file, and an input file stream that will be used to read values from the input file.
Connect the input file stream variable and the input file by executing the open() command. Check to make sure that the file opened correctly. If it did not open correctly, display a message about the file not opening and exit the program.
Read a value from the file. This will be the month number from the first record in the file. This value should be saved in the integer variable that was declared earlier.
Inside of a loop that will execute as long as there is information in the file, a value should be read from the file and saved in the double variable that was declared earlier. This will be the sales amount that is paired with the month number that was previously read. The double value should be ADDED to the value that is currently in the array for the specific month number. Finally, read another value from the file. This value will be the month number from the next record in the file and it should be saved in the integer variable.
Once the loop is finished executing, the file should be closed.
Note: see the "Using an Input File in a CPP program" section below.
void printSalesArray( double salesArray[] )
This function will display the contents of the sales array and the name of each month that is associated with the values in the array. It takes one argument: an array of doubles that holds the sales totals for each month of the year. It returns nothing.
The function should start by displaying a title similar to "Sales Totals by Month" and then use a loop that will execute exactly 12 times (once for each month saved in the array of double). Inside of the loop, display a month name and a value from the array of doubles.
double findSalesTotal(double salesArray[])
This function will calculate the total sales for the year.
It takes as its argument an array of doubles: the array that holds the sales totals for each month of the year. It returns a double: the total sales for the year.
The function should use a loop that will execute exactly 12 times (once for each month saved in the array of double). Inside of the loop, add a value from the array of doubles to a sum.
After the values in the array have been added to the sum, return the sum.
double findAverageSales(double salesArray[])
This function will calculate the average of the monthly sales totals for the year.
It takes as its argument an array of doubles: the array that holds the sales totals for each month of the year. It returns a double: the average of the sales for the year.
This function should call the findSalesTotal() to get the yearly sales total and then divide that value by 12. The resulting quotient is the average of the monthly sales totals and should be returned.
int findHighMonth(double salesArray[])
This function will find the subscript of the month with the highest sales total for the year.
It takes as its argument an array of doubles: the array that holds the sales totals for each month of the year. It returns an integer: the subscript of the month with the highest sales total.
int findLowMonth(double salesArray[])
This function will find the subscript of the month with the lowest sales total for the year.
It takes as its argument an array of doubles: the array that holds the sales totals for each month of the year. It returns an integer: the subscript of the month with the lowest sales total.

Symbolic Constant:
This program requires the use of 1 symbolic constant that should be defined at the top of the CPP file.
The constant is an integer that represents the number of months in the year. The value should be 12. This value should be used to create the array in main() and in the various functions that use loops that execute exactly 12 times.

Using an Input File in a CPP program:
Using a file in a program requires that a couple of extra include statements are added to the top of the code. Add #include <fstream> and #include <cstdlib>.
In the buildSalesArray() function, create an input file stream variable and "connect" it with the text file. The "connection" is created by opening the file:

ifstream infile;        //input file stream variable
                        //this will be used instead of cin

infile.open( "sales7.txt" );      //open the file for reading

The open statement will open a file named sales7.txt.

Windows Users: The sales7.txt file MUST be located in the same directory as the CPP file.

Mac Users: there are two options available to handle the input file.

  • Option 1: put in the set of double quotes ("") between the parenthesis for the open command, find where the file has been saved on your Mac, and then drag and drop the file in between the quotes. It should place the name of the file, including the complete path of where it is located on your Mac, between the quotes. If you use this option, before handing in the CPP file, remove the path name from the file name so that it only has sales7.txt between the double quotes.

  • Option 2: Build the Program one time. In the Project Navigator (it's on the left side of the screen on my version of XCode), there should be two folders: one with the name of the project and another with the name Products. Click on the Products folder. There should be a file with the name of the project. Click on the file in the Products folder. In the File Inspector (it's on the right side of the screen on my version of XCode), there should be a "Full Path" label that is followed by the complete path where the executable for the project will be saved. Open this path in Finder by clicking on the small arrow after the path name. Put the sales7.txt file in the location that opens in Finder. If you use this option, the open statement can be used as shown above.

Once the file has been opened, make sure that it opened correctly. This is an important step because a file cannot be processed if it doesn't exist or open correctly. To test if the file opened correctly:

if( infile.fail() )       //if the input file failed to open
  {
  cout << "sales7.txt input file did not open" << endl;
  exit(-1)                //stop execution of the program immediately
  }

In the previous programs, cin has been used to get data from standard input (the keyboard). Since this program is reading input from a file rather than standard input, substitute the name of the input file stream (infile in the example above) in place of cin. The cout statements that display a prompt for the user are not needed with the data being read from a file.

So if a program had something like:

int monthNum;

cout << "Enter a month number: ";
cin >> monthNum;

It should now be:

int monthNum;

infile >> monthNum;

The same type of pattern can be used for reading a double (or any data type) from a file as well.

When writing a read loop using data from a file, the loop should test to see if there is data in the file. One way to do this is to use the input file stream variable as a boolean variable:

while( infile )

As long as there is information in the file, the input file stream variable will remain valid (or true). Once the end of the data has been reached, the stream will become invalid (or false). Note: this test is only successful AFTER an attempt has been made to read data from the file. This means that a standard read loop pattern with a priming and secondary read should be followed.

Finally, once all the data has been read from the file, the file should be closed. To do this, execute the following:

infile.close();

Programming Notes:

  1. Add #include <fstream> and #include <cstdlib> at the top of the program.

  2. Copy the input file and write the program so that it reads the data from the current directory (ie. don't specify a file path). Make sure to put the data file in the same directory as the source code (.cpp) file. For those using a Mac, make sure to remove the path name before handing in the source code file.

  3. The array should be able to hold 12 elements. Use the symbolic constant to represent the maximum size of an array.

  4. Hand in a copy of the source code using Blackboard.

Programming Suggestion:

const string MONTH_NAMES[NUM_MONTHS] = { "January", "February", "March",
             "April", "May", "June", "July", "August", "September",
             "October", "November", "December" };
  1. It might be useful to create an array with the 12 month names. Assuming that a symbolc constant named NUM_MONTHS has been created and assigned the value 12:

Output:

The output that is produced with the sales7.txt input file:

Sales Totals by Month

January           8315.08
February          7384.53
March             9898.04
April             6060.45
May              15708.89
June              9675.06
July              4340.68
August           17170.37
September         2234.42
October           2467.33
November          4567.51
December          1237.99

Total Sales for the Year:              89060.35
Average Monthly Sales for the Year:     7421.70

Month with the BEST sales: August
Month with the WORST sales: December

Extra Credit:
For up to 5 points of extra credit, modify the printSalesArray, findSalesTotal, findAverageSales, findHighMonth, and findLowMonth functions so that they have the ability to process a subset of months rather than always processing a full year.
For each of the functions, add two integer arguments. The first argument is the first month to process. The second argument is the last month to process. For example, if the user wants to process the information from February through October, the values 2 and 10 should be passed to the modified functions. If the user wants to process the information for the full year, the value 1 and 12 should be passed to the modified functions. It can be assumed that the first month is earlier in the year than the last month.
The original version of the printSalesArray function displays a title before displaying the monthly sales data. The modified version should have a fourth argument. This argument should be a string that will be used to hold the title that should be displayed.
After the modifications have been made to the functions, update main() so that it uses the new versions of the functions. The output should be exactly the same as the original version.
Finally, add code to main() that will print the sales totals, average sales, month with the highest sales, and month with the lowest sales for May through August.
Note about extra credit: the points will ONLY be awarded if the required portions of the assignment work correctly. In other words, don't take short cuts in the rest of the program because it is assumed that 5 extra points will be awarded.

Extra Credit Output:
Sales Totals by Month January 8315.08 February 7384.53 March 9898.04 April 6060.45 May 15708.89 June 9675.06 July 4340.68 August 17170.37 September 2234.42 October 2467.33 November 4567.51 December 1237.99 Total Sales for the Year: 89060.35 Average Monthly Sales for the Year: 7421.70 Month with the BEST sales: August Month with the WORST sales: December *** Extra Credit Output *** Sales Totals for May through August May 15708.89 June 9675.06 July 4340.68 August 17170.37 Total Sales for May through August 46895.00 Average Monthly Sales for May through August 11723.75 Month with the BEST sales: August Month with the WORST sales: July

0 0
Add a comment Improve this question Transcribed image text
Answer #1

C++ Code:

#include<iostream>
#include<bits/stdc++.h> //GETTING ALL FUNCTIONS
#include<fstream>
using namespace std;
//Here array is building
void buildSalesArray(double salary[]){
  
   int month = 0;
   double thisSalary;
   ifstream fp;//Ifstream opens the file in read mode
   fp.open("abc.txt");
   if(fp==NULL){//Checking if the file exist
       cout<<"Error";
       return ;
   }
   else{
       while(!fp.eof()){//Getting input untill last character
       fp >> month;//taking integer
       fp >> thisSalary;//taking salary
       salary[month-1]+=thisSalary;//As array start with 0 and month start with 1
       }
   }
   fp.close();//closing file pointer
}
void printSalesArray(double salary[],char monthName[12][20]){
   int i=0;
   for(i=0;i<12;i++){
       cout<<monthName[i]<<" "<<salary[i]<<endl;//Printing salary monthName holds all months according to the index
   }
}
void findAverageSales(double total){
   cout<<(total/12.0); //printing average
}
void findSalesTotal(double salary[]){
   int i=0;
   double total=0.0;
   for(i=0;i<12;i++){
       total+=salary[i];
   }
   setprecision(2);
   cout<<endl<<"Total Sales for this year : ";
   cout<<total<<endl;//printing total salary
   cout<<endl<<"Average Sales for this year :";
   findAverageSales(total);
   cout<<endl;
}
void findHighMonth(double salary[],char monthName[12][20]){
   int i=0;
   int maximumsalary=0;
   for(i=1;i<12;i++){//finding maximum logic
       if(salary[i]>salary[maximumsalary])
           maximumsalary=i;
   }
   cout<<"Month with the best sales: "<<monthName[maximumsalary];
}
void findLowMonth(double salary[],char monthName[12][20]){
   int i=0;
   int minimumsalary=0;
   for(i=1;i<12;i++){//finding minimum logic
       if(salary[i]<salary[minimumsalary])
           minimumsalary=i;
   }
   cout<<endl<<"Month with the Worst sales: "<<monthName[minimumsalary];
}
int main(){
   //month name
   char monthName[12][20]={"January","February","March","April","May","June","July","August","September","october","November","December"};
   double salary[12]={0.0};//array initialisation
   buildSalesArray(salary);
   //printing all data
   printSalesArray(salary,monthName);
   findSalesTotal(salary);
   findHighMonth(salary,monthName);
   findLowMonth(salary,monthName);
   return 0;
}

OUTPUT:

January 8315.08 February 7384.53 March 9898.94 April 6060.45 May 15708.9 June 9675.06 July 4340.68 August 17170.4 September 2

PLEASE LIKE IF YOU LIKE AND DO COMMENT IF YOU ARE HAVING ANY DOUBT RELATED TO THIS SOLUTION

Add a comment
Know the answer?
Add Answer to:
Program 7 File Processing and Arrays (100 points) Overview: For this assignment, write a program that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • For this c++ assignment, Overview write a program that will process two sets of numeric information....

    For this c++ assignment, Overview write a program that will process two sets of numeric information. The information will be needed for later processing, so it will be stored in two arrays that will be displayed, sorted, and displayed (again). One set of numeric information will be read from a file while the other will be randomly generated. The arrays that will be used in the assignment should be declared to hold a maximum of 50 double or float elements....

  • Program 7 Arrays: building and sorting (100 points) Due: Friday, October 30 by 11:59 PM Overview...

    Program 7 Arrays: building and sorting (100 points) Due: Friday, October 30 by 11:59 PM Overview For this assignment, write a program that will calculate the quiz average for a student in the CSCI 240 course. The student's quiz information will be needed for later processing, so it will be stored in an array. For the assignment, declare one array that will hold a maximum of 12 integer elements (ie. the quiz scores). It is recommended that this program be...

  • The name of the C++ file must be search.cpp Write a program that will read data...

    The name of the C++ file must be search.cpp Write a program that will read data from a file. The program will allow the user to specify the filename. Use a loop that will check if the file is opened correctly, otherwise display an error message and allow the user to re-enter a filename until successful. Read the values from the file and store into an integer array. The program should then prompt the user for an integer which will...

  • Write a program that will take input from a file of numbers of type double and...

    Write a program that will take input from a file of numbers of type double and output the average of the numbers in the file to the screen. Output the file name and average. Allow the user to process multiple files in one run. Part A use an array to hold the values read from the file modify your average function so that it receives an array as input parameter, averages values in an array and returns the average Part...

  • Use two files for this lab: your C program file, and a separate text file containing...

    Use two files for this lab: your C program file, and a separate text file containing the integer data values to process. Use a while loop to read one data value each time until all values in the file have been read, and you should design your program so that your while loop can handle a file of any size. You may assume that there are no more than 50 data values in the file. Save each value read from...

  • Use c++ as programming language. The file needs to be created ourselves (ARRAYS) Write a program...

    Use c++ as programming language. The file needs to be created ourselves (ARRAYS) Write a program that contains the following functions: 1. A function to read integer values into a one-dimensional array of size N. 2. A function to sort a one-dimensional array of size N of integers in descending order. 3. A function to find and output the average of the values in a one dimensional array of size N of integers. 4. A function to output a one-dimensional...

  • Stuck on this computer science assignment Write a program that demonstrates binary searching through an array...

    Stuck on this computer science assignment Write a program that demonstrates binary searching through an array of strings and finding specific values in an corresponding parallel double array. In all cases your output should exactly match the provided solution.o. Provided files: Assignment.cpp - starter assignment with function prototypes companies.txt - file for program to read. earnings.txt - file for program to read. Input1.txt Input2.txt - Test these inputs out manually, or use stream redirection Input3.txt - These inputs are based...

  • Programming Assignment 1 Structures, arrays of structures, functions, header files, multiple code files Program description: Read...

    Programming Assignment 1 Structures, arrays of structures, functions, header files, multiple code files Program description: Read and process a file containing customer purchase data for books. The books available for purchase will be read from a separate data file. Process the customer sales and produce a report of the sales and the remaining book inventory. You are to read a data file (customerList.txt, provided) containing customer book purchasing data. Create a structure to contain the information. The structure will contain...

  • Write a complete C++ program that defines the following class: Class Salesperson { public: Salesperson( );...

    Write a complete C++ program that defines the following class: Class Salesperson { public: Salesperson( ); // constructor ~Salesperson( ); // destructor Salesperson(double q1, double q2, double q3, double q4); // constructor void getsales( ); // Function to get 4 sales figures from user void setsales( int quarter, double sales); // Function to set 1 of 4 quarterly sales // figure. This function will be called // from function getsales ( ) every time a // user enters a sales...

  • c++ program8. Array/File Functions Write a function named arrayToFile. The function should accept three arguments:...

    c++ program8. Array/File Functions Write a function named arrayToFile. The function should accept three arguments: the name of a file, a pointer to an int array, and the size of the array. The function should open the specified file in binary mode, write the contents of the array to the file, and then close the file. Write another function named fileToArray. This function should accept three argu- ments: the name of a file, a pointer to an int array, and the size...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT