A program with variables
Back in Xcode, you are going to create another project. First, close the AGoodStart project so that you do not accidentally type new code into the old project.
Now create a new project (File → New → Project...). This project will be a C Command Line Tool named Turkey.
In the project navigator, find this project’s main.c file and open it. Edit main.c so that it matches the following code.
#include <stdio.h> int main (int argc, const char * argv[]) { // Declare the variable called 'weight' of type float float weight; // Store a number in that variable weight = 14.2; // Log it to the user printf("The turkey weighs %f.\n", weight); // Declare another variable of type float float cookingTime; // Calculate the cooking time and store it in the variable // In this case, '*' means 'multiplied by' cookingTime = 15.0 + 15.0 * weight; // Log that to the user printf("Cook it for %f minutes.\n", cookingTime); // End this function and indicate success return 0; }
(Wondering about the \n that keeps turning up in your code? You will learn what it does in Chapter?6.)
Build and run the program. You can either click the Run button at the top left of the Xcode window or use the keyboard shortcut Command-R. Your output in the console should look like this:
The turkey weighs 14.200000. Cook it for 228.000000 minutes.
Back in your code, let’s review what you have done. In the line of code that looks like this:
float weight;
we say that you are “declaring the variable weight to be of type float.”
In the next line, your variable gets a value:
weight = 14.2;
You are copying data into that variable. We say that you are “assigning a value of 14.2 to that variable.”
In modern C, you can declare a variable and assign it an initial value in one line, like this:
float weight = 14.2;
Here is another assignment:
cookingTime = 15.0 + 15.0 * weight;
The stuff on the righthand side of the = is an expression. An expression is something that gets evaluated and results in some value. Actually, every assignment has an expression on the righthand side of the =.
For example, in this line:
weight = 14.2;
the expression is just 14.2.
An expression can have multiple steps. For example, when evaluating the expression 15.0 + 15.0 * weight, the computer first multiplies weight by 15.0 and then adds that result to 15.0. Why does the multiplication come first? We say that multiplication has precedence over addition.
To change the order in which operations are normally executed, you use parentheses:
cookingTime = (15.0 + 15.0) * weight;
Now the expression in the parentheses is evaluated first, so the computer first does the addition and then multiplies weight by 30.0.