-1
public int sum (int num1, int num2){
    int sum = 0;
        if(num2>num1){
        for (int i = num1; i<=num2; i++){
            sum = sum + i;
            }
        }
        else{
        for (int i = num2; i <= num1; i++){
            sum = sum + i;
            }
        }
    System.out.println("The sum between " +num1+ " and " +num2+ " equals " + sum);
    return sum(num1, num2);
    }
}

infinite loop problem. any fixes? trying to find the sum of all the numbers between two inputs. this is the class definition any ideas?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 5
    There's no exit case for the recursive call... – MadProgrammer Oct 31 '13 at 04:32
  • 1
    Format your code legibly. Then, only have one version of the loop. Specify that the caller needs to provide the lower number first, and then provide another method that you can call that will swap them around if necessary, so that your code is simpler and easier to follow. – chrylis -cautiouslyoptimistic- Oct 31 '13 at 04:33
  • Hello, Follow coding standards.Same name for variable and function. unacceptable. @chrylis : thanks dude. – Chandan Kumar Oct 31 '13 at 04:41
  • Yes, use a debugger and you could find out yourself. – Raedwald Feb 08 '16 at 16:25
  • Possible duplicate of [What is a debugger and how can it help me diagnose problems](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Feb 08 '16 at 16:27

4 Answers4

2

You're calling sum() again, and without any condition to check when to break the recursion. Hence an infinite loop

As the other answers have pointed out, you have to replace return sum(num1,num2); with return sum;

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
2

In place of return sum(num1, num2); you should return sum;

Dhruv Pal
  • 849
  • 2
  • 10
  • 25
0
public int sum (int num1, int num2)
{
   int sum = 0;
   if(num2>num1)
   {
        for (int i = num1; i<=num2; i++)
        {
            sum = sum + i;
         }
   }
   else
   {
        for (int i = num2; i <= num1; i++)
        {
            sum = sum + i;
        }
    }
    System.out.println("The sum between " +num1+ " and " +num2+ " equals " + sum);
    return sum;  
  }

you were doing recursive calling thats the problem..

sam
  • 2,426
  • 2
  • 20
  • 29
0

You are calling the function recursively by return sum(num1, num2);. So change return sum(num1, num2); to return sum;

Linga
  • 10,379
  • 10
  • 52
  • 104
upog
  • 4,965
  • 8
  • 42
  • 81