Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use a for loop inside the condition of an if-else statement?

Can you use a for loop inside the condition of an if-else statement? For example, something like this...

if(
        for(q = 0; q < 10; q++){
            values[q]>=values[q+1];
        }          
            )

            {

         done = 0;
    }

This is loading an error I can't seem to place. I want the if statement to check to see if the int[] I called values is in order from greatest to least, and if it is, set int variable done equal to 0.

I only just started taking a programming class and I bet this is a very dumb mistake, but I've been trying to figure this out for a while and some help would be absolutely fantastic.

like image 872
user3413468 Avatar asked Mar 13 '14 02:03

user3413468


1 Answers

You should work out your condition first (ie is your array in order), and then feed that in to your if statement. Like so...

boolean isOrdered = true;

for(q = 0; q < 10; q++){
  if (values[q]>=values[q+1]){
    // in order
    }
  else {
    // not in order
    isOrdered = false;
    break; // we have found a false, so we can quit out of the for loop
    }
  }

if (isOrdered){
  // do something if the array is in order;
  }
like image 59
wattostudios Avatar answered Oct 31 '22 14:10

wattostudios