Answer to Question #346426 in C++ for Nia

Question #346426

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]




1
Expert's answer
2022-05-30T15:14:09-0400
#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] << " ";
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS