Final answer:
The readSortedArray function takes an input filestream object and an array of floats as parameters. It reads the first item outside the loop, then uses a loop to compare adjacent items and place them in successive locations in the array. If any adjacent pair is not in order, it returns -1. Once the end of the file or the end of the array is reached, it returns the number of items read.
Step-by-step explanation:
Question 1 (pre-lab):
The parameters that will specify the array and the input filestream for the function readSortedArray are:
- An input filestream object
- An array of float values
The header for the function readSortedArray would be:
int readSortedArray(ifstream& file, float arr[])
Question 2 (pre-lab):
The loop to read the data into the array can be designed as follows:
file >> arr[0]; // Read the first item outside the loop
int count = 1;
float currentItem;
while (file >> currentItem)
{
if (currentItem < arr[count - 1])
{
return -1; // Abandon the process and return -1 if items are not in order
}
arr[count] = currentItem; // Place the item in the next location in the array
count++;
if (count >= 20)
{
break; // Exit the loop if the end of the array is reached
}
}
Question 3:
Here is an implementation of the readSortedArray function in C++:
#include <iostream>
#include <fstream>
using namespace std;
double readSortedArray(ifstream& file, float arr[])
{
file >> arr[0]; // Read the first item outside the loop
int count = 1;
float currentItem;
while (file >> currentItem)
{
if (currentItem < arr[count - 1])
{
return -1; // Abandon the process and return -1 if items are not in order
}
arr[count] = currentItem; // Place the item in the next location in the array
count++;
if (count >= 20)
{
break; // Exit the loop if the end of the array is reached
}
}
return count; // Return the number of items that were read
}
Question 4:
Here is a driver program to test the readSortedArray function:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
float arr1[20];
float arr2[30];
ifstream inputFile("input.txt");
ofstream outputFile("output.txt");
double result1 = readSortedArray(inputFile, arr1);
if (result1 == -1)
{
cout << "File is not sorted." << endl;
}
else
{
display(arr1, result1); // Call the display function from the previous lab to print the values stored in the array
}
inputFile.close();
inputFile.clear();
inputFile.open("input.txt");
double result2 = readSortedArray(inputFile, arr2);
if (result2 == -1)
{
cout << "File is not sorted." << endl;
}
else
{
display(arr2, result2); // Call the display function from the previous lab to print the values stored in the array
}
inputFile.close();
outputFile.close();
return 0;
}