Recent Changes - Search:

TEAMS Academy Wiki

THS 2011-2012

Explore TEAMS!
for visiting sophomores & juniors

Bodies & Bones

Interactive Robotics

Environmental BioTech

Bat Engineering Design

Assistive Technology & Electronics

Students (Forum)

Instructors

School Calendar

FY09 Planning

TEAMS Web Site

Wiki Info

edit SideBar

Using Variables

Notice
The Command Module cannot use float type variables. Floating point numbers require extra circuitry on the processor chip, which normal PC's have. The microprocessor in the Command Module, however, does not have this circuitry.

To store and manipulate data in your program, you need to create Variables. To create a variable, you must use the following form:

type_modifier variable_type variable_name;

variable_name can be anything of your choosing, so long as it begins with a letter or underscore, and doesn't use any special characters (like semicolon, which would end the statement).
variable_type is the kind of data you want to create, which can be one of the following:

  • int - integer: a whole number. (ex: 1, 5, -10)
  • float - floating point value: a number with a fractional part. (ex: 1.0, 0.25, 3.333)
  • double - a double-precision floating point value. (ex: 12.534, 2.563x1015, 5.332x10-12)
  • char - a single character. (ex: 'A', 'c', '@')
  • void - valueless special purpose type. One possible use of void, as you have seen in the HelloWorld program, is to have a function (the main function) which does not need data as input (void = nothing).

Let's write a small segment of a program that uses variables to do some math and then display the results to the screen. In addition to learning about variables, you'll see how printf can be used to display them. Make sure you understand the operations on variables, because you won't be able to use printf with your robot.

First, lets create (we can also say instantiate) our variables.

       int x;
       int y;
       int z;
       int result;
       float average;

These statements will tell the compiler to set aside some memory for data. We have 4 variables that store integers, and 1 variable that stores a floating point (real) number.
Now, lets give some of these variables a value (also called initialization) by using the assignment operator: an equals sign.

       x = 2;
       y = 2;
       z = 0x0B;

We used both decimal and hexadecimal numbers to assign our variables with values. Either way, it is stored in binary format in memory, but we don't need to worry about that; the value is the same no matter the format.
What if we had performed the assignment result = 1.5;? Is this correct? No, because 1.5 is a floating point value, but result is an integer type variable. This is one example of a type mis-match, and they are generally not allowed.

Do you understand how to create and initialize variables now? If so, take a look at this shortcut:

int x = 2;
int y = 2, z = 11, result;
float average;

We can create and initialize multiple variables in the same statement, as long as they are the same type. It is always a good idea to initialize variables as soon as possible. If you try to use a variable before you have initialized it, it's value could be anything (and would probably be meaningless junk).

Now, lets try some mathematical operations with our variables. We should remember to put a semi-colon at the end of each statement.

Line#
  1     x + y;       // 2 + 2
  2     y - x;       // 2 - 2
  3     x * (x + 2); // 2 * (2 + 2)
  4     y / x;       // 2 / 2
  5     z / (y + 1); // 11 / (2 + 1)

For doing math problems, C has an order of operations identical to the mathematical order. Since C has some extra operations besides the standard math operations, they need to have a place in the order as well. Don't worry about those yet, since they won't interfere in basic math computations like these.

Will all these C statements compile? Yes (remember, comments are ignored by the compiler). Will any of these C statements be useful? No. Why?
When these operations are performed, where does the result of the computation go? Our code did not say where to store the result of the computation, so the results are gone. We need to use the assignment operator here as well, and choose a variable to put the result.

Line#
  1     result = x + y;       // result = 2 + 2
  2     result = y - x;       // result = 2 - 2
  3     result = x * (x + 2); // result = 2 * (2 + 2)
  4     result = y / x;       // result = 2 / 2
  5     result = z / (y + 1); // result = 11 / (2 + 1)

Now, the results of the computations are being stored in the result variable. What will happen to the value of result each time a new computation is performed? It will be overwritten. In that case, what is the value stored in result after all these computations are complete? Mathematically speaking, the result of (11 / (2 + 1)) is 3.666666, which is a floating point number. Does that mean the code on line 5 causes a type mis-match? The answer is, in fact, no. The C compiler can see that it is dealing with integers and division, so it takes the easy way out and drops the remainder of the division, resulting in an integer value. The value stored in result is 3.

So, what would happen if we replaced line 5 with average = z / (y + 1);? The value stored in average will actually still be 3.0. Why? Since there are integers being used in division, the remainders are being dropped during the computation, which means the value is an integer. Once again, the compiler is versatile enough to convert the integer into a floating point value, and doesn't produce a hard error. The result of the computation will still contain inaccuracy, even though the storage variable type is floating point. This is another important example of why it is important to match your types: big problems my still exist even when a hard error is not generated by the compiler.

Now lets use the printf function to make sure the result of the computations are what we think they are.

result = x + y;
printf("x + y = %d \n", result);

result = y - x;
printf("y - x = %d \n", result);

result = x * (x + 2);
printf("x * (x + 2) = %d \n", result);

result = y / x;
printf("y / x = %d \n", result);

average = z / (y + 1);
printf("z / (y + 1) = %f \n", average);

The exact output will look like this:

x + y = 4
y - x = 0
x * (x + 2) = 8
y / x = 1
z / (y + 1) = 3.000000

Displaying Variables with printf

The printf function is looking much different here than it looked in HelloWorld, but don't get discouraged. We'll take it a step at a time.
Each printf function call still contains a string (delimited by double-quote pairs " ") as one if it's arguments, which determines exactly what is displayed to the screen. Each function call also contains one additional argument: the value of result or the value of average. Where does the value get inserted into the string? Notice the "%d" or "%f" in each string argument. The printf function will look through it's string argument, from left to right, for '%' characters, and when it finds one, it will look at the character(s) directly following the '%' to determine how it should display the inserted function. When printf sees a "%d", it means that it must replace that section of the string with an integer in decimal format (as opposed to hexadecimal, or binary). It looks at the first argument it has been given after the string argument (the variable result), formats it to decimal notation, and inserts it into the string. If printf finds more "%"'s in the string, it will look at the second argument after the string, and then the third, and so on.

The '\n' part you see is actually another way of saying "newline" or "enter key". Since pressing the enter key when writing your code will move down to a next line, we need '\n' to keep our code clean.

To see the printf and cr8_printf reference page, click here.

More Operations and Examples

Let's start with the following variable declarations:

int x = -4, y = 2, z = 11;

Modulo

One very useful operation is the modulo operation, which is represented by a percent sign (%). It can be used to get the remainder of integer division.

For example, we know that 11 / 2 = 5.5, or 5 and one-half. With integer division, z / y = 11 / 2 = 5, since the remainder is dropped. We can use the modulo operator to retrieve that remainder:

int result = z / y; // result = 5
int remainder = z % y; // remainder = 1

If we assigned z with the value of 10, what would remainder be? It would be 0.

More Assignment

If we wanted to change the value of x to the result of x + y, we could use this line of code:

x = x + y; // x = -4 + 2 = -2

We can use a shortcut by putting the plus sign right before the equal sign, and the putting only y after it:

x += y; // x = x + y = -2 + 2 = 0

Instead of saying "assign the result to x" using an equals sign, we are saying "add the result to x". We can also do:

x -= y;  // x = x - y = 0 - 2 = -2
x *= x;  // x = x * x = -2 * -2 = 4
x /= y;  // x = x / y = 4 / 2 = 2

Increment / Decrement

Now, we want to display how x will count up from 2 to 4. We could write the code:

printf("%d \n",x);
x = x + 1;
printf("%d \n",x);
x = x + 1;
printf("%d \n",x);

We could also use a shortcut called the increment operator, which is two plus signs together (++). The new code could look like:

printf("%d \n",x);
x++;
printf("%d \n",x);
x++;
printf("%d \n",x);

It could even look like:

printf("%d \n",x++);
printf("%d \n",x++);
printf("%d \n",x);

If you wanted to count backwards from 4, you could use the decrement operator, which is two minus signs together (--).

printf("%d \n",x--);
printf("%d \n",x--);
printf("%d \n",x);

Variable Type Modifiers

There are some additional keywords you can use to make some changes to your variables. These keywords are added before the type, for example: <modifier> int my_var;

const - The constant modifier causes the value of the variable to be locked and unchangable. When creating a constant variable, you must give it a value at the same time you create it, since that's the only time you can set it's value.

unsigned - This modifier allows you to create basic variables that do not have negative values. This means the value can be twice as large on the positive side.

short - This modifier allows you to reduce the size of a variable. For example, a standard integer will be two bytes long, but a short integer will be only one byte. This will reduce the range of values of your variable.

long - The long modifier is the opposite of the short modifier. This will increase your variable size, allowing them to be a greater range of values.


<< Syntax | Home Page | Data Structure >>


Have a Question? Please ask below.

Edit - History - Print - Recent Changes - Search
Page last modified on January 04, 2008, at 11:15 AM