Thursday 15 June 2017

Java code to compute the Harmonic Mean of n values

Problem:

Develop an algorithm to compute the harmonic mean of n data values.

Algorithm:

1. Prompt the number of terms in a series
2.  Initialize sum for zero numbers
3. While less than n numbers have been summed repeatedly do
     a. compute current sum by adding the harmonic series (i.e 1/number) to the most recent sum.
4. Divide the number of terms in a series by sum
5. Print the output

Solution:

package com.myprograms;

import java.util.Scanner;

public class HarmonicMean {

public static void main(String[] args) {
System.out.println("Enter the No. of terms in series : ");
Scanner s = new Scanner(System.in);
int n = s.nextInt();

double sum = 0.0;
for(int i = 1; i <= n; i++){
sum = sum + 1.0/i;
}
System.out.println("the harmonic mean  is: " + n/sum);

s.close();
}
}


Output:

Enter the No. of terms in series :
5
the harmonic mean  is: 2.18978102189781


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...