0

This is a part of my 2nd method.. the method is using the first and last values of an array given by my main method and adding them together. If the sum is above (in my example "20"), then j (the last value of the array) decreases. If the sum is below 20, i (first value of the array) is increased. The process is repeated until either i == j or i + j = 20

I am using a do ... while loop with a couple of if statements...but for some reason, my program keeps running and gives no result. Help?

        public static int checkSum(int[] array){
        int i = 0;
    int j = 6;
    int sum;

    sum = array[i] + array[j];
    do {

        if (sum == 20) {
            break;
        }
        else if (sum < 20) {
            i = i++;
            sum = array[i] + array[j];
        }
        else {
            j = j--;
            sum = array[i] + array[j];
            System.out.print("No");
        } 
        sum = array[i] + array[j];
    } while (i != j);

    if (i == j) {
        i = -1;
    }
    return i;   

For the sake of not spamming the website.. i should be 2... but my program gives no results and keeps running infinitely..

Keith
  • 276
  • 2
  • 14
  • 1
    there are two loop break conditions that I see and the question is what guarantee you have that one or the other will occur? The first is that `sum` converges to the value of `20`. The other is that at some point the value of the variable `i` will be equal to the value of variable `j`.Perhaps you should instead have `while (i < j)` ? and why are you doing `i = i++;` rather than just `i++`? The same for `j = j--;` rather than just `j--;`? I think that neither the variables `i` nor `j` are changing since you are using postfilx operators. – Richard Chambers Aug 28 '19 at 01:46

2 Answers2

1

The reason your program keeps running is because you are never changing the values of i and j.

The syntax i++ means "increment i, but return the original value (BEFORE the increment)" So, when your code has a statement like :

i = i++;

you are assigning i to be the value BEFORE the increment - ie. it's not changing !

The fix is to simply use i++ and j++ without assignments.

racraman
  • 4,988
  • 1
  • 16
  • 16
0
public static int checkSum(int[] array) {
        int i = 0;
        int j = 6;
        int sum;


        do {
            sum = array[i] + array[j];
            if (sum == 20) {
                break;
            } else if (sum < 20) {
                i++;
            } else {
                j--;
            }
        } while (i != j);

        if (i == j) {
            i = -1;
        }
        return i;

    }

Issue is how you use i++. Check this thread for more details And I have removed unnecessary code parts mainly the sum = array[i] + array[j].

sYl3r
  • 393
  • 5
  • 16