SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
C++ Basics
Exercise:
Programming Projects
Question:11 | ISBN:9780321531346 | Edition: 7

Question

11. Modify your program from Programming Project 10 so that it outputs the sum of all positive numbers, the average of all positive number, the sum of all non-positive numbers, the average of all non-positive numbers, the sum of all positive and non-positive numbers, and the average of all numbers entered.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

NOTE: Refer the previous programming project 10. 

Modified program code:

//header file
#include <iostream>
using namespace std;
//Program begins from the main method
int main()
{
    //Define variables
    double inputNums;
    double sumOfPositiveNums=0;
    double sumOfNegativeNums=0;
    double totalOfAllNums=0;
    double totalPosNums=0;
    double totalNegNums=0;
    //Readsten whole numbers 
    cout<<" Enter any 10 numbers(whether positive, negative, or zero): "
    <<endl;
    for(int i=0;i<10;i++)
    {	
	    cin>>inputNums;
	    
	    totalOfAllNums +=inputNums ;
	   if(inputNums>0)//validate negative
	   {
            sumOfPositiveNums += inputNums;
            totalPosNums++;
	   }
       else
       {
	        sumOfNegativeNums += inputNums;
	        totalNegNums++;
       }
    }
    //Print sum of all positive numbers
    cout<<"Sum of all the POSITIVE numbers: "
         <<sumOfPositiveNums<<endl;
    cout<<"AVERAGE of all positive numbers : "
        <<sumOfPositiveNums/totalPosNums<<endl;
    //Print sum of all negative numbers
    cout<<"Sum of all the NEGATIVE numbers: "
         <<sumOfNegativeNums<<endl;
    cout<<"AVERAGE of all negative numbers : "
        <<sumOfNegativeNums/totalNegNums<<endl;
    //Print total sum of numbers
    cout<<"The sum of all the numbers : "<<totalOfAllNums<<endl;
    cout<<"Average of ALL NUMBERS: "<<totalOfAllNums/10<<endl;

}

Output of the program code:

Enter any 10 numbers(whether positive, negative, or zero): 
5
10
15
20
-6
-12
1
-4
25
-5
Sum of all the POSITIVE numbers: 76
AVERAGE of all positive numbers : 12.6667
Sum of all the NEGATIVE numbers: -27
AVERAGE of all negative numbers : -6.75
The sum of all the numbers : 49
Average of ALL NUMBERS: 4.9

 

0 0

Discussions

Post the discussion to improve the above solution.