155k views
4 votes
g Write a program that prompts the user for an integer n between 1 and 100. If the number is outside the range, it prints an error. The program computes and prints at the end two things: The sum of the numbers from 1 to n. The average of the numbers from 1 to n. Average should only have 2 digits after the decimal.

User Cygorger
by
5.1k points

1 Answer

1 vote

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

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

Step-by-step 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.

User MalsR
by
5.9k points