This program has the user input a number n and then finds the
mean of the first n positive integers. It uses a while loop
for data validation and a for loop to accumulate the total of the integers from 1 to n.
Display:
This program finds the average of the first n integers.
Please enter a positive integer: -2
Only positive integers are valid. Please re-enter: 6
The mean average of the first 6 positive integers is 3
This program finds the average of the first n integers.
Please enter a positive integer: 15
The mean average of the first 15 positive integers is 8
Code:
#include
using namespace std;
int main()
{
//declaration of variables
int n;
int total = 0;
int number;
float mean;
cout<< "This program finds the average of the first n integers.\n";
cout<< "Please enter a positive integer: ";
cin>> n;
//Using while loop and for loop statment
while (n <= 0)
{
//Prompts user to input
cout<< "Only positive integers are valid. Please re-enter: ";
cin>> n;
}
for (number = 1; number <= n; number++)
{
total = total + number;
}
mean = (total) / n;
cout << "The mean average of the first " << n
<< " positive integers is "<< mean << endl;
return 0;
}