Home > Back-end >  For loop returns different results compared to While loop
For loop returns different results compared to While loop

Time:07-06

Can someone explain why I'm getting incorrect results when I use a for loop?

WORKING CODE:

int smallest = myList.get(0);
int index = 0;
while (index < myList.size()) {
    if (myList.get(index) < smallest) {
        smallest = myList.get(index);
    }
    index  ;
}

5 4 3 1 1 7

Smallest number: 1 Found at index: 3 Found at index: 4

INCORRECT CODE:

int smallest = myList.get(0);
int index = 0;
for (index = 0; index < myList.get(index); index  ) {
    if (myList.get(index) < smallest) {
        smallest = myList.get(index);
    }
}

5 4 3 1 1 7

Smallest number: 3 Found at index: 2

CodePudding user response:

The limit of the for loop you have set was not right. Same like while loop it should iterate till the last element for getting the min value, for that we set its limit less than size of list.

for (index = 0; index < myList.size(); index  )

CodePudding user response:

for (index = 0; index < myList.get(index); index  ) {

As others have mentioned the problem is in this line specifically the myList.get(index) part. Instead of checking the size of myList it takes the current elements index as size. So for the first 3 you get lucky as 0 (index) < 5 (myList.get(index), 1 < 4 and 2 < 3, but starting with the 4th element (index 3) you get 3 < 1, which is obviously false and so the loop is stopped here.

Also just as a side note, if you don't use that first part of the for loop you can usually omit it:

for (; index < myList.size(); index  ) {
  • Related