Java program to find sum of harmonic series 1 + 1/2 + 1/3 + 1/4 + 1/5 +……+ 1/n

Java program to find sum of harmonic series 1 + 1/2 + 1/3 + 1/4 + 1/5 +......+ 1/n

class Harmonic
{
public static void main(String…s)
{
int n,i;
float sum=0;

n=Integer.parseInt(s[0]);

for(i=1;i<=n;i++)
{
sum=sum+(float)1/i;
}

System.out.println(“nSum=”+sum);
}
}

12 thoughts on “Java program to find sum of harmonic series 1 + 1/2 + 1/3 + 1/4 + 1/5 +……+ 1/n

  1. deepa

    class Harmonic
    {
    public static void main(String…s)
    {
    int n,i;
    float sum=0;

    n=Integer.parseInt(s[0]);

    for(i=1;i<=n;i++)
    {
    sum=sum+(float)1/i;
    }

    System.out.println(“nSum=”+sum);
    }
    }

    Reply
  2. Jatin Singh

    Plz tell the code for harmonic series
    S = 1-1/2 + 1/3 – 1/4…… -1/10

    Reply
  3. sriram krishna

    I want Harmonic series program for the below expression.

    1/(n+1)+1/(n+2)+1/(n+3)+………1/(n+n);
    please,help me for this.

    Reply
  4. Samreen fatma

    How to find the sum of series
    Question:
    1*1+ 2*2+3*3*3+4*4+5*5+6*6*6+……

    Reply
  5. Deepanshu Vashist

    why is (float) used in following statement?
    sum=sum+(float)1/i;

    Reply
    1. user

      Because if you divide 1 by i which is an integer your ans will be an integer. E.g. if i=2, 1/i will give you 0 and not 0.5, that’s why you typecast either numerator or denominator to float, so that the division 1/i is also float

      Reply
      1. soorajmahato

        import java.util.Scanner;
        class sum_of_hp
        {
        public static void main(String args[])
        {
        double num,i,sum=0;;
        Scanner sc=new Scanner(System.in);
        System.out.print(“upto how many terms you want to sum = “);
        num=sc.nextInt();
        for(i=1;i<=num;i++)
        {
        sum=sum+(1/i);
        }
        System.out.println("sum of the series upto "+num+" terms is " +sum);
        }
        }
        instead of using typecasting why didnot you take double type it is easier than type casting

        Reply
      2. sooraj

        import java.util.Scanner;
        class sumofhp
        {
        public static void main(String args[])
        {
        double num,i;
        double sum=0;
        Scanner sc=new Scanner(System.in);
        System.out.print(“upto how many terms you want to sum = “);
        num=sc.nextInt();
        for(i=1;i<=num;i++)
        {
        sum=sum+(1/i);
        }
        System.out.println("sum of the series upto "+num+" terms is " +sum);
        }
        }

        Reply
  6. sooraj

    instead of taking two different data type int and float can i use double type?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.