Java program to generate Harmonic Series 1 + 1/2 + 1/3 + 1/4 + 1/5

Share on FacebookTweet about this on TwitterDigg thisPin on PinterestShare on LinkedInShare on StumbleUponShare on TumblrShare on Google+Email this to someone
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* Write a program to generate Harmonic Series.
   Example :
   Input - 5
   Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */
class HarmonicSeries{
	public static void main(String args[]){
		int num = Integer.parseInt(args[0]);
		double result = 0.0;
		while(num > 0){
			result = result + (double) 1 / num;
			num--;
		}
		System.out.println("Output of Harmonic Series is "+result);
	}
}

Share on FacebookTweet about this on TwitterDigg thisPin on PinterestShare on LinkedInShare on StumbleUponShare on TumblrShare on Google+Email this to someone

6 Responses to “Java program to generate Harmonic Series 1 + 1/2 + 1/3 + 1/4 + 1/5”

  1. kunal singh

    class pat1
    {
    public void print()
    {
    for(int i=1;i<=5;i++)
    {
    for(int j=1;j<=i;j++)
    {
    System.out.print("*");
    }
    System.out.println();
    }
    }
    }

    Reply
  2. import java.io.*;

    class h2
    {
    public static void main(String args[])
    {
    int n=Integer.parseInt(args[0]);
    double r=0.0;
    while(n>=0)
    {
    r=r+(double) 1 / n;
    n–;
    }
    System.out.println(“output of harmonic series is ” + r);
    }
    }

    i tried that above program but i’l get a Array index out of bounds exception error.. i dont know how to rectify that error…kindly rectify it …pls

    Reply
  3. shresthaa atreya

    public class display
    {
    public static void main(String ar[])
    {
    int a=1,i;
    double s=0.0;
    for(i=1;i<=5;i++)
    {
    s=s+a/i;
    }
    System.out.println("series="+s);
    }
    }

    Reply
  4. Nusrat Ahmed Asha

    public class HermonicSeries {
    public static void main(String args[])
    {
    int i;
    double result=0.0;
    for(i=1; i<=5; i++)
    {
    result=result + (double) 1/i;
    }
    System.out.println("1+1/2+1/3+1/4+1/5 = "+result);
    }

    }

    Reply
  5. why we are using double????? in result= result
    = 1/i;
    why its not like result = result + 1/i;

    Reply

Leave a Reply