package tamirnfasle2;
import java.util.Scanner;

public class Tamrine4 {
    private int number;
    Tamrine4(int n)
    {
        number=n;
    }
    public void Calculate()
    {
        float sum=0.0f;
        for(int i=1;i<=number;i++)
        {
            i=1/i;
            sum=sum+i;
        }
        System.out.println("Sum Reverse Number Between [1," + number + "] Is :" + sum);
    }
    public static void main(String [] args){
        Scanner inputNumber = new Scanner (System.in);
        System.out.println("Enter Number : ");
        int number = inputNumber.nextInt();
        Tamrine4 ClassSumInverse = new Tamrine4(number);
        ClassSumInverse.Calculate();  
    }  
}

What is Wrong With This Code?! It's Not Working!!!

Recommended Answers

All 2 Replies

Your for loop will go forever because you set i to 0 or 1 at the start of each iteration of the loop. 1/1 is 1, and 1/2 is 0. So i will never reach number unless number is one of those two values, and the loop won't stop until i is greater than number.

for(int i=1;i<=number;i++)
            {
                i=1/i;// error is here
                //you are using i variable to increment and again assinging value to the same variable 
                sum=sum+i;
            }

The line marked as error line is shown above.
Here you are reassigning variable i value.
So first time when it comes in loop, value of i=1, then u reassign it to 1/1=1.and then it is incremented to 2.

On second iteration i=2, goes in loop if number is greater than 1, now
i=1/2=0.
So the loop continues as i Value changes from 1 and 0 alternatively so infinite loloop becomes infinite loop

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.