For a set of integers stored in an array,calculate the sum of the positive numbers and the sum of the negative numbers. The program should store these numbers in memory variables: positiveSum and negativeSum. Numbers should be read from the array one at a time with a zero value (0) being used to signal the end of data (the zero value is acting as a "sentinel" value).

Respuesta :

Answer: The c++ program to implement the given conditions is shown below.

#include <iostream>

using namespace std;

int main()

{

// used as index of array in the loop for calculating the sum

   int i=0;

// array contains both negative and positive integers

// 0 is used as the sentinel value

   int arr[12]={-9,-8,-3,-12,-78,-10,23,45,67,1,0};

   int positiveSum=0, negativeSum=0;

   do

   {

       if(arr[i]<0)

           negativeSum = negativeSum + arr[i];

       if(arr[i]>0)

           positiveSum = positiveSum  + arr[i];

// after every element is added, index of array represented by i is incremented

       i++;

   }while(arr[i]!=0);

// loop continues till end of array is reached

   cout<<"Sum of positive integers "<<positiveSum<<" and sum of negative integers "<<negativeSum<<endl;

   return 0;

}

OUTPUT

Sum of positive integers 136 and sum of negative integers -120

Explanation: This program declares and initializes an integer array without user input. As mentioned in the question, 0 is taken as the sentinel value which shows the end of data in the array.

   int arr[12]={-9,-8,-3,-12,-78,-10,23,45,67,1,0};

All the variables are declared with data type int, not float. Since, integers can yield integer result only.

The do-while loop is used to calculate the sum of both positive and negative integers using int variable i. The variable i is initialized to 0.

This loop will run till it encounters the sentinel value 0 as shown.

while(arr[i]!=0);

Hence, all the integers in the array are read one at a time and sum is calculated irrespective of the element is positive or negative.

       if(arr[i]<0)

           negativeSum = negativeSum + arr[i];

       if(arr[i]>0)

           positiveSum = positiveSum  + arr[i];

After the element is added, variable i is incremented and loop is continued.

The do-while loop tests positive and negative integers based on the fact whether their value is greater than or less than 0.

The program can be tested using different size and different values of positive and negative integers in the array.