Program for weighted mean of natural numbers in C++

C++Server Side ProgrammingProgramming

Given with an array of natural numbers and one more array containing the weights of the corresponding natural numbers and the task is to calculate the weighted mean of natural numbers.

There is a formula which is used for calculating the weighted mean of natural numbers.

$$\overline{x}=\frac{\displaystyle\sum\limits_{i=1}^n (x_{i*}w_{i})}{\displaystyle\sum\limits_{i=1}^n w_{i}}$$

Where, x is the natural number and w is the weighted associated with that natural number.

Input 

X[] = {11, 22, 43, 34, 25, 16}
W[] = {12, 12, 43, 54, 75, 16}

Output 

weighted mean is : 29.3019

Explanation 

(11*12 + 22*12 + 43*43 + 34*54 + 25*75 + 16*16) / (12 + 12 + 43 + 54 +75 +16)

Input 

X[] = {3, 4, 5, 6, 7}
W[] = {4, 5, 6, 7, 8}

Output 

weighted mean is : 5.33333

Explanation 

(3*4 + 4*5 + 5*6 + 6*7 + 7*8) / (4 + 5 + 6 + 7 + 8)

Approach used in the below program is as follows

  • Input the two different arrays, one is for natural numbers and another for the weights for the corresponding natural numbers.

  • Apply the formula to calculate the weighted mean of natural numbers

  • Print the corresponding result.

Algorithm

Start
Step1→ declare function to calculate weighted means of natural numbers
   float weightedmean(int X[], int W[], int size)
      Declare int sum = 0, weight = 0
      Loop For int i = 0 and i < size and i++
         Set weight = weight + X[i] * W[i]
         Set sum = sum + W[i]
      End
      return (float)weight / sum
Step 2→ In main()
   Declare int X[] = {11, 22, 43, 34, 25, 16}
   Declare int W[] = {12, 12, 43, 54, 75, 16}
   Declare int size_X = sizeof(X)/sizeof(X[0])
   Declare int size_W = sizeof(W)/sizeof(W[0])
   IF (size_X == size_W)
      Call weightedmean(X, W, size_X)
   End
   Else
      Print -1
   End
Stop

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
//calculate weighted mean.
float weightedmean(int X[], int W[], int size){
   int sum = 0, weight = 0;
   for (int i = 0; i < size; i++){
      weight = weight + X[i] * W[i];
      sum = sum + W[i];
   }
   return (float)weight / sum;
}
int main(){
   int X[] = {11, 22, 43, 34, 25, 16};
   int W[] = {12, 12, 43, 54, 75, 16};
   int size_X = sizeof(X)/sizeof(X[0]);
   int size_W = sizeof(W)/sizeof(W[0]);
   if (size_X == size_W)
      cout<<"weighted mean is : "<<weightedmean(X, W, size_X);
   else
      cout << "-1";
   return 0;
}

Output

If run the above code it will generate the following output −

weighted mean is : 29.3019
raja
Published on 13-Aug-2020 07:15:50
Advertisements