Thursday, May 26, 2011

Programming term - If/Else Statements

Definition:

A conditional statement/expression or construct that perform different actions depending on whether a boolean condition evaluates to true or false.

Conditional statements are used to perform different actions based on different conditions. A boolean condition has only two values - either true or false. For example:

boolean tree = true;

This can indicate whether a particular condition is true, but can also be used to represent any situation that has two states, such as a lightbulb being on or off. 




The if statement consists of the word if followed by a boolean expression, followed by a statement. The condition is enclosed in brackets and must evaluate to either true or false. If the condition is true, then the statement is executed and the processing continues with any statement that follows. If the condition is false, the statement controlled by the condition is skipped, and processing continues immediately with any statement that follows. 

Example:
  if (cMoney < totalMoney) {
             cMoney = cMoney + 20;
}                                        

This is saying that if the cMoney is less than the totalMoney then add 20 to the cMoney and put that value back into cMoney until the condition turns false and reaches the total amount of money. If this condition is originally false, ie. the cMoney is equal or greater than the totalMoney, then it will skip over it to any other processing that concedes it. 


The next part of this is the else statement which gives a true and false condition. 

Example:
if (cMoney < totalMoney) {
             cMoney = cMoney + 20;
  }else{                                    
                                            String limit = "You have reached the limit"       

This is saying the same thing except it adds the else component which means that if the first statement is false, it automatically defer to the else statement where it will say "You have reached the limit".    


The last part of this term is the if..else if..else statements that can be used to select one block of code when there are multiple options. This can be used infinitely.

Example: 
 
if (cMoney < totalMoney) {
             cMoney = cMoney + 20;
          }else if (cMoney > totalMoney) {
             cMoney = cMoney - 20;
}else{                                  
                                            String limit = "You have reached the limit"       

This is adding another condition when the first one is false. It is saying that if the cMoney is not less than totalMoney  but greater than it, then it will minus 20 from the cMoney and replace it with that value, then continue on with the rest of the code after the conditions. 



One last thing about if/else statements are nested if's. This means that there are if statements inside the original if statements which means there are two conditions for the code to pass.


No comments:

Post a Comment