Example 8-6: How would you slove these questions in c++ language, using visual s
ID: 3805768 • Letter: E
Question
Example 8-6:How would you slove these questions in c++ language, using visual studios?
1. Write a function to read into an array all the integers in an input file of unknown size. When the function ends, the calling program has the array filled with values and a variable whose value is the actual number of elements read in. 2. write a function to output all the integers in an array to an output file, with 10 values per line. Values on a line are separated by a single space. 3. Write a function similar to the function indexLargestElement (page 535 in Example 8 6) except that this function is called indexSmallestElement and it returns the index of the minimum value found in an array. 4. Write a complete C++ program which includes both functions l. and 2. above, as well as indexLargestElement and indexSmallestElement. The main program will declare variables and call functions to get array input, find and output to a file the maximum value in the array, find and output to the file the minimum value in the array, and output all the values in the array. Output will have appropriate labels.
Explanation / Answer
Answer
1.
Below is the required c++ code:
//include the headers
#include <iostream>
#include <fstream>
using namespace std;
//the required function
int read_file(int *arr)
{
char file_name[100];
int num_count = 0; /*intializing the value for the number of integers read*/
cout<<"Enter the file name from which you want to read the integers::";
cin>>file_name;
ifstream File;
File.open(file_name);
while(!File.eof())
{
File>>arr[num_count]; /*File is a pointer that points to single integer in the file at a time*/
num_count++;
}
File.close();
return num_count;
}
//main function from where the read_file() is called
int main()
{
int arr[100];
int count = read_file(arr);
cout<<"The number of integers read from the input file is "<<count+1; /*+1 because array index starts with 0 so to include it in the count we do +1*/
return 0;
}
2.
Below is the required c++ code:
#include<iostream>
#include<fstream>
using namespace std;
void write_array(int *arr, int n)
{
char file_name[100];
int count=0;
cout<<"Enter the file name on which you want to write::";
cin>>file_name;
ofstream fout(file_name); /*opening the file for writing*/
if(fout.is_open()) /*if the file opens succfully*/
{
for(int i=0;i<n;i++)
{
fout<<arr[i];
fout<<" ";
count ++;
if(count == 10)
{
fout<<" ";
count=0;
}
}
}
else
cout<<"File did not open ";
}
int main()
{
int arr[100];
int num = 0;
cout<<"Enter the size of the array::";
cin>>num;
cout<<"Enter the array elements::";
for(int i=0;i<num;i++)
{
cin>>arr[i];
}
write_array(arr, num);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.