Conditional Expressions

Conditionals are expressions that evaluate to either true or false. They are mostly used to determine Program Flow through if statements and while loops.

Conditional Boolean Expressions

Often a computer program must make choices on which way to proceed, e.g., if the ball is in bounds, do one thing, else, do something different... if the data has all been processed, end the program, else continue to the next data item... while the player has lives left continue the game.

These "things" are called Conditions. Usually this is in the form of a mathematical statment using equals, less-than, or greater-than.

Note: Conditional expressions are usuallyfound inside parentheses.

Remember, all conditions must evaluate to either true or false (i.e., BOOLEAN values).

You can combine more than one condition into a single condition (using AND or OR) as long as in the end, the expression only produces one value (true or false).

Examples of Conditional Boolean Expressions

	
	 ( money < 5 )               

	 ( loop_counter < length_of_loop )               

	 ( rent > 300  )

	 ( test_score > 80 && grade_level == 5 )
	
      

The stuff inside the parentheses of the if statement is called the condition. A condition must evaluate to either true or false. Usually we use the greater than or less than or equal-equals == (equality test) to generate our boolean values.

You can combine more than one condition into a single condition as long as in the end, the expression only produces one value (true or false). Notice the use of && above to mean AND. We use || to mean OR.

The PARENTHESES

The purpose of using parentheses is to set the condition apart from the "if" or "while" keywords, and make our code easier to understand and read!

You should get in the habit of placing () around all Boolean expressions.

Warning: Some lagnuages, such as Matlab, do not require parentheses around a conditional expression. Most languaes like C, Java, and Actionscript do. For the purpose of this class all Conditional Expressions must be placed ( inside of parentheses).


Combining Conditions with AND and OR

Often in a boolean expression, you wish to determine if two things are true, such as, is the value contained by the variable A equivalent to 10, or is it equivalent to 20. If either condition is true then you wish to proceed. To combined multiple conditions into one, you use the && to mean AND or you use the || to mean OR.

Please be aware: Every sub-part of a boolean expression must be a complete boolean expression. Thus if you want to know if A is either 10 or 20, you cannot say: (A == 10 || 20). This is interpreted by the computer as: ( (A == 10) || (20) ). Below is an example of the correct and incorrect ways to combined two queries about the same variable.

Correct version

	    
	  ( ( A == 10 ) || ( A == 20 ) ) % correct
	    
	  

Incorrect version

	    
	      ( ( A == 10 || 20 ) ) % incorrect
	    
	  

Back to Topics List