Your boss sent you a notepad file called numbers.txt containing an
unknown number of integers. He requests you to write a single program
that a) reads these numbers into an array b) checks whether the file
has correctly opened c) prints out the average of all the numbers in the
array d) then program should search the array to see whether integer 150
is present e) finally the program should print out all the positive numbers
in the array. [20]
#include <iostream>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main() {
string filename = "numbers.txt";
ifstream File;
int number = 0, element = 0, sum_all = 0;
bool exists_value = false;
vector<int>p_darr;
File.open(filename);
if (File.is_open()) {
while (!File.eof()) {
File >> element;
number++;
p_darr.push_back(element);
sum_all += element;
if (element == 150) {
exists_value = true;
}
}
File.close();
}
cout << "the average of all the numbers in the array: " << sum_all << endl;
cout << "Is 150 present in array: " << exists_value << endl;
for (int i = 0; i < number; i++) {
if (p_darr[i] > 0) {
cout << p_darr[i] << " ";
}
}
}
Comments
Leave a comment