Turing/Hello world

From Wikibooks, open books for an open world
Jump to: navigation, search

This is a very simple program. It will print text to the screen, and then exit.

put "Hello, world!"

Pretty simple, eh? As you probably deduced, put prints text. For now, we'll be using it to output to the screen.

Next, we'll learn how to gather input from the user using get. We'll also declare two variables, name and age. The program will get the user's name and age, and repeat it back to them.

var name : string %A string is text
var age : nat %Natural number

put "What is your name?"
get name
put ""
put "How old are you?"
get age

put "Hello, ", name, " you are ", age, " years old!"

First, we have to declare two variables. Turing lets you declare variables anywhere in the program, but it's usually a good idea to declare them at the top.

Now why was age a natural number? Why not an integer? Well, in Turing, natural numbers are all positive integers, including zero (0,1,2,3...). Integers, however, include negative numbers as well as positive numbers. The user's age shouldn't be a negative number, so it doesn't need to be an integer.

Second, did you notice the % followed by some text? Those are called comments. They start at the percent-sign and continue until the end of the line. They are meant to be messages to you, the programmer, about your program. Turing doesn't care about them. They have no meaning except to the person reading the code, of which they may well be of great importance. It is important that you use meaningful comments. When you come back eight weeks later, or someone else reads your code, you may have no idea what that code you wrote meant.

After we have two variables set up, we proceed to ask the user their name...they have to know what to enter!

Then we say get name. This means, "Let the user type in a string, and store it under the variable name for later use. Same for age.

Finally, we regurgitate the information back to the user. Make sure you put spaces before closing the quotation marks, or else there won't be any spaces before and after their name and age!

One last thing: Turing uses token-oriented input. This means that when the user inputs a space, it is treated the same as a line break. But we don't want this in our program, because what if the user enters their first and last name? Therefore, we tell turing "only get the next variable when they press enter."

To do this, replace get name with get name : *

If statements, cases