Duplicate Local Variable error in a For loop

183 views Asked by At

I'm trying to make a program that finds the sum of all the integers between two numbers, inclusive. I'll paste what I have so far, but I'm getting an error (i is a duplicate local variable?). Thanks

public int sum(int num1, int num2){

    if (num1 == num2){
        return num1;
    }
    if (num1 > num2){
        for (int i = (num2 + 1), i <= num1, i++){
            num2 += i;
        }
        return num2;
    }
    if (num2 > num1){
        for(int i = num1 + 1, i <= num2, i++){
            num1 += i;
        }
        return num1;
    }
}
1

There are 1 answers

0
Reut Sharabani On

Use semi-colons in your for loops, not commas:

public int sum(int num1, int num2){

    if (num1 == num2){
        return num1;
    }
    if (num1 > num2){
        for (int i = (num2 + 1); i <= num1; i++){
            num2 += i;
        }
        return num2;
    }
    if (num2 > num1){
        for(int i = num1 + 1; i <= num2; i++){
            num1 += i;
        }
        return num1;
    }
}