Answer to Question #297981 in C++ for Sahil

Question #297981

When will the ‘while’ loop be preferred over the for loop? Mention the scenario and write the




programme to demonstrate this?

1
Expert's answer
2022-02-15T08:15:27-0500

The while loop is used when the number of iterations is unknown in advance. For example, a while loop may be used to read numbers from the user and terminate reading when the user entered a negative number.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v;
    int x;

    cout << "Give me some positive numbers: ";
    cin >> x;
    while (x >= 0) {
        v.push_back(x);
        cin >> x;
    }

    cout << "You have entered " << v.size() << " numbers." << endl;
    cout << "Here they are: ";
    for (int i=0; i<v.size(); i++) {
        cout << v[i] << " ";
    }

    return 0;
}

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