iOS For High School Students: Getting Started

This is a blog post by Connor Osborn, an aspiring student with a passion for creating software and 2d games! This is a new tutorial series on beginning programming for iOS – for high school students, by high school students! We’ll walk you through creating an app from the very beginning, assuming zero knowledge! And we’ll make […] By .

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 4 of this article. Click here to view the first page.

Programming with Logic: If Statements

The next step requires the computer to print a message based on the skill set of the user. This requires us to write some logic code. In plain English, we want to tell the computer to do the following, for example:

  • If speed and intelligence are both really high, then print the message, “You are an assassin.”
  • If strength is really high, then print the message, “You are a troll.”

Let’s take this a step further and create a better example that uses numbers to define what is “really high”:

  • If strength is greater than or equal to 7, and intelligence is greater than or equal to 7, and the average of the user’s alchemy skill and speed is less than 7, then print: “You are a clever brute. You are known for your defense of Aristotle’s logic, while being equally admired by competent athletes. In the gladiator ring, your intelligence outmatches beings of even greater strength.”

Below is the snippet of code that executes the above paragraph. It uses something called an if-then statement. See if it makes sense. It’s something new, but you should be able to make some connections. :]

if (strength >= 7 && intelligence >= 7 && (alchemy_skill + speed)/2 < 7)
     {
     NSLog(@"You are a clever brute. You are known for your defense of Aristotle's logic, while being equally admired by competent athletes. In the gladiator ring, your intelligence outmatches beings of even greater strength.")
     }

In case you're confused, a few things to keep in mind. The "if" conditions are all within the first set of parentheses (). The twin ampersands ("&&") simply mean "and." Every condition linked by && has to be met to trigger the "then" statements, which follow in the brackets {}.

We are going to take this (and a bunch of other if-then statements) and paste them into our program after the declarations of our sum and avg variables.

//
//  main.m
//  Are You A WIZARD?
//
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

     //These are the different variables that will be evaluated to generate responses. 
     float strength, intelligence, speed, alchemy_skill, sum, avg;
	
     //I included (1-10) so that users would know how to answer
     NSLog (@"What is your strength (1-10)?");
     scanf ("%f", &strength);

     NSLog (@"What is your intelligence (1-10)?");
     scanf ("%f", &intelligence);
	
     NSLog (@"What is your speed (1-10)?");
     scanf ("%f", &speed);
	
     NSLog (@"What is your alchemy skill level (1-10)?");
     scanf ("%f", &alchemy_skill);

     sum = strength + intelligence + speed + alchemy_skill;
     avg = (strength + intelligence + speed + alchemy_skill)/4; 

     //Here are the logical statements that determine a response based on the user's input for various skills!
     if (strength >= 8 && intelligence >= 8 && (alchemy_skill + speed)/2 < 7)
     {
     NSLog(@"You are a clever brute. You are known for your defense of Aristotle's logic, while being equally admired by competent athletes. In the gladiator ring, your intelligence outmatches beings of even greater strength.");
     }
     if (speed >= 8 && intelligence >= 8 && (alchemy_skill + strength)/2 < 7) 
     {
     NSLog(@"You are an assassin. Your sharp blade and agile mind gleam in the shadows. Being not particularly confrontational, you wear an aura of mystery.");
     }
     if (alchemy_skill >= 8 && intelligence >= 8 && (strength + speed)/2 < 7)
     {
     NSLog(@"You are a cleric. You summon mysterious powers to heal and protect.");
     }
     if (avg >= 8 && avg <= 9)
     {
     NSLog(@"You are a mage, apprenticed to a great wizard. One day you may be a master of the universe.");
     }
     if (avg >= 5 && avg <= 7)  
     {
     NSLog(@"You are a commoner. You will live a long life, and tend to your property.");
     }
     if (avg >= 1 && avg <= 4) 
     {
     NSLog(@"You are a peasant. Your lord is cruel. He does not compensate you for the work that you accomplish. You only dream of being successful. :(");
     }
     [pool drain];
     return 0;
}

Solving Problematic Inputs with While Loops and Else Statements

Well, our program is pretty cool, but there are a few setbacks preventing it from being a killer program. Run the program a few times, and each time use one of the below sets of input:

  • (12, 14, 56, 2)
  • (8, 8, 4, 4)
  • (10, 10, 10, 10)

Let's first discuss the following problematic inputs (12, 14, 56, 2). Here's what our current program does with these inputs:

Although in the print statements we declared that answers ought to range from (1-10), the reality is that the user can input whatever they want. If they input answers outside of the range (1-10), the program ceases to function. :O

As the rage comic indicates, we need something called a while loop to overcome those inclined to rebellious behavior. The idea behind the while loop is this:

While people answer values we don't want, tell them they're stupid, and make them answer the question again. (Just kidding :p)

While strength is greater than 10 or strength is less than 1, then print: "Your answer is deceitful! What is your strength?" Next, use scanf() to allow them to retry their input. This should make sense when you read the code below.

while(strength>10||strength<1) 
     {
     NSLog(@"Your answer is deceitful!");
     NSLog(@"What is your strength (1-10)?");
     scanf("%f", &strength);
     }

Note that || means "or."

You might be asking what is the difference between a while statement (often called a while loop) and an if-then statement.

if(strength>10||strength<1) 
     {
     NSLog(@"Your answer is deceitful!");
     NSLog(@"What is your strength (1-10)?");
     scanf("%f", &strength);
     }

An if statement runs once. After the completion of its conditions (strength>10 or strength<1) it runs its statements and concludes. If we code the program with the if statement, answer 57 the first time we are asked to input our strength and 64 the second time, we get the following output:

Notice that the if statement ends and stores 64 as a legitimate value of strength. :(

We simply need to add a while loop for every variable that needs an input of value 1-10. Write out the while loops, then check your code with what is below. Run the program and test entering input outside of the range of (1-10). The while loop prevents the user from advancing until conditions are met.

//
//  main.m
//  Are You A WIZARD?
//

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

     //These are the different variables that will be evaluated to generate responses.
     float strength, intelligence, speed, alchemy_skill, sum, avg; 
    
     NSLog(@"What is your strength (1-10)?");
     scanf("%f", &strength);
    
     //Each while statement is designed to make sure that inputs for each question are between 1 and 10
     while(strength>10||strength<1) 
          {
          NSLog(@"Your answer is deceitful!");
          NSLog(@"What is your strength (1-10)?");
          scanf("%f", &strength);
          }

     NSLog(@"What is your intelligence (1-10)?");
     scanf("%f", &intelligence);
    
     //Each while statement is designed to make sure that inputs for each question are between 1 and 10
     while(intelligence>10||intelligence<1) 
          {
          NSLog(@"Your answer is deceitful!");
          NSLog(@"What is your intelligence (1-10)?");
          scanf("%f", &intelligence);
          }

     NSLog (@"What is your speed (1-10)?");
     scanf ("%f", &speed);

     //Each while statement is designed to make sure that inputs for each question are between 1 and 10
     while(speed>10||speed<1) 
          {
          NSLog(@"Your answer is deceitful!");
          NSLog(@"What is your speed (1-10)?");
          scanf("%f", &speed);
          }

     NSLog (@"What is your alchemy skill level (1-10)?");
     scanf ("%f", &alchemy_skill);

     //Each while statement is designed to make sure that inputs for each question are between 1 and 10
     while(alchemy_skill>10||alchemy_skill<1) 
          {
          NSLog(@"Your answer is deceitful!");
          NSLog(@"What is your alchemy_skill (1-10)?");
          scanf("%f", &alchemy_skill);
          }

     sum = strength + intelligence + speed + alchemy_skill;
     avg = (strength + intelligence + speed + alchemy_skill)/4; 

     //Here are the logical statements that determine a response based on the user's input for various skills!
     [...]

Our program is significantly more sound because of the while loops.

All right, let's move on to the next problematic output, (8, 8, 4, 4). (We are almost to the coolest part of the program!) Here's what we get:

For a single set of input, we get two outputs. :( This means that some of the conditions for our if statements are overlapping. The input (8, 8, 4, 4), in that order, means the user is a clever brute. However, it just so happens that the average of (8, 8, 4, 4) also generates the response: You are a commoner.

There are several other inputs that also generate two responses. But we don't have to test every possible input with each if statement. We just have to use something called an else statement. Let me explain how they work in simple terms.

  • if (trees are green)
  • then (teach kids that trees are green)
  • else (teach kids that trees have something covering them)

We can also use an else-if statement. A clever brute could make sense of the code below. Can you? :]

  • if (trees are green)
  • then (teach kids that trees are green)
  • else if (trees are white)
  • then (teach teach kids that trees have snow on them)

When I designed the program, knowing that sometimes two answers would be generated, I decided to use a bunch of else-if statements. Use the image below to understand how else-if statements and else statements work.

In the series of if statements in the picture, the arguments only go out the horizontal tubes if they pass the condition. Once they pass the condition they are no longer considered. Immediately after the first statement, x is taken out of the running.

Else statements and else-if statements can only follow after an if statement. At the beginning of every new if statement, all variables are considered again.

If, else, and else-if statements are incredibly important. All you have to do now is look the if statements that should already be in your code. Keep the first one as an if statement and make each of the ones following an else-if statement. Look below for reference. All you are doing is creating the vertical tube illustrated in the picture. :)


     if (strength >= 8 && intelligence >= 8 && (alchemy_skill + speed)/2 < 7) 
     {
     NSLog(@"You are a clever brute. You are known for your defense of Aristotle's logic, while being equally admired by competent athletes. In the gladiator ring, your intelligence outmatches beings of even greater strength.");
     }
     else if (speed >= 8 && intelligence >= 8 && (alchemy_skill + strength)/2 < 7) 
     {
     NSLog(@"You are an assassin. Your sharp blade and agile mind, gleam in the shadows. Being not particularly confrontational, you wear an aura of mystery.");
     }
     else if (alchemy_skill >= 8 && intelligence >= 8 && (strength + speed)/2 < 7)
     {
     NSLog(@"You are a cleric. You summon mysterious powers to heal and protect.");
     }
     else if (avg >= 8 && avg <= 9)
     {
     NSLog(@"You are a mage, apprenticed to a great wizard. One day you may be a master of the universe.");
     }
     else if (avg >= 5 && avg <= 7)  
     {
     NSLog(@"You are a commoner. You will live a long life, and tend to your property.");
     }
     else if (avg >= 1 && avg <= 4) 
     {
     NSLog(@"You are a peasant. Your lord is cruel. He does not compensate you for the work that you accomplish. You only dream of being successful. :(");
     }

Now when you input (8, 8, 4, 4), you only get one output. :D