Sum of 1/1-1/2+1/3-1/4+.......1/n in java

package Loops;
import java.util.Scanner;
public class factorial {
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        int n=sc.nextInt();
        System.out.println("the number is "+n);
        float result=0;
        for(float i=1;i<=n;i++) {
            if(i%2==0) {
                result=result-1/i;
            }
             else {
                 result=result+1/i;
            }
        }
        System.out.println("the result is "+result);
     }
}
    output:-
    8
    the number is 8
    the result is 0.6345238
   

Comments