While-loop allows code to be executed repeatedly based on a given condition.
Example:
char ans='y';
while(ans=='y') {
cout << "Do you want to continue? (y/n): ";
cin >> ans;
}
While-loop will keep asking the user if they want to continue until the user enters 'n'.
When the user enters 'n', the loop will stop because the condition is no longer true.
#include <iostream>
using namespace std;
int main() {
int arr[5];
int i=0;
cout << "Enter 5 numbers: ";
while(i<5) {
cin >> arr[i];
i++;
}
}
Example:
Enter a number: 5
Enter a number: 3
Enter a number: 2
Enter a number: -1
Average: 3.33