Question

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.

Basic Logic for main()

Note: all of the functions mentioned in this logic are described below.

Declare the two arrays of float/doubles and two integer variables to hold the number of values that have been placed into each array. If any other variables are needed, those should also be declared.

Use srand to set the seed value for the random number generator. The program that is handed should use 18 as the seed value but any value can be used as the program is being developed.

Fill the first array by calling the buildFromFile() function. The buildFromFile() function returns the number of values that it read. This returned value should be put into one of the integers that was created to hold the number of values that have been placed into an array.

Fill the second array by calling the buildRandom() function. The buildRandom() function returns the number of values that it put into the array. This returned value should be put into the other integer that was created to hold the number of values that have been placed into an array.

Display the number of values placed into the first array with a meaningful label.

Display the number of values placed into the second array with a meaningful label.

Display the contents of the first array by calling the print() function with a title similar to "Array of numbers from a file".

Display the contents of the second array by calling the print() function with a title similar to "Array of random numbers".

Sort the first array by calling the sort() function.

Sort the second array by calling the sort() function.

Display the contents of the first array (again) by calling the print() function with a title similar to "Sorted array of numbers from a file".

Display the contents of the second array (again) by calling the print() function with a title similar to "Sorted array of random numbers".

Functions to write and use

Write and use the following 5 functions in the program.

int buildFromFile( double array[] )

This function will fill an array of doubles.

It takes as its argument an array of doubles: the array that will hold the numeric information. It returns an integer that is equal to the number of values that were placed in the array.

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 as a subscript, a double that will be used to hold a value that is read from the file, and an input file stream that will be used to read values from the input file.

Initialize the subscript variable to the beginning of the array.

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 value should be saved in the double variable that was declared earlier.

Inside of a loop that will execute as long as there is information in the file, the double number should be put into the array at the subscript position, the subscript should be incremented by 1, and another value should be read from the file.

Once the loop is finished executing, the file should be closed and the number of values that were placed in the array should be returned.

Note: see the "Using an Input File in a CPP program" section below.

double randDouble()

This function will generate a random double value that is within a specific range. It takes no arguments and returns a double: the random number.

The rand function that has been used in previous assignments generates a random integer value. This function will still use that value but it will be used in a formula that changes the value to a double. The formula is:

lower bound + ( random integer / (maximum possible random number / (upper bound - lower bound)))

See the Symbolic Constants section for the "lower bound," "upper bound," and "maximum possible random number" values.

int buildRandom( double array[] )

This function will fill an array of doubles with a random number of random values.

It takes as its argument an array of doubles: the array that will hold the numeric information and returns an integer: the number of values that were placed in the array.

The function should start by generating a random integer value that represents the number of values to place into the array. This value should be between 30 and 50. Use the following formula to generate a value within a specific range:

minimum_value + (random integer % (maximum_value - minimum_value + 1))

Once the number of values has been determined, write a loop that will execute that number of times. Inside of the loop, call the randDouble function that was previously described to get a random double value and then put the value that is returned from the function into the array argument.

After the values have been placed into the array, return the number of values that were placed in the array (the random integer from earlier).

void print( string title, double array[], int numberOfValues )

This function will display the numeric information in an array of doubles, ten values per line.

It takes three arguments: the first argument is a string that hold the title for the information that is being displayed, the second argument is an array of doubles that holds the numbers to be displayed, and the third argument is an integer that holds the number of values to be displayed. It returns nothing.

This function should display the string argument and then execute a loop that executes numberOfValues number of times. Within the loop, determine if ten values have been displayed. If ten values have been displayed, cout a newline character. After that display a number from the array.

The values should be displayed with exactly 1 digit after the decimal point.

void sort( double array[], int numberOfValues )

This function will use the selection sort algorithm that was presented in lecture to sort the array in ASCENDING order.

This function takes two arguments: the first argument is an array of doubles that holds the numbers to be sorted, and the second argument is an integer that holds the number of values to be sorted.

The function returns nothing.

Symbolic Constants

This program requires the use of 6 symbolic constants. One of the constants is pre-defined and the remaining 5 must be defined at the top of the CPP file.

Pre-defined constant

RAND_MAX is a symbolic constant that holds the maximum possible random number that is available on the system that is executing the program. At a minimum, the value will be 32767. Make sure to add #include <cstdlib> to the top of the program to use this constant. DO NOT declare this constant in the program.

Constants that need to be created/defined

The first constant is a double that represents the lower bound of the double values that will be placed into the array of doubles by the buildRandom function. The value should be 1. (Note: make sure to use the value 1.0 if using #define)

The second constant is a double that represents the upper bound of the double values that will be placed into the array of doubles by the buildRandom function. The value should be 250. (Note: make sure to use the value 250.0 if using #define)

The third constant is an integer that represents the minimum number of values that the array of random doubles can hold. The value should be 30.

The fourth constant is an integer that represents the maximum number of values that the arrays can hold. The value should be 50.

The fifth constant is an integer that represents the maximum number of values to display per line of output. The value should be 10.

Using an Input File in a CPP program

The file with the input data can be downloaded and saved. It is called nums.txt and can be found here:

http://faculty.cs.niu.edu/~byrnes/csci240/pgms/nums.txt

The file consists of a set of numbers, one per line. The file resembles the following:

1.23
4.56
7.89
1.4
2.58
3.69
9.5

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 buildFromFile() 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( "nums.txt" );      //open the file for reading

The open statement will open a file named nums.txt. The file must be located in the same directory as the CPP file. (For Mac users, you will probably have to put in the set of double quotes(""), 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 computer, between the quotes.)

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 << "nums.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:

double num;

cout << "Enter a number number (-99.99 to quit): ";
cin >> num;

It should now be:

double num;

infile >> num;

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 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 arrays should be able to hold 50 elements. Use a symbolic constant to represent the maximum size of an array.

  4. The array has the capability to hold 50 elements, however, that does not mean that all 50 spots will be used. This is the reason that the number of elements in the array is being passed to the sort and print functions. This value is the return value from the two build... functions.

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

Output

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

Windows PC using srand(18);

Number of values in the file: 29
Number of random values: 43

Array of numbers from a file

    1.2    4.6    7.9    1.4    2.6    3.7    9.5   52.3   16.0   14.7
   -1.2   -9.0   41.8   36.4    6.5   87.5   -1.1   25.1  100.0    7.5
   -6.5   88.2  100.0  123.5    6.5   91.2   -7.2  486.2    8.1

Array of random numbers

   35.8  115.8   73.9  234.1  129.7  241.3   94.9   97.9  139.7   25.2
  220.6   49.8   25.3  204.5    3.5    2.1  230.9   25.2   93.3  227.8
  119.8  227.3  161.3  146.7   29.7  147.0   30.6  196.7   46.5  181.1
  157.6  169.9  174.1   64.6  230.2  212.6  225.2  224.0  246.3  112.0
  128.3  141.5   96.4

Sorted array of numbers from a file

   -9.0   -7.2   -6.5   -1.2   -1.1    1.2    1.4    2.6    3.7    4.6
    6.5    6.5    7.5    7.9    8.1    9.5   14.7   16.0   25.1   36.4
   41.8   52.3   87.5   88.2   91.2  100.0  100.0  123.5  486.2

Sorted array of random numbers

    2.1    3.5   25.2   25.2   25.3   29.7   30.6   35.8   46.5   49.8
   64.6   73.9   93.3   94.9   96.4   97.9  112.0  115.8  119.8  128.3
  129.7  139.7  141.5  146.7  147.0  157.6  161.3  169.9  174.1  181.1
  196.7  204.5  212.6  220.6  224.0  225.2  227.3  227.8  230.2  230.9
  234.1  241.3  246.3
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Screenshot

Quick Launch (Ctrl+Q) DoubleArrayInCpp - Microsoft Visual Studio Team Window File Edit View Project Build Debug Tools Test AnProgram

/*
Program to fill 2 double arrays
One for file data
Other for random data
Sort arrays
Print arrays
*/
#include <iostream>
#include<fstream>
#include<string>
#include<iomanip>
#include<cstdlib>
using namespace std;
//Symbolic constants
#define MAX_SIZE 50
#define LOWERBOUND 1.0
#define UPPERBOUND 250.0
#define MIN 30
#define MAX 50
#define PERLINE 10
//Function prototypes
int buildFromFile(double array[]);
double randDouble();
int buildRandom(double array[]);
void print(string title, double array[], int numberOfValues);
void sort(double array[], int numberOfValues);
int main()
{
   //Set seed
   srand(18);
   //Declare arrays
   double fileArray[MAX_SIZE];
   double randArray[MAX_SIZE];
   //Variable for size of arrays
   int sz1, sz2;
   //Call function to read file data
   sz1 = buildFromFile(fileArray);
   //Call function to fill random array
   sz2 = buildRandom(randArray);
   //Display size values
   cout << "Number of values in the file: " << sz1 << endl;
   cout << "Number of random values : " << sz2 << endl;
   //Print both arrays
   print("Array of numbers from a file", fileArray, sz1);
   print("Array of random numbers",randArray, sz2);
   //Sort arrays
   sort(fileArray, sz1);
   sort(randArray, sz2);
   //Print both arrays
   print("Sorted array of numbers from a file", fileArray, sz1);
   print("Sorted array of random numbers", randArray, sz2);
}
/*
Function: buildFromFile
ParamIn: array, to store data from file
ParamOut: number of elemnts in array
Description: It takes as its argument an array of doubles:
               the array that will hold the numeric information.
               It returns an integer that is equal to the number of values
               that were placed in the array.
*/
int buildFromFile(double array[]) {
   //Subscript of array variable
   int i=0;
   //Variable to read file data
   double num;
   //File read object
   ifstream in("nums.txt");
   //File open error check
   if (!in) {
       cout << "File not found!!!" << endl;
       exit(0);
   }
   //Read file data
   while (in>>num) {
       array[i] = num;
       i++;
   }
   return i;
}
/*
Function: randDouble
ParamIn: None
ParamOut: double random number
Description: This function will generate a random double value
               that is within a specific range
*/
double randDouble() {
   return LOWERBOUND + ((double)rand() / (RAND_MAX/ (UPPERBOUND -LOWERBOUND)));
}
/*
Function: buildRandom
ParamIn: array, to store random data
ParamOut: number of elements in array
Description: It takes as its argument an array of doubles:
               the array that will hold the random numeric information.
               It returns an integer that is equal to the number of values
               that were placed in the array.
*/
int buildRandom(double array[]) {
   //Generate random integer for number of elemnts in array
   int cnt = MIN + (rand() % (MAX - MIN + 1));
   //Loop to fill array
   for (int i = 0; i < cnt; i++) {
       array[i] = randDouble();
   }
   return cnt;
}
/*
Function: print
ParamIn: array, contains double values
           numberOfValues, elements count
           title, display header
ParamOut: None
Description: Display the numeric information in an array of doubles,
                ten values per line
*/
void print(string title, double array[], int numberOfValues) {
   cout << fixed << setprecision(1);
   cout << "\n" << title << endl<< endl;
   for (int i = 0; i < numberOfValues; i++) {
       if (i % 10 == 0 && i != 0) {
           cout << "\n" << array[i] << " ";
       }
       else {
           cout << array[i] << " ";
       }
   }
   cout << endl;
}
/*
Function: sort
ParamIn: array, contains double values
           numberOfValues, elements count
ParamOut: None
Description: sort array in ascending order
*/
void sort(double array[], int numberOfValues) {
   int index;
   for (int i = 0; i < numberOfValues - 1; i++)
   {
       index = i;
       for (int j = i + 1; j < numberOfValues; j++) {
           if (array[j] < array[index]) {
               index = j;
           }  
       }
       double temp = array[index];
       array[index] = array[i];
       array[i] = temp;
   }
}

------------------------------------------------------

Output

Number of values in the file: 29
Number of random values : 43

Array of numbers from a file

1.2 4.6 7.9 1.4 2.6 3.7 9.5 52.3 16.0 14.7
-1.3 -9.0 41.8 36.4 6.5 87.5 -1.1 25.1 100.0 7.5
-6.5 88.2 100.0 123.5 6.5 91.3 -7.2 486.2 8.1

Array of random numbers

35.8 115.8 73.9 234.1 129.7 241.3 94.9 97.9 139.7 25.2
220.6 49.8 25.3 204.5 3.5 2.1 230.9 25.2 93.3 227.8
119.8 227.3 161.3 146.7 29.7 147.0 30.6 196.7 46.5 181.1
157.6 169.9 174.1 64.6 230.2 212.6 225.2 224.0 246.3 112.0
128.3 141.5 96.4

Sorted array of numbers from a file

-9.0 -7.2 -6.5 -1.3 -1.1 1.2 1.4 2.6 3.7 4.6
6.5 6.5 7.5 7.9 8.1 9.5 14.7 16.0 25.1 36.4
41.8 52.3 87.5 88.2 91.3 100.0 100.0 123.5 486.2

Sorted array of random numbers

2.1 3.5 25.2 25.2 25.3 29.7 30.6 35.8 46.5 49.8
64.6 73.9 93.3 94.9 96.4 97.9 112.0 115.8 119.8 128.3
129.7 139.7 141.5 146.7 147.0 157.6 161.3 169.9 174.1 181.1
196.7 204.5 212.6 220.6 224.0 225.2 227.3 227.8 230.2 230.9
234.1 241.3 246.3

Add a comment
Know the answer?
Add Answer to:
For this c++ assignment, Overview write a program that will process two sets of numeric information....
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
  • 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...

  • 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...

  • Program in C++! Thank you in advance! Write a menu based program implementing the following functions: (1) Write a funct...

    Program in C++! Thank you in advance! Write a menu based program implementing the following functions: (1) Write a function that prompts the user for the name of a file to output as a text file that will hold a two dimensional array of the long double data type. Have the user specify the number of rows and the number of columns for the two dimensional array. Have the user enter the values for each row and column element in...

  • Write a menu based program implementing the following functions: (0) Write a function called displayMenu that...

    Write a menu based program implementing the following functions: (0) Write a function called displayMenu that does not take any parameters, but returns an integer representing your user's menu choice. Your program's main function should only comprise of the following: a do/while loop with the displayMenu function call inside the loop body switch/case, or if/else if/ ... for handling the calls of the functions based on the menu choice selected in displayMenu. the do/while loop should always continue as long...

  • C++ programming please Write a program that will display random numbers in order from low to...

    C++ programming please Write a program that will display random numbers in order from low to high. 1. Declare an integer array of size 100. Ask the user how many numbers to work with (n). It can be less than 100. 2. Generate random numbers from 10 to 50. 3. Write the random numbers to an output file named random.dat. Close the file. 4. Open random.dat for input and read the data values into your array. Pass your array to...

  • #include <stdio.h> // Define other functions here to process the filled array: average, max, min, sort,...

    #include <stdio.h> // Define other functions here to process the filled array: average, max, min, sort, search // Define computeAvg here // Define findMax here // Define findMin here // Define selectionSort here ( copy from zyBooks 11.6.1 ) // Define binarySearch here int main(void) { // Declare variables FILE* inFile = NULL; // File pointer int singleNum; // Data value read from file int valuesRead; // Number of data values read in by fscanf int counter=0; // Counter of...

  • 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...

  • 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...

  • C programing Write a program to sort numbers in either descending or ascending order. The program...

    C programing Write a program to sort numbers in either descending or ascending order. The program should ask the user to enter positive integer numbers one at a time(hiting the enter key after each one) The last number entered by the user should be -1, to indicate no further numbers will be entered. Store the numbers in an array, and then ask the user how to sort the numbers (either descending or ascending). Call a function void sortnumbers ( int...

  • Write a program that compares the execution speed of two different sorting algorithms: bubble sort and...

    Write a program that compares the execution speed of two different sorting algorithms: bubble sort and selection sort. It should do this via functions you must write with the following prototypes: void setRandomValues(int[], int[], int length); This function sets two integer arrays with identical random values. The first two arguments are two integer arrays of the same length, and the third argument is the length of those arrays. The function then sets each element in the first and second argument...

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