0
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!!!

3
Contributors
2
Replies
20
Views
4 Years
Discussion Span
Last Post by IIM
0

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.

0
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

Edited by IIM: spell

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.