31.2k views
3 votes
Question 3 Declare a large array of doubles. The first five elements of the array are to be read from the keyboard, and the rest of the array elements are to be read from a file containing an unknown number of doubles. Then the program should print the average of all the array elements. (It is easy to go wrong here. You should check your final average with a calculator to be sure that it is correct. There are traps, and you may get a wrong answer without realizing it - so check.)​

User Erran
by
8.8k points

1 Answer

7 votes

Here's an example program in C++ that fulfills the requirements:

_______________________________________________________

#include <iostream>

#include <fstream>

#include <vector>

using namespace std;

int main() {

const int ARRAY_SIZE = 1000; // Set a large size for the array

double array[ARRAY_SIZE];

double sum = 0.0;

int count = 0;

// Read the first five elements from the keyboard

cout << "Enter the first five elements of the array:\\";

for (int i = 0; i < 5; i++) {

cout << "Element " << i + 1 << ": ";

cin >> array[i];

sum += array[i];

count++;

}

// Read the remaining elements from a file

ifstream inputFile("input.txt"); // Replace "input.txt" with your file name

double num;

while (inputFile >> num && count < ARRAY_SIZE) {

array[count] = num;

sum += array[count];

count++;

}

inputFile.close();

// Calculate and print the average

double average = sum / count;

cout << "Average of array elements: " << average << endl;

return 0;

}

________________________________________________________

In this C++ program, a large array of doubles is declared with a size of 1000. The first five elements are read from the keyboard using a for loop, and the sum and count variables keep track of the cumulative sum and the number of elements entered.

The remaining elements are read from a file named "input.txt" (you should replace it with the actual file name) using an ifstream object. The program continues reading elements from the file as long as there are more numbers and the count is less than the array size.

Finally, the average is calculated by dividing the sum by the count, and it is printed to the console. Remember to replace "input.txt" with the correct file name and double-check the average with a calculator to ensure accuracy.

~~~Harsha~~~

User Akalanka
by
8.3k points

No related questions found