Learn to Code iOS Apps 1: Welcome to Programming

Learn to code iOS apps using Apple’s development tools. For complete beginners – no prior programming experience needed! By Mike Jaoudi.

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

Working With Variables

Computers are terribly good at remembering pieces of information such as names, dates, and photos. Variables provide ways for you to store and manipulate these types of objects in your program. There are four basic types of variables:

  • int: stores a whole number, such as 1, 487, or -54.
  • float: stores a floating-point number with decimal precision, such as 0.5, 3.14, or 1.0
  • char: stores a single character, such as “e”, “A”, or “$”.
  • BOOL stores a YES or NO value, also known as a “boolean” value. Other programming languages sometimes use TRUE and FALSE.

To create a variable — also known as declaring a variable — you simply specify its type, give it a name and optionally provide a default value.

Add the following line of code to main.m between the @autoreleasepool line and the NSLog line:

    int num = 400;

Don’t forget that all-important semicolon!

The line above creates a new integer variable called num and assigns it a value of 400.

Now that you have a variable to use in your app, test it out with an NSLog statement. Printing out the values of variables is a little more complicated than printing out strings; you can’t just put the word “num” in the message passed to NSLog and see it output to the console.

Instead, you need to use a construct called format specifiers which use placeholders in the text string to show NSLog where to put the value of the variable.

Find the following line in main.m:

NSLog(@"I can write anything I want!");

…and replace it with the following line of code:

NSLog(@"num equals %i", num);

Click the Run button in the upper left corner. You should get a message in the console that says:

num equals 400

That looks great — but how did Xcode know how to print out the value of num?

The %i in the code above is a format specifier that says to Xcode “replace this placeholder with the first variable argument following this quoted string, and format it as an integer”.

What if you had two values to print out? In that case, the code would look similar to the following:

NSLog(@"The two variables are %i and %i", num1, num2);

Okay, so %i is used for integer formatting. But what about other variable types? The most common format specifiers are listed below:

  • %i: int
  • %f: float
  • %c: char

There isn’t a specific format specifier for boolean values. If you need to display a boolean value, use %i; it will print out “1” for YES and “0” for NO.

Along with declaring variables and setting and printing values, you can also perform mathematical operations directly in your code.

Add the following line to main.m, immediately below the int num = 400; line:

num = num + 100;

The above code takes the current value of num, adds 100 to it, and then replaces the original value of num with the new sum — 500.

Press the Run button in the upper left corner; you should see the following output in your console:

num equals 500

That’s enough theory to get started — you’re probably itching to start coding your first real app!

Building Your First Game

The application you’ll create in this tutorial is the classic game “Higher or Lower”. The computer generates a secret random number and prompts you to guess what that number is. After each successive guess, the computer tells you if your guess was too high or too low. The game also keeps track of how many turns it took for you to guess the correct number.

To get started, clear out all of the lines in the @autoreleasepool block of main.m so that main looks like the code below:

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        
        
    }
    return 0;
}

All the code you add in the steps below will be contained between the curly braces of the the @autoreleasepool block.

You’re going to need three variables: one to store the correct answer, one to store the player’s guess and one to store the number of turns.

Add the following code within the @autoreleasepool block:

    int answer = 0;
    int guess = 0;
    int turn = 0;

The code above declares and initializes the three variables you need for your game. However, it won’t be much fun to play the game if answer is always zero. You’ll need something to create random numbers.

Fortunately, there’s a built-in random number generator, arc4random, which generates random numbers for you. Neat!

Add the following code directly below the three variable declarations you added earlier:

answer = arc4random();
NSLog(@"The random value is %i", answer);

answer now stores a random integer. The NSLog line is there to help you test your app as you go along.

Click the Run button in the upper left corner and check your console output. Run your app repeatedly to see that it generates a different number each time. It seems to work well, but what do you notice about the numbers themselves?

The numbers have a huge range — trying to guess a number between 1 and 1228691167 doesn’t sound like a lot of fun. You’ll need to scale those numbers back a little to generate numbers between 1 and 100.

There’s an arithmetic operator called the modulo operator — written as % in Objective-C — that can help you with this scaling. The modulo operation simply divides the first number by the second number and returns the remainder. For example, 14705 % 100 will produce 5, as 100 goes into 14705 a total of 147 times, with a remainder of 5.

To scale your values back between 1 and 100, you can simply use the above trick on your randomly generated numbers. However, if you divide the randomly generated number by 100, you’ll end up with numbers that range from 0 to 99. So, you simply need to add 1 to the remainder to get values that range from 1 to 100.

Find the following line in your code:

answer = arc4random();

…and modify it to look like the line below:

answer = arc4random() % 100 + 1;

Run your app a few times and check the console output. Instead of huge numbers, your app should only produce numbers between 1 and 100.

You now know how to create and display information to your user, but how do you go about accepting input from the user to use in your app?

That’s accomplished by the scanf function — read on to learn how it works.

Mike Jaoudi

Contributors

Mike Jaoudi

Author

Over 300 content creators. Join our team.