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

Saturday, February 5th, 2011
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);
	}
}

Author Name :
surajk

Total : 5 Comments


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

  1. kunal singh says:

    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();
    }
    }
    }

  2. shalini says:

    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

  3. shresthaa atreya says:

    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);
    }
    }

  4. Ravikrishna.T says:

    calculator program logics

  5. Nusrat Ahmed Asha says:

    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);
    }

    }

Leave a Reply

Question and Answer
C/C++ Unix & Linux Wordpress
Source codes
C C++ Java

Free email signup

Email: