C++
Goals:Practicing arrays
Create a program that will read whole numbers from a file called Labs4-7Mu.dat (posted on Canvas)and store it into an array. The number of values in the file is less than 300 and all the values are whole numbers. The actual number of values stored in the file should be determined.
Your program should then prompt the user to enter another whole number between 2 and 20 (you may assume the user enters a valid value) and write a loop that will determine how many of the numbers in the array are evenly divisible by the entered value. This loop should not contain more than 3 arithmetic operators (++ and += count as arithmetic operators, but = does not). A message similar to
35 of the 189 values in the file were evenly divisible by 19.
with the underlined values replaced by your calculated values and the user’s input
Do not use any concepts beyond Chapter 7 of your textbook(e.g. pointers).Remember to write introductory comments for the entire program. If you decided to use functions,your code should contain comments for each function other than main that states the purpose of the function, input to the function (both input from the function call and interactive input), output from the function (both information sent back to the function call and interactive output), and processing performed in the function. Follow the Assignment Guidelines posted on Canvas.
/* C++ program to read whole numbers from input file into an
array and
determine the count of numbers that are evenly divisible by the
number entered by the user */
#include <iostream>
#include <fstream>
// function declaration
int readFile(int numbers[]);
using namespace std;
int main()
{
int numbers[300]; // create an array of maximum size 300
int n, divisor, freq;
// read file data into array and return the count of numbers
read
n = readFile(numbers);
// input a whole number between 2 and 20
cout<<"Enter a whole number between 2 and 20: ";
cin>>divisor;
freq = 0; // initialize freq to 0
// loop over the array counting the whole numbers that are
evenly divisible by divisor
for(int i=0;i<n;i++)
{
if(numbers[i]%divisor == 0) // ith number is evenly divisible by
divisor, increment freq by 1
freq++;
}
// display the number of whole numbers in array that are
divisible by divisor
cout<<freq<<" of the "<<n<<" values in the
file were evenly divisible by "<<divisor<<".\n";
return 0;
}
/*
* Function that reads whole numbers from input file into the
array
* and return the count of numbers read from file.
*/
int readFile(int numbers[])
{
int n = 0;
ifstream fin;
// open the input file
fin.open("Labs4-7Mu.dat");
// loop till the end of file reading whole numbers into the
array
while(!fin.eof())
{
fin>>numbers[n];
n++; // increment n
}
fin.close(); // close the file
return n;
}
//end of program
Output:
Input file:
Output:
Get Answers For Free
Most questions answered within 1 hours.