C++ while-loop

Introduction

For-loop is usually used when we know the number of iterations.
However, when we do not know the number of iterations, we use a while-loop.

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.

Code - Enter 5 numbers (use while-loop as for-loop)

#include <iostream>
using namespace std;

int main() {
	int arr[5];
	int i=0;
	cout << "Enter 5 numbers: ";
	while(i<5) {
		cin >> arr[i];
		i++;
	}
}
	

Task

Ask for user input until negative number is entered.
Output the average value.
Hints: declare one variable to store the sum of the numbers and another variable to store the count of the numbers.

Example:

Enter a number: 5
Enter a number: 3
Enter a number: 2
Enter a number: -1
Average: 3.33
	

Reference

w3schools