Exercise HarmonicSum (Loop) ~ Programming is Fun
 Programming is Fun!

www.anandsingh.net
Subscribe For Free Updates!

We'll not spam mate! We promise.

Saturday, September 6, 2014

Exercise HarmonicSum (Loop)

Write a program called HarmonicSum to compute the sum of a harmonic series, as shown below, where n=50000. The program shall compute the sum from left-to-rightas well as from the right-to-left. Obtain the difference between these two sums and explain the difference. Which sum is more accurate?
ExerciseBasics_HarmonicSum.png
Hints:
public class HarmonicSum {   // saved as "HarmonicSum.java"
   public static void main (String[] args) {
      int maxDenominator = 50000;
      double sumL2R = 0.0;    // sum from left-to-right
      double sumR2L = 0.0;    // sum from right-to-left
   
      // for-loop for summing from left-to-right
      for (int denominator = 1; denominator <= maxDenominator; ++denominator) {
          ......
          // Beware that int/int gives int.
      }
      // for-loop for summing from right-to-left
      ......
      // Find the difference and display
      ......
   }
}
Comment your Answers :)


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

0 comments:

Post a Comment