Answer:
The cpp program is given below.
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
// variables declared
int n;
int sum=0;
float avg;
do
{
// user input taken for number
cout<< "Enter a number between 1 and 100 (inclusive): ";
cin>>n;
if(n<1 || n>100)
cout<<" Number is out of range. Enter valid number."<<endl;
}while(n<1 || n>100);
cout<<" "<<endl;
// printing even numbers between num and 50
for(int num=1; num<=n; num++)
{
sum = sum + num;
}
avg = sum/n;
// displaying sum and average
cout<<"Sum of numbers between 1 and "<<n<<" is "<<sum<<endl;
cout<<"Average of numbers between 1 and "<<n<<" is ";
printf("%.2f", avg);
return 0;
}
OUTPUT
Enter a number between 1 and 100 (inclusive): 123
Number is out of range. Enter valid number.
Enter a number between 1 and 100 (inclusive): 56
Sum of numbers between 1 and 56 is 1596
Average of numbers between 1 and 56 is 28.00
Explanation:
The program is explained below.
1. Two integer variables are declared to hold the number, n, and to hold the sum of numbers from 1 to n, sum. The variable sum is initialized to 0.
2. One float variable, avg, is declared to hold average of numbers from 1 to n.
3. User input is taken for n inside do-while loop. The loop executes till user enters value between 1 and 100. Otherwise, error message is printed.
4. The for loop executes over variable num, which runs from 1 to user-entered value of n.
5. Inside for loop, all the values of num are added to sum.
sum = sum + num;
6. Outside for loop, average is computed and stored in avg.
avg = sum/n;
7. The average is printed with two numbers after decimal using the following code.
printf("%.2f", avg);
8. The program ends with return statement.
9. All the code is written inside main() and no classes are involved.