Chapter Two: If-Statements

Matthew Campbell, October 9, 2011

If statements are used to execute code based on whether a condition is present in the state of the program. Simply put, an if statement is a way for us to tell a computer to do something if a condition is met and something else if the condition is not met. Below is the general form that an if statement takes.

BOOL condition = YES;
if(condition){
     //take action when condition is YES
}
else{
     //take action when condition is NO
}

The if statement above has three important components: the test to see if the condition is true, the code that will execute if the condition is true and the code that will execute if the condition is false.

BMI Calculator Example

Let’s take a look at how an if statement works in the context of something you might find in a real iPhone app like MyNetDiary or LoseIt!. The example that I am thinking of is a BMI calculator. BMI stands for Body Mass Index. BMI is a statistic used to determine if you are underweight, normal weight, overweight or obese. This statistic is included in many health apps because it is used to determine if someone is at risk of developing health conditions like heart disease.

To calculate BMI you need to know your height and weight. The formula for BMI is weight divided by height squared. Once you have calculated BMI you can figure out whether you are underweight, normal weight, overweight or obese based on your BMI value.

BMI Weight Status
Below 18.5 Underweight
18.5-24.9 Normal
25-29.9 Overweight
30 & Above Obese

What we are going to do in our program is first write code to figure out BMI based on height and weight values that a user will supply to us. Then we will use an if statement to find out whether the BMI stat indicates that the person is underweight. Let’s declare the variables that we need now and set some initial values so that we can test.

float heightInMeters = 1.8796;
float weightInKilograms = 117.934016;
float BMI;

Now we can add in the BMI calculation and assign the result to the BMI float variable.

float heightInMeters = 1.8796;
float weightInKilograms = 117.934016;
float BMI;

BMI = weightInKilograms / (heightInMeters * heightInMeters);


The result that we get with the test data above is 33.3816795. Now what we want to do is compare our BMI statistic with the value from the table above. If our BMI is under the value that determines if we are underweight then our app will do one thing like print out relevant health information. Otherwise, the app will assume for now that the BMI is within normal range.

Relational And Equality Operators

To make this assessment we will need to evaluate the condition using relational and equality operators. These operators are used to evaluate expressions and we include these in the parenthesis after the if keyword in an if statement. Some of the expressions that you can evaluate are equal to, greater than, less than and not equal to. Here are the operators that you have available to you.

Operator Meaning
== Equal To
!= Not Equal To
> Greater Than
< Less Than
>= Greater Than Or Equal To
<= Less Than Or Equal To

Since all we need to do for now is determine whether our BMI is underweight or not we can simply use the less than operator < in our if statement.

float heightInMeters = 1.8796;
float weightInKilograms = 117.934016;
float BMI;

BMI = weightInKilograms / (heightInMeters * heightInMeters);

if(BMI < 18.5){
     //execute if the BMI indicates the person is underweight
}
else{
     //execute if the BMI seems normal (not underweight)
}


If we were writing this app for real we would replace the comments in the if statement above with code that would communicate something of value to the user. The values I supplied above would cause the if statement to execute the code after the else keyword, but the real result would depend on what the user actually enters into the app when it is being used.

Scope

When you need to include more than one line of code as a consequence for an if statement then you must define the scope for a region of code. In programming, scope refers to a region of code that is separated from the rest of the code in the program. This means that variables declared from within that region can only be used inside of that region. Scope is defined with curly braces: a left curly brace defines the beginning of a region of code, and a right curly brace defines the end of a region of code.

In the if statements that we have seen so far the code that executes is always contained in the area constrained by the curly braces to the right of the condition that we evaluate and also right after the else keyword where we put the code that evaluates when the condition is not met.

The thing to remember about scope is that variables that you declare within a region of code can only be used from within that region or from regions of code contained by the parent region. So if you declare a variable in the region of code like the block right after the else keyword you can only use that variable from within that region of code. If you try to use in further down in your program you will get an error warning.

Nested If Statements

So far our BMI example is incomplete since we only have one if statement that is testing whether we are underweight or not. If we were putting something like this into our own app our users would probably want to know what to do if they fell into one of the other categories as well. To get this done we will need to use more if statements.

This referred to as using nested if statements. Nested if statements are used when you need to include more if statements to further test the conditions present in the program. You can use nested if statements by including them in the regions of code after you evaluate your expressions. The general form that this takes looks like this:

BOOL condition = YES;
BOOL anotherCondition = NO;

if(condition){
     //take action when condition = YES
     if(anotherCondition){
          //take action when 
          //anotherCondition = YES
     }
     else{
          //take action when 
          //anotherCondition = NO
     }
}
else{
     //take action when condition = NO
     if(anotherCondition){
          //take action when 
          //anotherCondition = YES
     }
     else{
          //take action when 
          //anotherCondition = NO
     }
}

The example above has new if statements listed in both areas were we can include code. You can nest as many if statements as you need in code. In order to manage the complexity of your code though I would not recommend using more than three layers of nested if statements.

To apply these statements to our BMI example we will need to add a nested if statement to the region of code after the else keyword. What we want to do is test to see if BMI statistic indicates whether the person is normal weight.

float heightInMeters = 1.8796;
float weightInKilograms = 117.934016;
float BMI;

BMI = weightInKilograms / (heightInMeters * heightInMeters);

if(BMI < 18.5){
     //execute if the BMI indicates the person is underweight
}
else{
     //execute if the BMI is not underweight
     
     if(BMI >= 18.5 && BMI <= 24.9){
          //execute if the BMI indicates the person is normal weight
     }
     else{
          //execute if the BMI is not underweight
          //or normal weight
     }
     
}

If you take a look at the if statement condition in the nested if statement you will see that it is bit more complex that the first if statement. We need to determine if the BMI is in a range and to do that we need to employ the logical operator AND which uses the symbol &&. && means AND so we use it when we want to evaluate two conditions both of which must be true in an if statement.

To finish our example we would continue to nest if statements. Our finished product becomes fairly complex when we attempt to include every possibility.

float heightInMeters = 1.8796;
float weightInKilograms = 117.934016;
float BMI;

BMI = weightInKilograms / (heightInMeters * heightInMeters);

if(BMI < 18.5){
     //execute if the BMI indicates the person is underweight
}
else{
     //execute if the BMI is not underweight
     if(BMI >= 18.5 && BMI <= 24.9){
          //execute if the BMI indicates the person is normal weight
     }
     else{
          //execute if the BMI is not underweight
          //or normal weight
          if(BMI >= 25 && BMI <= 29.9){
               //execute if the BMI means the person is over weight
          }
          else{
               //execute if the BMI is obese
          }
     }
}

Logical Operators

In the example above we used the logical operator && because we wanted to make sure that both conditions that we were evaluating were true. We have two more logical operators that we can use in if statements. These two operators are ! and || which mean NOT and OR respectively.

The NOT operator is used to reverse the outcome of a condition. So, if your condition normally would evaluate to false but you wanted it to evaluate to true you could put ! in front of the condition to achieve this. That may look something like this:

BOOL isTrue = YES;
if(!isTrue){
     //this would execute when isTrue == NO
}
else{
     //this would execute when isTrue == YES
}

The OR operator || is used when we want to evaluate a condition when at least one of the conditions is true. In this example I am imagining writing code to test to see if I can get my email or not. I know that to do that I would need to either have a cell coverage or access to a wifi network so this is a perfect time to use the OR operator.

BOOL hasWifi = NO;
BOOL hasCellCoverage = YES;

if(hasWifi || hasCellCoverage){
     //I can get my email since I have
     //either cell coverage or wifi
}
else{
     //no email since I am not connected
}

Hands-On Time

Expand on the idea of creating an app in the health niche by adding information about blood pressure and waist size. Use what you learned in the last chapter to first create a composite type definition that is composed of primitive types to described these attributes: BMI, diastolic blood pressure, systolic blood pressure and waist size. Also include a BOOL variable type called flag to help keep track of whether the person has any warning signs.

Look up the criteria for each of these attributes that may indicate an unusual measurement and use if statements to screen the data for people who may have warning signs for health problems. Use the BOOL variable flag to keep track of whether the data indicates that a person should consult a doctor about their health.

For a real challenge, add the dimension of gender and make sure to apply the appropriate criteria for each gender in your analysis.