If statements allow you to run one set of code if a certain condition is met, and another set of code if another condition is met
For example, you may want to write a piece of code that only prints the output of a value less than 1, or if you want to add together two numbers only if they are positive
The basic format of the if statement looks like this:
if (test condition) {
statements if true;
}
statements;
The final statements are run regardless of the if statement (they are outside the {} ) the first set of statements are executed only if the test condition is met
Test Conditions
Test Conditions are boolean expressions (results in either "True" or "False") that typically use relational operators like:
!= not equal
> greater than
< less than
>= greater than or equal to
<= less than or equal to
The && operator can be used to combine 2 test conditions together
int x = 10;
if(x<20) && (x>1) {
x=x+10;
}
In this example the value of x is tested to see if it is less than 20 AND greater than 1 before it will execute the +10 addition, both conditions must be true
Logical Operators that can be used include:
&& And (x<20) && (x >1)
|| Or (x>5) || (x==2)
! Not !(x==10)
Stacking If Statements
In this example, the correct table size is selected based on the number of people attending
if (people <= 2) {
tableSize="3feet x 3feet";
} else if (people<=6){
tableSize="3feet x 6feet";
} else if (people <=8) {
tableSize="3feet x 9feet";
} else { tableSize="There are too many people"
}
Questions to consider when constructing if statements
How many different outcomes are possible?
Is there a need for output when none of the included conditional statements are true?
Can you combine conditional statements to get the right answer faster?
Are there redundant conditional statements?
No comments:
Post a Comment