Computer Science Canada

The Start: Introduction, Comments, Output, Variables, Input

Author:  Cervantes [ Thu Aug 18, 2005 11:24 am ]
Post subject:  The Start: Introduction, Comments, Output, Variables, Input

The Basics



Introduction to Programming

    Programming may seem scary at first, but hold fast! It is elegantly simple. Here's why: Programming languages are not computer languages. They are human languages that computers can translate into their own language (binary). They have been successfully designed by humans for use by humans, despite the restrictions placed on programming languages because they must be understood by computers as well. Writing in a programming language is strikingly similar to writing in a language in the traditional sense of the word: there are syntax rules to follow, there are objects that analogous to nouns, and methods that are analogous to verbs. There are no adjectives, mind you, because computers understand quantity, not quality.

    That said, let's delve in and learn just how computer languages work. The only thing you need to know right now is that the computer executes the code sequentially--line by line. The first line of a program is completely executed before execution of the next line has begun.




Comments

    Some code is difficult to understand, even if you understand the language it is written in. To that end, the designers of programming languages have allowed us to comment our code. In Turing, this is done by placing the percent sign (%) before a comment.
    Turing:

    % This is a comment.  Everything after the % on this line is ignored by the computer.

    Another way of commenting code is by using matching sets of "/*" and "*/"
    Turing:

    /*
    This is a comment.  Everything after the forward-slash-asterisk but before the matching asterisk-forward-slash is ignored by the computer.
    */


    Commenting makes your code more understandable to yourself (you may think you know what your code is doing, but you probably won't know when you return to it a month later) and to others who read your code. If your code is more understandable, you will be more productive in writing it and others will spend less time understanding it and more time helping/learning from you.




Output

    There are several ways that our computers can communicate to us. The first and most obvious is visually, through the monitor. The second is audibly, through the speakers. The last is much more tangible: the printer. We will begin by learning how to output text to the monitor, and save the speakers and printer for later lessons.

    We want to put some text on the screen, to prove that the link between us and the computer does in fact exist. Let me repeat that again: We want to put some text on the screen. In Turing, we do this by using the put command, followed by the text, contained in double quotes, that we want to output, like this:
    Turing:

    put "Hello World"

    Type this code into your Turing window and click the Run button (or hit F1). You should see a Turing Run Window pop up with some buttons across the top and text that says "Hello World". If you see this, the first task is complete. If not, go update your version of Turing.

    Now, a bit of explanation is due. The put command takes whatever is after it and puts it at the cursor location in the Run Window. You don't see the cursor, mind you, because we never asked for input; only output. The cursor begins in the upper left corner, and with each time you put text on the screen, the cursor moves down one line.

    What comes after the put command determines what you will see on the screen. In the case of our "Hello World" program, we put a string on the screen. "What's a string?" you ask. Let us examine.




Variable Types

    Strings:

      We have already encountered the string. Now let us answer the unrelenting question, "What is a string?" A string is a sequence of characters. The characters can be ordinary things such as letters and numbers, or they can be wacky things found in the ASCII chart such as the plus-minus sign (±). A string is bounded by quotation marks, as in "Yarr! I caught me aye fish!" A string can contain a maximum of 255 characters.

    Characters:

      A character is a single letter, number, or any wacky symbol that you can find in the ASCII chart. Characters are bound by quotation marks, as in 'Q'. Generally, strings use double quotes and characters use single quotes, though either type can use either style of quotation mark.

    Integers:

      We should all know what an integer is, given some fundamental math. Just to make sure, an integer is a whole number; it has no decimals; it is a fraction whose denominator is 1; it can be negative, zero, or positive.

    Real Numbers:

      Real numbers can contain decimal places. Turing supports up to 16 decimal places for real numbers. Real numbers contain the realms of the positive, the negative, and zero.

    Boolean:

      The boolean (named after George Boole) variable type contains only two alternatives: true or false. We will look into these in greater depth later, particularly when learning about conditions or if statements.





Returning to Output

    Now that we know our Hello World program output a string on the screen, let's experiment with the other variable types. Let's try outputting an integer, then a real number.
    Turing:

    put 7                               % Outputs 7
    put 8.19538032154                 % Outputs 8.19538

    Notice how the real number was rounded.
    Now I know everyone loves arithmetic, so it's about time we did some. Quickly now, (4 + 8) / 2 * (3 - 5) equals what?

    Turing:

    put (4 + 8) / 2 * (3 - 5)       % Outputs -12

    Turing does the math following the precedence rules, BEDMAS (Brackets, Exponents, Division and Multiplication, Addition and Subtraction). Now let's output the question and the answer:
    Turing:

    put "(4 + 8) / 2 * (3 - 5) = ", (4 + 8) / 2 * (3 - 5)
    % Output: (4 + 8) / 2 * (3 - 5) = -12

    Notice the use of the comma (,). The comma separates one section from the next. The first section is a string, which shows us the question. The next section is an integer, which is the answer.
    Strings can be added together, a process called concatenation: we are taking one value and placing another value directly after it.
    Turing:

    put "Hello " + "Alan Turing."      % Outputs "Hello Alan Turing."

    "Alan Turing" is placed directly after "Hello ", to produce a quaint greeting to the legendary mathematician, cryptographer, logician, philosopher, biologist, and computer scientist, Alan Turing (1912 - 1954).




Constants and Variables

    We use constants and variables in mathematics all the time. Consider the following equation:
    Volume_of_a_Sphere:

    V = 4/3 * pi * r ^ 3

    Volume equals four-thirds pi times the radius cubed.
    There are two variables in the above equation: V and r. V represents volume. r represents the radius of the sphere. V and r have values that can change. They are probably real numbers.
    There is only one constant in the above equation, pi. It's value is constant, unchanging, no matter when or where you are in the universe. It is always (approximately) 3.14159265358979323846.

    In programming, a variable represents a location in the memory where a value is stored.

    Declaring Constants and Variables

      The general syntax (read: grammar) for creating a constant in Turing looks like this:
      Turing:

      const variableName : typeSpec

      Declaring a variable is the same, except the keyword const is replaced with var.
      Turing:

      var variableName : typeSpec

      variableName is the name of your variable. It can contain letters (upper case and lower case), numbers (though it cannot start with a number), and underscores.
      typeSpec is the variable type: a string, integer, real number, or a boolean value. Let's create one variable of each type:
      Turing:

      var customerName : string          % A variable to store the name of your customer
      var numberOfPassengers : int        % A variable to store the number of passengers (in your private jet, nonetheless)
      var priceOfASausage : real         % A variable to store the cost of a sausage at the local supermarket
      var tastyToblerone : boolean        % A variable to store whether a toblerone bar is tasty or not



    Assigning Values to Variables

      The thing is, none of these variables have been assigned any values. To assign a value to a variable, we use the colon-equals (:=).
      The general syntax (read: grammar) for creating a variable in Turing looks like this:
      Turing:

      customerName := "Wolfgang Mozart"
      numberOfPassengers := 645
      priceOfASausage := 2.55
      tastyToblerone := true

      The variable on the left side of the assignment (:=) is given the value on the right side of the assignment (:=).
      You can assign more complex things to variables, as well. You can assign entire expressions, variables, or mixtures of both to variables. Watch:
      Turing:

      var priceOfChocolateBar : real
      var priceOfTeddyBear : real
      var priceOfBicycle : real
      var numOfChocolateBars : int
      var numOfTeddyBears : int
      var numOfBicycles : int
      var total : real

      priceOfChocolateBar := 1.49
      priceOfTeddyBear := 6.99
      priceOfBicycle := 349.99
      numOfChocolateBars := 2
      numOfTeddyBears := 4
      numOfBicycles := 1
      total := priceOfChocolateBar * numOfChocolateBars + priceOfTeddyBear * numOfTeddyBears + priceOfBicycle * numOfBicycles

      put "The cost of ", numOfChocolateBars, " chocolate bars, ", numOfTeddyBears, " teddy bears, and ", numOfBicycles, " bicycles comes to $", total, "."

      You can even use the value of the variable you are assigning to on the right side of the assignment (:=). Say we want to buy another chocolate bar:
      Turing:

      % Add the current total and the cost of  another chocolate bar,
      % and assign the sum to the variable, total
      total := total + priceOfChocolateBar



    Three Examples to Digest

      If you haven't opened Turing (the programming language, not the person) already, do so. Copy and paste the following code into the typing area and run the program.
      Example 1: Various Facts
      Turing:

      var customerName : string         % A variable to store the name of your customer
      var numberOfPassengers : int       % A variable to store the number of passengers (in your private jet, nonetheless)
      var priceOfASausage : real        % A variable to store the cost of a sausage at the local supermarket
      var tastyToblerone : boolean       % A variable to store whether a toblerone bar is tasty or not

      customerName := "Wolfgang Mozart"
      numberOfPassengers := 645
      priceOfASausage := 2.55
      tastyToblerone := true

      put "A wispy, frail man named ", customerName, " has entered your store."
      put "Despite the occupant limit of 200 people, you have managed to fit ", numberOfPassengers, " people into your private jet!"
      put "Due to inflation, the price of a single, moderately spicy, Italian sausage has risen to $", priceOfASausage, "."
      put "True or False: Toblerone's are tasty: ", tastyToblerone

      The program should execute successfully. The output should look like this:
      Turing Run Window wrote:

      A wispy, frail man named Wolfgang Mozart has entered your store.
      Despite the occupant limit of 200 people, you have managed to fit 645 people into your private jet!
      Due to inflation, the price of a single, moderately spicy, Italian sausage has risen to $2.55.
      True or False: Toblerone's are tasty: true


      Example 2: Volume of a Sphere
      Turing:

      var V : real
      var r : real
      /*
      Because pi is declared as a constant, we must give it a value immediately.  We cannot wait a line or two, because then we are changing the value of pi from nothing (nil) to 3.1415...
      */

      const pi : real := 3.14159265358979323846

      r := 10
      V := 4 / 3 * pi * r ** 3       
      % Usually we use the carat (^) for exponents, but Turing uses a double-asterisk (**). 
      % The base is immediately before the double-asterisk.
      % The exponent is immediately after the double-asterisk.

      put "The volume of a sphere with radius ", r, " units is ", V, " cubic units."

      Here's the output:
      Turing Run Window wrote:

      The volume of a sphere with radius 10 units is 4188.790205 cubic units.


      Example 3: Quadratic Formula
      If you don't know anything about the quadratic formula, don't worry. Just look at the programming, and don't worry about the math.
      Turing:

      % We can declare variables of the same variable type on the same line,
      % by separating them with commas.
      var a, b, c, x1, x2 : real
      a := 5
      b := 8
      c := -3
      x1 := (-b + (b**2 - 4*a*c) ** 0.5) / (2 * a)
      x2 := (-b - (b**2 - 4*a*c) ** 0.5) / (2 * a)
      /*
      Raising something to the power of one-half is the same as taking the square root of it.
      for curiosity, these lines could also be written like this:
      x1 := (-b + sqrt (b**2 - 4*a*c)) / (2 * a)
      x2 := (-b - sqrt (b**2 - 4*a*c)) / (2 * a)
      */


      put "The roots of the parabola 'y = ", a, "x**2 + ", b, "x + ", c, "' are ", x1, " and ", x2, "."

      Here's the output:
      Turing Run Window wrote:

      The roots of the parabola 'y = 5x**2 + 8x + -3' are 0.313553 and -1.913553.




    Problems with Assignability

      If you've been tinkering around with Turing as you're reading this, you may have already discovered this. Say you have a integer variable. You are not allowed to assign it a value such as "Fred" or 4.684. This is a syntax error.
      That's understandable, but what about this next scenario? You've got an integer variable and you want to assign it a value of "7". That's 7, in double-quotes. We can't even do this. The reason is "7", the string, is stored in memory differently than is 7, the integer. (Integers can be stored using simple binary. 7, for example, is 111 in binary. Strings, however, are actually a collection of characters, and the characters are defined by their ASCII value. 7 has an ASCII value of 55, which in binary is 110111. A conversion must take place in order to allow things to operate smoothly. I discuss this in my String Manipulation tutorial, but don't go there. This is all just to peak your unbridled and ever-lusting curiosity. Is it satisfied now?)

      For now, accept the rules of assignability. Don't go trying to assign a value of "Jared Diamond" to your boolean variable.





Getting Information From The User

    Now comes the fun part. We're going to learn how to get input from the user of your program. The most basic way of doing this is using the get command. It's rather simple:
    Turing:

    var name : string
    put "What is your name?"
    get name
    put "Hello ", name, "!"

    First, we must declare our variable. Then we get the variable name, which will get input from the user. Try running this program.
    Question 1:
      Try to crash the above program.

    Hint 1:
      Look above, where we first introduced the variable types.

    When you're done crashing that delicious program, try running the following, very similar program:
    Turing:

    var age : int
    put "How old are you?"
    get age
    put "Wow! ", age, " sure is old, especially for you mortals! *cackle*"

    This program is much easier to crash. Entering a string such as "Insolent fool! I'm immortal!" or entering a real number such as 9e5 (this means 9 * 10^5, which is nine hundred thousand [900 000], and is in fact a valid real number).

    Question 2:
      Write a program to output the kinetic energy of an object given its mass its velocity (that is, the user inputs the mass and the velocity) according to the following formula:
      Ek = 1/2 * m * v^2
      where Ek is the kinetic energy of the object,
      m is the mass of the object,
      and v is the velocity of the object.





Conclusion

    If you've made it this far, kudos to you! You've mastered the fundamentals of Turing and of any programming language. You can now interact with the computer through Turing, and you're program can interact with the user through the put and get commands.

    Now take your mind off these things. Spin an album-side (or have you been multitasking this whole time?), go for a run, talk to your family/friends, or, in the spirit of getting into the CompSci.ca community, download and watch some anime / play DDR.
    The Beatles - Tomorrow Never Knows wrote:

    Turn off your mind, relax, and float downstream.
    It is not dieing. It is not dieing.
    Lay down all thoughts, surrender to the void.
    It is shining. It is shining.
    That you may see the meaning of within.
    It is being. It is being.

    When you're ready, learn how to test certain conditions using if statements.


Answers

    Answer 1
      Input a string longer than 255 characters. 3.5 lines of characters using the standard run window size should do it.


    Answer 2
    Turing:

    var kineticEnergy, mass, velocity : real
    put "Please enter the mass of an object, in kilograms: " ..
    % The .. makes the cursor follow this line,
    % rather than jumping down to the next line.
    % Thus, the text the user types will appear
    % immediately after the request.
    get mass
    put "Please enter the velocity of the same object, in metres per second: " ..
    get velocity
    kineticEnergy := 0.5 * mass * velocity ** 2
    put "The kinetic energy of your object is ", kineticEnergy, " Joules."


Author:  [Gandalf] [ Thu Aug 18, 2005 12:34 pm ]
Post subject: 

Wow, that's pretty detailed and well presented. Read that once or twice and you're set from knowing no programming to being on a path to making some amazing programs Smile.

Good job!

Author:  theguru [ Fri Oct 07, 2005 9:55 pm ]
Post subject: 

great tutorial. lot's of details and examples. i think you should put something about escape characters. i don't know if turing has any but it should. for example how would you put a "quotes" in the put command. if turing is like c++ and other languages it should be \" but correct me if I'm wrong.

Author:  [Gandalf] [ Fri Oct 07, 2005 10:25 pm ]
Post subject: 

Indeed... The \ is the escape character in Turing as well.

\n - newline
\t - tab
\" - quote
\' - single quote (for chars)
\b - backspace
\\ - backslash
and the whole lot of them...

Author:  theguru [ Fri Oct 07, 2005 11:16 pm ]
Post subject: 

ok, thanks a lot for the help. Very Happy but shouldn't they put that in the tutorial too? and what's the function for square roots?

Author:  Cervantes [ Thu Oct 13, 2005 3:28 pm ]
Post subject: 

theguru wrote:
ok, thanks a lot for the help. Very Happy but shouldn't they put that in the tutorial too? and what's the function for square roots?

sqrt() or raise the number to the exponent of (1/2)

Please don't flood the tutorial with questions. There's an entire forum for that.

I could add that to the tutorial, yes. But then that's more to digest, and not necessary at this level.

Author:  FakeSound [ Sat Apr 22, 2006 9:23 am ]
Post subject: 

Hey, I'm new to programming and I just wanted to say that this site is really helpful .. thanks guys Very Happy

Author:  jamonathin [ Sun Apr 23, 2006 5:02 pm ]
Post subject: 

Shocked - Im just amazed at the length and detail of these tutorials you produce. No it's not hard to remeber all of these things when you need them, but to spit them all out off the top of your head? - crazy.

You need to start writing books Cervantes Wink.

Author:  Jessica43999 [ Tue Jun 06, 2006 11:17 am ]
Post subject:  Putting On Same Line

Does anybody know how to make something put on the same row over and over again? Like, a score in a loop?

Author:  Delos [ Tue Jun 06, 2006 12:16 pm ]
Post subject: 

Sounds like you'll want to look into locate(). If this does not suit your needs, then please post a question in [Turing Help]. Make sure to include a clear description of your problem, some sample code illustrating what you've done so far, and your thoughts on where you think the problem may lie.

Author:  [Gandalf] [ Tue Jun 06, 2006 6:22 pm ]
Post subject: 

Use .. after your put statement, for example:
code:
for i : 1 .. 10
    put i ..
end for

Will put the numbers from 1 to 10 right beside each other. If you had read Cervantes' tutorial thoroughly then you would have found the answer to your question.

Author:  Foundation [ Tue Sep 12, 2006 5:09 pm ]
Post subject:  Thanks!

I'm just learning about Turing, and this really helps! I appreciate this very much. Thanks.

Author:  Andr3iB [ Mon Feb 12, 2007 9:51 am ]
Post subject:  Re: The Start: Introduction, Comments, Output, Variables, Input

WOW Cervantes, your tutorials are really really helpful! Thnx for all the hard work!

Author:  Cervantes [ Mon Feb 12, 2007 2:01 pm ]
Post subject:  RE:The Start: Introduction, Comments, Output, Variables, Input

You're most welcome. Smile

Author:  TuringError [ Wed Nov 14, 2007 6:01 pm ]
Post subject:  Re: The Start: Introduction, Comments, Output, Variables, Input

Awesome,thank u so muchhh

Author:  mattman [ Wed Dec 05, 2007 8:42 pm ]
Post subject:  Re: The Start: Introduction, Comments, Output, Variables, Input

hey guys i just starting programming in m gr 10 class like basic stuff and i thougt id get a jump on things and this REALLLLLYYYYY helps me li9ke i agree what you said at start that that stuff was easy i understand it now because of you guy THANK YOU SOOOO MUCH:) Very Happy

Author:  cwlvc [ Thu Jan 10, 2008 6:30 pm ]
Post subject:  RE:The Start: Introduction, Comments, Output, Variables, Input

good job well done tutorial

Author:  cwlvc [ Thu Jan 10, 2008 6:31 pm ]
Post subject:  Re: The Start: Introduction, Comments, Output, Variables, Input

good job

Author:  riveryu [ Mon Feb 11, 2008 9:42 pm ]
Post subject:  RE:The Start: Introduction, Comments, Output, Variables, Input

- I think there should be a summary chart for commands covered in this intro, ex. for the arithmetic operators mentioned in this; instead of scattered all over this tutorial.

- Perhaps minor things such as "cls" or "delay" should be mentioned...

However, im basing this opinion only on reading this page, idk if other tutorials covered the stuff mentioned above. Sry if this seems to be arrognant.

Anyways, this is already a very comprehensive introduction, thanks a lot. Im grade 10 and this has helped me stay ahead.

Author:  wtd [ Sun Oct 12, 2008 1:38 pm ]
Post subject:  Re: The Start: Introduction, Comments, Output, Variables, Input

Wikified and linked via the walkthrough!

Author:  alithegator [ Sun Oct 04, 2009 10:13 pm ]
Post subject:  RE:The Start: Introduction, Comments, Output, Variables, Input

awesome job, very straightforward and understandable! way to go Very Happy

Author:  wysper [ Wed Apr 21, 2010 1:03 pm ]
Post subject:  RE:The Start: Introduction, Comments, Output, Variables, Input

without this tutorial..i would fail my programing class..my teacher has actualy not showed my class anything..his excuse is "i havent used turing in over 10 years", so ty for helping me pass my class Razz

Author:  atal [ Mon Jul 18, 2011 3:06 pm ]
Post subject:  Re: The Start: Introduction, Comments, Output, Variables, Input

Thanks so much im currently learning turing using ur tuts. +all of my bits. srry its not much


: