When will the ‘while’ loop be preferred over the for loop? Mention the scenario and write the
programme to demonstrate this?
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;
}
Comments
Leave a comment