-4

Why doesn't the conditional Boolean in the standard for loop below behave as expected? I'm trying to get 3 and 4, indexes 2 and 3 in the array below to print out. If I try to specify the range in the condition of the for loop it doesn't run the loop. To test the conditional in an if condition ( see 2nd listing it works )

Why doesn't it simply work just in the for loop ?

int[]weather = {1,2,3,4,5,6,7};
for(int i=0;i>1&&i<4; i++ ) {
    //if(i>1&&i<4) {
        System.out.println("Weather is ===> "+weather[i]);
    //}
}

nothing printed...

int[]weather = {1,2,3,4,5,6,7};
for(int i=0;i<10; i++ ) {
    if(i>1&&i<4) {
        System.out.println("Weather is ===> "+weather[i]);
    }
}

Weather is ===> 3
Weather is ===> 4
Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39
JohnnyO
  • 527
  • 9
  • 21
  • 1
    Because 0 is less than 1 so the loop condition is already false on the first iteration? – UnholySheep Sep 09 '21 at 12:45
  • 1
    "`for(int i=0;i>1&&i<4; i++ ) {`" the condition is immediately false. – Andy Turner Sep 09 '21 at 12:45
  • 1
    how can i be greater than 1 when it is set to 0? – OldProgrammer Sep 09 '21 at 12:46
  • 1
    Note that the condition in a loop is used to check whether it should continue running (or start at all) and if the first check returns false (because 0 > 1 is false) it never starts. If that weren't the case, how should the loop "know" when to stop? – Thomas Sep 09 '21 at 12:49

3 Answers3

1

for(int i=0;i>1&&i<4; i++ ) dosen't work because since i=0 and it dosen't satisfy the condition in a loop and thus the program never enters the loop.

This is usually used to sometime skip the loop when not needed.

0
for(int i=0;i>1&&i<4; i++ ) {
            ^------^ expression

For loops execute until the expression is false, and then stop executing. This expression is immediately false (because 0>1 is false), so it immediately stops executing. It doesn't "wait and see" if the expression becomes true again.

If you only want the loop to execute for i>1&&i<4:

for(int i = 2; i<4; i++ ) {
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Thanks.. for some reason I forgot the fact that the loop stops, shuts down immediately upon 1st false. That the conditional meant stop running. – JohnnyO Sep 09 '21 at 13:24
0

Simply you don't pass the condition after the initialization. At the beginning i is set to 0. The loop continues until i is between 1 and 4 (both excluded), so you never start the loop.

for (int i = 0; i > 1 && i < 4; i++) {
    // You never goes here because i is 0 so not > than 1
    ...
}

Instead if you put the condition inside the loop you bypass execute all the iterations and for some of them you enter the if condition.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56