In C++: For a number N input by the user, 1. Print the average of all numbers fr
ID: 3796950 • Letter: I
Question
In C++:
For a number N input by the user,
1. Print the average of all numbers from 1 to N,
2. Print the average of all even numbers from 1 to N, and
3. Print the average of all odd numbers from 1 to N. ……
4. Print the average of every third number ( e.g., 1, 4, 7, )
5. Print the highest average value
6. Print the least average value
Constraint: You must use ‘for’ loop to solve this problem.
Furthermore, once the program prints output on the console, it should ask the user if s/he is interested in entering another number. If the user enters ‘y’ or ‘Y’ the program will continue the execution, but for any other input, the program will terminate.
Explanation / Answer
// C++ code
#include <iostream>
#include <fstream>
#include <cctype>
#include <cstring>
#include <stdlib.h> /* srand, rand */
#include <iomanip>
#include <limits.h>
#include <cmath>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
int main()
{
int n;
char again;
double average1, average2, average3, average4, sum;
double highest = INT_MIN;
double lowest = INT_MAX;
int count;
while(true)
{
cout << "Enter n: ";
cin >> n;
sum = 0;
for (int i = 1; i <= n ; ++i)
{
sum = sum + i;
}
average1 = sum/n;
if(average1 < lowest)
lowest = average1;
if(average1 > highest)
highest = average1;
cout << "Average: " << average1 << endl;
sum = 0;
count = 0;
for (int i = 1; i <= n; ++i)
{
if(i%2 == 0)
{
sum = sum + i;
count++;
}
}
average2 = sum/count;
if(average2 < lowest)
lowest = average2;
if(average2 > highest)
highest = average2;
cout << "Average of all even numbers: " << average2 << endl;
sum = 0;
count = 0;
for (int i = 1; i <= n; ++i)
{
if(i%2 != 0)
{
sum = sum + i;
count++;
}
}
average3 = sum/count;
if(average3 < lowest)
lowest = average3;
if(average3 > highest)
highest = average3;
cout << "Average of all odd numbers: " << average3 << endl;
sum = 0;
count = 0;
for (int i = 1; i <= n; i=i+3)
{
sum = sum + i;
count++;
}
average4 = sum/count;
if(average4 < lowest)
lowest = average4;
if(average4 > highest)
highest = average4;
cout << "Average of every third number: " << average4 << endl;
cout << "Highest average: " << highest << endl;
cout << "Lowest average: " << lowest << endl << endl;
cout << "Do you want to enter another number(y/n)? ";
cin >> again;
cout << endl;
if(again == 'n')
break;
}
return 0;
}
/*
output:
Enter n: 20
Average: 10.5
Average of all even numbers: 11
Average of all odd numbers: 10
Average of every third number: 10
Highest average: 11
Lowest average: 10
Do you want to enter another number(y/n)? y
Enter n: 40
Average: 20.5
Average of all even numbers: 21
Average of all odd numbers: 20
Average of every third number: 20.5
Highest average: 21
Lowest average: 10
Do you want to enter another number(y/n)? n
*/