TweetFollow Us on Twitter

The Road to Code: The Courage to Start

Volume Number: 23 (2007)
Issue Number: 07
Column Tag: The Road to Code

The Road to Code: The Courage to Start

Take the first step towards programming for Mac OS X

by Dave Dribin

Welcome

Welcome to The Road to Code, a new column about programming on OS X for the non-programmer. My name is Dave Dribin, and I'll be your guide in the issues to come. Unlike a rollercoaster, playing around can't hurt you. In fact, the best way to learn programming is to actually do it. So please, keep your hands and fingers on the keyboard at all times.

Why Program

Before I go into the details of programming, you might be wondering why you would want to program a computer. As a computer user, you no doubt know that the computer is our personal assistant. It helps us stay organized, eases communication with others, and entertains us. Unfortunately, you might also agree that a computer doesn't always work the way we expect. Sometimes a piece of software allows you to do everything except that one thing you need it to do. Other times, software just doesn't exist for the task you are trying to accomplish. The key to harnessing the full power of your personal assistant is to speak to it directly by writing your own programs.

I began programming a long time ago on an operating system far, far away. Apple's DOS 3.3, to be exact, running on an Apple ][+. Once I started programming, I was hooked. The fact that I could tell the computer what to do and it would listen was fantastic. My first programs were very simple, but over the next few years, the programs I wrote increased in complexity.

A year ago, I was going through some of my old 5.25" floppy disks. I came across a number of programs I wrote in Applesoft BASIC: a program to keep track of my (measly) bank account, a blackjack game, and even a program to keep track of my bowling scores. While the finance software and blackjack are not groundbreaking ideas, the bowling program was fairly unique. At the end of our bowling league season, we would get a printout with all of our scores for the entire year, along with a ton of statistics. I was a bowling geek and loved these stats, but I didn't want to wait until the end of the year to see them. So, I wrote a program that would allow me to enter my scores and provide the same statistics without the wait.


Figure 1: My Apple II bowling program

There are a couple of lessons to take away from this. First, start small. I didn't dive right into writing my bowling program. I also found plenty of half-finished work and small, experimental programs on my old disks. Second, practice, practice, practice. The more I programmed, the better I got. Even the little programs that don't do much add to your experience, and that counts for something.

A lot has changed since the days of the Apple ][, with its 1 megahertz processor, 64 kilobytes of memory, and 140 kilobyte floppy disks, but the reasons to start programming have not. Maybe you want to write a program that actually works the way you do, maybe you want to write the next blockbuster game, or maybe you just think it's fun. These are the reasons why I began programming and why I still program today. Whatever your reasons, you should start, too.

What Is Software

Software, also known as a program, is what controls a computer. A computer's sole purpose is to respond to instructions from a program. By writing programs for the computer, you can take full control of your personal assistant. Think of a program as a series of instructions, like a recipe, that the computer follows, step by step. But sometimes even a programmer has trouble communicating with the computer. It is very literal in its interpretation of these instructions. If you don't give them properly, the computer may go off and do something unexpected.

The language used to write programs is called, brace yourself for this, a programming language. Actually, computers are multilingual. Some of the programming languages available on Mac OS X 10.4 are C, C++, Ruby, Python, and Perl. Each language has its own pros and cons. However, the language Apple recommends for writing new OS X software is called Objective-C. Since in this case it's wise to follow the mothership, Objective-C will be the main focus of this column. Objective-C is an extension to C with support for object-oriented programming. You'll get to learn about Objective-C and fancy phrases like "object-oriented programming" in due time, but first we need to build a strong foundation. Since Objective-C is built upon C, I'll cover the basics of C before moving on to Objective-C. As the old saying goes, you've got to learn to walk before you can run.

Time to Code

Before starting to write our first program and in order to follow along, you will need to install Xcode, Apple's free development environment. As of this writing, the current version of Xcode is 2.4.1. It requires Mac OS X 10.4, and is available from Apple's developer website:

http://developer.apple.com/tools/xcode/

You will need to become an Apple Developer Connection (ADC) member, but it does not cost anything to register. Xcode includes all the tools to write Objective-C, including a text editor and a compiler. Even though Objective-C is the language we will be communicating to the computer with, the computer's processor does not understand this language directly. A compiler is needed to translate Objective-C into assembly code, which is the true native tongue of the processor.

With Xcode installed, we can finally start getting our hands dirty and begin coding. We're going to start with what's called a "Hello World" program. This "Hello World" program will print a nice greeting to the user when run, and is often used to introduce programmers to a new language. A word of warning: "Hello World" isn't sexy. In fact, it doesn't even use windows or the mouse. We're going to crawl back into the dark ages for a bit, and we'll be creating console applications, not applications with a graphical user interface (GUI), until we get through the basics. While console applications will run directly in Xcode, they can also be run from the command line using Terminal. But don't get discouraged. We will get to GUI applications soon enough.

Creating Hello World

To create our first program, startup Xcode and select New Project… from the File menu. Xcode provides starting point templates for many kinds of projects. The one we are looking for is Standard Tool under Command Line Utility. For a project name, choose hello_world and choose a suitable directory, such as ~/work/hello_word. After clicking Finish, Xcode will create the project, along with some basic files. Use Figure 2 and Figure 3 as examples.


Figure 2: Creating a new Standard Tool project


Figure 3: Setting the project name and directory

C programs are made up of one or more text files with the ".c" extension called source files. A source file contains the actual programming instructions called source code, often just shortened to source or code depending on the context. This is also why programming is sometimes referred to as coding [Editor's note: if they can be called programmers or coders, could they also be referred to as sorcerers? - jr]. As part of the New Project template, Xcode created a single source file named main.c. To view this file, expand the Source item in the left pane, and select the main.c item. Next, click on the Editor toolbar icon. Your window should look similar to Figure 4.


Figure 4: main.c source file in Xcode

You will notice that this file is not empty. As it turns out, Xcode creates a ready-to-run "Hello World" every time we create a new project. This is handy for us because it means we don't even need to type anything to get started. Click on the Build and Go toolbar icon to compile and run the program. If all goes well, you should get a Run Log window with the Hello, World! message on line 2 similar to Figure 5.


Figure 5: Hello World Run Log

Let's start picking this program apart line by line. The programming instructions are listed in the order you want them to execute. You can think of these instructions, called statements, as sentences, except instead of using a period to mark the end of a sentence, C uses a semicolon to mark the end of a statement. Not every line contains executable statements, though. Sometimes, the code contains extra information about the program for the compiler, and other times it contains extra information for the programmer. For example, Line 4 starts with two slashes, and is what is called a comment. The compiler ignores the two slashes and any text after them. You can put whatever you want in comments, but they should be used to make the program more understandable for someone reading the program.

On line 5, you have a statement that looks like:

   printf("Hello, World!\n");

This is what is known as a function call. A function in C is a set of statements that can be reused over and over again. A function call executes the function's statements. When the function finishes, the program picks up where it left off before the function call.

In this function call, printf is the name of the function to execute, and the text between the parentheses is the function's arguments. Arguments are used as inputs to the function allowing you to customize how it behaves. The text between the double quotes is called a string. The printf function is part of the Standard C library, and displays a message to the console. It expects a string argument and uses that string as its message.

First Steps

To get a better understanding, let's modify this program a bit. Change this line of code to:

   printf("My favorite number is %d\n", 7);

Now build and run the program, and the output in the Run Log should show:

My favorite number is 7

Now it's getting interesting. This time we passed two arguments to printf, the first a string, and the second a number. You'll notice that instead of printing %d, it replaced that with 7. This is where the "f" part of printf name comes from: formatted printing. The string passed to printf is called a format string, and is used like a template to format the final message. In the example above, %d is a placeholder for an integer number. An integer is a number without decimal points. Format strings could be a topic in itself, but here is another example showing how to use strings and floating point numbers (numbers with a decimal point):

   printf("Hello %s.\nMy lunch cost $%.2f.\n", "Dave", 7.5);

The output of this is:

Hello Dave.
My lunch cost $7.50.

You can see the %s is replaced with the string Dave and the %.2f is replaced with 7.50. This also shows how you can customize the formatted output. The .2 tells printf to always use 2 places after the decimal point. The final piece of magic going on is the string \n. printf replaces this string with a newline, which is why our output shows up on two lines. You almost always want one of these at the end of your format string, but I wanted to show explicitly what \n does and that you can put them anywhere in your string.

Congratulations! You're now programming! Try replacing the string "Dave" with your own name, and try printing out other numbers. Remember, it helps to experiment.

Variables

Variables are the next key concept to understand. Think of variables as containers that hold stuff, like storage boxes that you may have around the house. These boxes can hold different items, such as books and clothes. In order to keep things organized, your boxes may also have labels, like "Science Fiction", so you know what it contains. Similarly, variables can hold different values, such as numbers and strings and they also have labels to help keep things organized. Let's replace the entire main.c of our earlier program with Listing 1.

Listing 1: main.c demonstrating variables

#include <stdio.h>
int main(int argc, const char * argv[])
{
   int myVariable;
   myVariable = 5;
   printf("The number is %d\n", myVariable);
   myVariable = myVariable*2;
   printf("The number is now %d\n", myVariable);
   
   return 0;
}

In C, every variable must be declared before it's used, so the compiler is aware of it. The statement on line 3 is called a variable declaration, and it tells the compiler the variable's label, called a name, and type. This variable is named myVariable and its type is int, for an integer. Why do we need the type? Back to the box analogy, variables in C are like boxes with strict rules. Boxes that are designed to hold books cannot hold clothes, and boxes designed to hold clothes cannot hold books. Thus, an integer variable can hold any integer, but not any other type, such as floating point numbers or strings. This may seem silly, but one benefit to including the type with every variable is it allows the compiler to tell you when you've made a mistake. Just as your parents will tell you if you are putting your books in your clothes box and make you fix it, the compiler will not let you put a string in an integer variable.

You can change the contents of a variable with an assignment statement using an equal sign. The first assignment statement sets the contents of the variable, myVariable, to five. The second assignment statement shows that you can use a mathematical expression on the right hand side of the equal sign. In this case the asterisk (also called a star) means we are multiplying the original number in myVariable, five, by two. The resulting output of this program is:

The number is 5
The number is now 10

A Brief Interlude on Expressions

You can use any of the common arithmetic operations summarized in Table 1 as part of a mathematical expression, and you can use parenthesis to prioritize multiple operations. Take this expression, as an example:

   myVariable = (myVariable+1)*2;

First, one is added to myVariable and then the result is multiplied it by two. If myVariable starts off as five, it will be set to twelve by this statement. Without parenthesis, the standard operator priority is observed. In this case, one is multiplied by two first, and then the result is added to myVariable resulting in myVariable being set to seven. It's usually a good idea to add parentheses to any complex expression to avoid confusion.

Table 1: Arithmetic Operations By Priority

Operation   C Syntax   
              Multiply      *   
              Divide        /   
              Add           +   
              Subtract      -   

Variety is the Spice of Life

Variables are an extremely important part of not only C programming, but also any programming language. Now that you know the basics of variables, try changing the name of myVariable to something else or adding new variables. Also, try out different mathematical expressions. Keep in mind that variable names have certain restrictions. You may only use letters, numbers or the underscore character ("_"), and they must not begin with a number.

Your Own Functions

The Standard C library contains other functions besides printf, but as your program starts getting larger, you will want to write your own custom functions. Usually this is because you want to use the same code without duplicating it, but sometimes you will use functions to make your programs easier to understand. Let's say that we will be printing our Hello, World! message multiple times. We can put this code in our own function, and then call it multiple times. Modify main.c to match Listing 3.

Listing 3: main.c demonstrating custom functions

#include <stdio.h>
void printMessage(void)
{
   printf("Hello, World!\n");
   return;
}
int main(int argc, const char * argv[])
{
   printMessage();
   printMessage();
   return 0;
}

If you build and run this program, you should see our message printed twice:

Hello, World!
Hello, World!

Notice that we typed our function before using it — it precedes its use in the program. This is called defining a function. Like variables, you must always tell the compiler about the function ahead of time. The very first line of a function is called a function signature. The function signature specifies the name of the function, the name and type of each argument, and the type of the return value. Let's look at our function signature:

void printMessage(void)

Our function name is printMessage. It doesn't take any arguments, so we use (void) to specify this. The first void before the function name means our function does not have a return value. We will get more into arguments and return values in a bit.

After the function signature comes the function body. The function body always begins and ends with curly braces, { and }. Inside the braces are the function's statements. The body of the printMessage function contains two statements. The first calls another function, printf. And the second is a return statement. A return statement marks the end of a function, and causes the program to return to the place where the function was called. While you may include statements after the return statement, they won't get executed. The return statement is optional for functions without a return value, so we could have written this function with one statement as:

void printMessage(void)
{
   printf("Hello, World!\n");
}

Arguments and Return Values

As I mentioned earlier, functions may have arguments and return values to customize their behavior, similar to a mathematical function. Modify main.c to match Listing 5.

Listing 5: main.c demonstrating function arguments and return values

#include <stdio.h>
int squareNumber(int number)
{
   int square;
   square = number*number;
   return square;
}
int main(int argc, const char * argv[])
{
   int number;
   number = 5;
   printf("The number is %d\n", number);
   number = squareNumber(number);
   printf("The number is now %d\n", number);
   
   return 0;
}

If you build and run this program, you should get the output:

The number is 5
The number is now 25

The function signature of the squareNumber function is different from the printMessage function in that the return type has changed from void to int, and the arguments have changed from (void) to (int number). This states that our function expects to take one integer argument and return an integer value. Inside the body of our function, we multiply the number by itself and store this result in a new integer variable called square. This time, the return statement itself takes an argument, which is used as the return value.

Local Scope of Function Variables

Function arguments themselves are variables. Thus, instead of creating a new variable, we could have shortened our function to:

int squareNumber(int number)
{
   number = number*number;
   return number;
}

Notice that even though we are changing the number variable in the squareNumber function, we still have to set the number variable in the main function. This is because each function has it's own set of variables that are independent from other functions. Variables defined in a function are called local variables. Local variables are only available for use inside the function they are declared in and do not conflict with variables defined in another function. They are essentially different boxes that just happen to have the same label. The concept of which variables are available is called variable scoping. We will cover more about variable scoping over time.

As it turns out, we don't even have to bother using the number argument as a variable. We can just do the multiplication directly in the return statement:

int squareNumber(int number)
{
   return number*number;
}

Multiple Arguments

Functions may take more than one argument by separating each one with a comma:

int multiplyNumbers(int number1, int number2)
{
   return number1*number2;
}

This states that you must pass two arguments when calling multiplyNumbers, for example:

   number = multiplyNumbers(number, 3);

Now that you know how to define your own functions, it's time again to experiment. If you are writing your own functions, keep in mind that the same restrictions described above for variable names also apply to function names. Try creating a function that takes three floating-point number arguments and returns the average of them. I'll give you a hint, especially since I haven't mentioned how to specify floating point number variables and return values, yet. Here's a function signature:

float threeNumberAverage(float number1, float number2, float number3)

Notice that I used float as type for the arguments and return value. Try and fill in the function body yourself.

Tying Up Loose Ends

Before wrapping up, I want to cover a couple points I've been skirting around. Now that you know how to define functions, you'll notice that we've actually been defining two functions in the last few examples. The second function is named main, and main is a special function. The operating system always calls main when a C program starts executing, and is called the entry point of your program. You'll notice that the signature for main has two arguments and a return value. The arguments use somewhat advanced types like an array of strings, which you can ignore for now. The integer return value is sent to the operating system when your program exits. The operating system then sends this value to the program that started your program. For example, if you change the return value to something other than zero, you will see this reflected in the Xcode Run Log window as the status. Be careful, though. Returning a number other than zero from main is typically used to indicate that something in your program went wrong. I suggest always returning zero, for now.

The second point I've skirted around is the very first line of every example:

#include <stdio.h>

Remember how I said that all functions must be defined before use? Well you may be wondering why we can call printf without a definition. This first line tells the compiler to include another source file named stdio.h. This source file, which is short for "standard input and output", contains the definitions for all of the Standard C library functions that pertain to input and output. Notice that this source file has a ".h" extension instead of ".c". This is a special source file called a header file. We will be learning more about header files, but for now, you need to remember to have this line in your source files, if you plan to use printf.

Conclusion

Phew! You made it through this first article, and you've already learned a lot about C programming. I'll reiterate what I said about practice. Take what you've learned about functions and variables and see what you can do. It doesn't hurt to experiment. You'll probably run into problems, but that's all part of the learning process.

Learning something new can be overwhelming. I started running a couple years ago, after being mainly inactive my entire adult life. When I was getting started, I read an inspirational book called The Courage To Start, by John "The Penguin" Bingham (Bingham 1999). A key point John makes is that the hardest part about starting to run at the age of forty-three is taking the first step. This advice holds true to learning anything new, no matter what your age is, though. Don't let that first step scare you. The next time you are cursing at your computer for not being a good personal assistant, take a moment and think. You could wait for an existing piece of software to be enhanced or a new piece of software to emerge, which is what most people do. But if you know how to program, you could write it yourself. Embrace that first step, and I'll see you next month.

Bibliography

Bingham, John. The Courage to Start: A Guide to Running for Your Life. 1999.


Dave Dribin has been writing professional software for over eleven years. After five years programming embedded C in the telecom industry and a brief stint riding the Internet bubble, he decided to venture out on his own. Since 2001, he has been providing independent consulting services, and in 2006, he founded Bit Maki, Inc. Find out more at http://www.bitmaki.com/ and http://www.dribin.org/dave/>.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.