Turing/Variables and Types

Code

edit

Try this code:

  var text : string
  get text 

This code does two things

  1. makes "text" a variable (the first line of code)
  2. allows the user to input the value of "text" (the second line of code)

A variable is essentially the variable in math. However, in a programming language, a variable can hold a character, number, or a string. Before you use a variable, you have to declare it. There is a simple way to do that:

var foo : int

There are several important parts in this code segment. First, there is the keyword "var". It basically means that whatever comes next is a variable declaration. "foo" is the name of the variable you are defining. After, there is a colon. After the colon is the keyword "int". This says that foo is an integer. This statement essentially declares foo as an integer. This will be further explained in the next section.

Variable Types

edit

There are four types of variables:

type what it is syntax
boolean true or false var a : boolean
integer numbers with no decimals var b : int
real number numbers with decimal places var c : real
string series of characters var d : string

Working With Variables

edit

In the previous section, we saw all the variable types. Now we need to learn how to use them. Suppose we had two integers, called "foo" and "bar". We can do many things with these two variables.

foo := 5
bar := foo + 10

Arrays

edit

Another useful type of variables is an array. It can store many different variables at once. For example, a 10 by 10 array can store 10 times 10 variables, or 100 different values. The syntax is as follows:

    var asdf : array 1..10, 1..10 of int

You can choose the variable type and the size by changing the numbers and the "int" to boolean for example. If you choose to add more dimensions, you can, for example:

    var jkl : array 1..3, 1..5, 13..36 of boolean

The way you assign or call variables is as follows:

    asdf (1,4) := 5
    get asdf (2,7)
    put jkl (3, 3, 34)

Exercises

edit

Exercises:

  1. Make a program that has the user input their name and then prints it out (Hint: to print a variable, you cannot put quotation marks around it)
  2. Make a variable that stores 10 names in an array, and if you want, prints them out. You will learn a more efficient way of doing this next lesson.


Project: Turing
Previous: Introduction — Turing/Variables and Types — Next: Control Structures and Logical Expressions