In: Computer Science
Write a C++program that initializes an array called resistances with the following initializer list: from file called "resistances. txt" {12.3, 98.5, 15.15, 135, 125} Using a while-loop, compute the sum of the elements of the resistances array and then obtain the average resistance and d isplay it. Then, use another loop to display the resistances that has value smaller than the average resistance that
// TEXT CODE
#include <bits/stdc++.h>
using namespace std;
// driver code
int main()
{
// filestream variable file
fstream file;
string word, filename;
// filename of the file
filename = "resistances.txt";
// opening file for getting number of numbers
file.open(filename.c_str());
int size = 0;
// getting size
while (file >> word)
{
// displaying content
size++;
}
// declare an array resistances od size "size"
double resistances[size];
// opening file again for extracting word
fstream file1;
file1.open(filename.c_str());
int i = 0;
// extracting words from the file and saving it into array
resistances
while (file1 >> word)
{
resistances[i] = stod(word);
i++;
}
// get the sum
double sum = 0;
for(int i = 0; i < size; i++){
sum = sum + resistances[i];
}
// get average
double average = sum/size;
cout << "Average is: " << average << endl;
// now print all numbers lesser than average
cout << "resistances less than average resistance are:
";
for(int i = 0; i < size; i++){
if(resistances[i] < average)
cout << resistances[i] << ", ";
}
return 0;
}
// resistances.txt file
12.3, 98.5, 15.15, 135, 125
// OUTPUT (After running for resistances.txt file)
Average is: 77.19
resistances less than average resistance are: 12.3, 15.15,