Difference between revisions of "RPi Education/Manual"

From eLinux.org
Jump to: navigation, search
m (Spelling & Grammatical Fixes)
(Python function example)
 
(25 intermediate revisions by 7 users not shown)
Line 20: Line 20:
  
 
It is considered good programming to use an iterative approach, using existing tools and patterns as much as possible, as such it is customary to start with a hello world:  
 
It is considered good programming to use an iterative approach, using existing tools and patterns as much as possible, as such it is customary to start with a hello world:  
==Bash==
+
==Hello world==
 +
===Bash===
 
Bash is the language of the terminal.
 
Bash is the language of the terminal.
  
# open the termonal application
+
# open the terminal application
# type: '''echo Hello World!'''
+
# type:
 +
<syntaxhighlight lang="bash">echo Hello World!</syntaxhighlight>
  
<tt>echo Hello World!</tt>
 
  
 
That was a computer program,
 
That was a computer program,
  
If you want to learn more about the echo command you can type '''man echo''' (press '''q''' to quit)  
+
If you want to learn more about the echo command you can type
 
+
<syntaxhighlight lang="bash">man echo</syntaxhighlight>
<tt>
+
(press '''q''' to quit)  
man echo
+
</tt>
+
  
 
Now let's make our program into runnable file:
 
Now let's make our program into runnable file:
  
# '''nano hi.sh'''
+
# <syntaxhighlight lang="bash">nano hi.sh</syntaxhighlight>
# '''echo Hello $1!'''
+
# <syntaxhighlight lang="bash">echo Hello $1!</syntaxhighlight>
 
# '''[Ctrl]+[x],[y],[enter]'''
 
# '''[Ctrl]+[x],[y],[enter]'''
# '''bash hi.sh Tux'''
+
# <syntaxhighlight lang="bash">bash hi.sh Tux</syntaxhighlight>
 
+
<tt>
+
bash hi.sh Tux
+
</tt>
+
 
+
 
Which should ouput:
 
Which should ouput:
 
 
<tt>
 
<tt>
 
Hello Tux!
 
Hello Tux!
 
</tt>
 
</tt>
  
 +
===Python===
  
(vim, and gedit are other editors you may with to use.)
+
Make a file called '''hi.py''', put <syntaxhighlight lang="python">print("Hello, world!")</syntaxhighlight> in it and run it with '''python hi.py'''  
 
+
==Python==
+
 
+
Make a file called '''hi.py''', put '''print("Hello, world!")''' in it and run it with '''python hi.py'''  
+
  
 
Now a GUI version:
 
Now a GUI version:
 +
<syntaxhighlight lang="python">
 +
#!/usr/bin/python
  
...//TODO format code in wiki...
+
import pygtk
 +
import gtk
 +
class Whc:
 +
        def __init__(self):
 +
                self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
 +
                self.window.connect("destroy", self.destroy)
 +
                self.window.set_title("Title")
 +
                self.window.set_default_size(200,100)
 +
                self.label = gtk.Label("Hello, World!")
 +
                self.window.add(self.label)
 +
                self.label.show()
 +
                self.window.show()
 +
        def destroy(self, widget, data=None):
 +
                gtk.main_quit()
 +
def main(self):
 +
        gtk.main()
 +
        if __name__ == "__main__":
 +
                base = Whc()
 +
base.main()
 +
</syntaxhighlight>
  
=Beginning=
+
===java===
  
Features, libraries, and limitations.
+
Create a text file called 'Hello.java' with the following content:
  
==Python==
+
<syntaxhighlight lang="java">
Create a text file called 'hello.py', with the following contents
+
public class Hello {
 +
    public static void main(String[] args) {
 +
        System.out.println("Hello World!");
 +
    }
 +
}
 +
</syntaxhighlight>
  
<syntaxhighlight lang="python">
+
Now compile your file as follows:
print "Hello World!"
+
</syntaxhighlight>
+
  
To run the program, type the following
+
<syntaxhighlight lang="bash">javac Hello.java</syntaxhighlight>
 +
To run your program:
 +
<syntaxhighlight lang="bash">java Hello</syntaxhighlight>
  
<tt>
+
It should respond with
python hello.py
+
<tt>Hello World!</tt>
</tt>
+
 
+
It should respond with:
+
 
+
<tt>
+
Hello World!
+
</tt>
+
 
+
==C/C++==
+
 
+
C and C++ are often put together, but are indeed two similar but different languages.
+
  
 
===C===
 
===C===
Line 105: Line 110:
 
Now compile the file using 'cc' , like this:
 
Now compile the file using 'cc' , like this:
  
 
+
<syntaxhighlight lang="bash">cc hello.c</syntaxhighlight>
<tt>
+
$ cc hello.c
+
</tt>
+
  
  
 
If all went well, there will no error messages and a new file called 'a.out' should have been created by the compiler.
 
If all went well, there will no error messages and a new file called 'a.out' should have been created by the compiler.
 
<tt>
 
$ ls
 
<br/>
 
hello.c
 
a.out
 
</tt>
 
 
 
To run your program type:
 
To run your program type:
 
+
<syntaxhighlight lang="bash">./a.out</syntaxhighlight>
<tt>
+
$ ./a.out
+
</tt>
+
  
 
It should report back with your message:
 
It should report back with your message:
  
<tt>
+
<tt>Hello World!</tt>
Hello World!
+
</tt>
+
  
 
===C++===
 
===C++===
Line 151: Line 140:
 
Open a terminal and switch to the directory, which contains the saved file.
 
Open a terminal and switch to the directory, which contains the saved file.
  
  <tt>cd ~/cpp</tt>
+
  <syntaxhighlight lang="bash">cd ~/cpp</syntaxhighlight>
  
 
Make sure with <tt>ls</tt> that you are in the correct directory. It should output <tt>helloworld.cpp</tt> and all other files in this directory (if any).
 
Make sure with <tt>ls</tt> that you are in the correct directory. It should output <tt>helloworld.cpp</tt> and all other files in this directory (if any).
Line 157: Line 146:
 
Now it is time to translate your code so your computer can understand it. This is called compiling.
 
Now it is time to translate your code so your computer can understand it. This is called compiling.
  
  <tt>g++ helloworld.cpp -o helloworld</tt>
+
  <syntaxhighlight lang="bash">g++ helloworld.cpp -o helloworld</syntaxhighlight>
  
 
If everything went ok, nothing is printed. Now run your program.
 
If everything went ok, nothing is printed. Now run your program.
  
  <tt>./helloworld</tt>
+
  <syntaxhighlight lang="bash">./helloworld</syntaxhighlight>
  
 
This outputs <tt>Hello world!</tt> on the command line.
 
This outputs <tt>Hello world!</tt> on the command line.
  
==Java==
+
===perl===
  
=Intermediate=
+
A "Hello World" example in Perl.
  
Useful tools and fun toys.
+
Create a file called 'hello.pl' in a directory of your choice, with the following contents:
  
==Bash==
+
<syntaxhighlight lang="bash">#!/usr/bin/perl
==C/C++==
+
==Perl==
+
==Java==
+
Create a text file called 'hello.java' with the following content:
+
  
<syntaxhighlight lang="java">
+
print "Hello World!\n";
public class hello {
+
</syntaxhighlight>
 +
To run your program type:
 +
 
 +
<syntaxhighlight lang="bash">perl hello.pl</syntaxhighlight>
 +
 
 +
It should respond with:
 +
 
 +
<tt>Hello World!</tt>
 +
 
 +
==Structure==
 +
Most all code is executed in order; from top to bottom, left to right, and in English.
 +
===Control flow statements===
 +
*Decision-making statements (if-then, if-then-else, switch)
 +
*Looping statements (for, while, do-while, break, continue)
 +
*branching statements (fork join)
 +
 
 +
==C For Loop==
 +
There are a number of loops in C but one of the most commonly used is the for loop. The for loop repeats the code inside it a certain number of times then stops. An example of how a for loop may be used is below.
 +
 
 +
In order to make this program run,
 +
*First open the terminal application and type in "cd ~/Documents", switches the folder that the terminals working in to your documents folder. Then open a text editor such as gedit. This can be done by opening a terminal and typing "gedit" then pressing enter on your keyboard, at this point a text editor should open up. If gedit doesn't start you probably don't have it,  type "nano" and press return, you should have an application load in your terminal which you can type text in.
 +
*Next copy and past the code below into the text editor. This can be done by right clicking your mouse and clicking copy, then in the text editor right click your mouse and select paste. ('''HINT: in gedit you can enable syntax highlighting, which will make the important parts of the code coloured like in the example below.''')
 +
*Now you need to save the code. In gedit click on file and save, a save window will then appear. Choose a name for your file, I suggest loop.c, but any name is fine so long it has a ".c" after it, and save it in the Documents folder. If you are using nano press and hold the control (ctrl) key on your keyboard and then press the 'x' key. There will be some text asking you to save the code before you exit type 'y' and press enter. Then type in loop.c and press enter. This has now saved your file as loop.c.
 +
*Now if you used type "gcc -o loop loop.c" replacing loop.c with whatever you called you code file. This should finish quite quickly and no text should appear. If any errors appear check what you have typed into your code file very carefully and make sure that it is exactly like the one in the example.
 +
*You should now have a new file in your documents folder called "loop", you can check this by typeing "ls" then press enter to display a list of files in you documents folder.
 +
*To run the program you need to type "./loop" and press enter. The program should now have the output:
 +
<tt>0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br></tt>
 +
The code is as follows:
 +
<syntaxhighlight lang="cpp">
 +
#include <stdio.h>  // Load the standard input/output library which contains the "printf" function
 +
 
 +
int main(void)
 +
{
 +
  int count;    // Initialise the counter variable.
 +
 
 +
  for(count = 0; count < 10; count++)
 +
  {
 +
      printf("%d\n", count);  // print the value of the counter in the terminal
 +
  } // The loop stops here, and checks to see if it has repeated 10 times.
  
public static void main(String[] args) {
+
  return 0;
    System.out.println("Hello World!");
+
}
+
 
}
 
}
 +
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Now compile your file as follows:
+
<p>The program starts by loading the "stdio" library. This library is required in order for you to output data onto the screen or make a file on the computer.
 +
Next the "main" function is started. The main function must exist in a C program and must be named "main" all lower case. The content of a function in C is surrounded by a scope.
 +
Scopes in C are indicated by curly braces '{' to start and '}' to finish. In the case of the main function in this program a "return 0;" statement is positioned at the end of a function. This lets the computer know that when the program finishes that everything ran properly.</p>
  
<tt>
+
The next statement "int count;" tells the computer to create a variable called count. Variables are used to store data such as numbers or sentences. In C variables should be created or "declared" at the beginning of a function, this is not completly nessesary as newer C compilers often allow you to ignore this rule. However it is recomended to stick to it, as when you are trying to find out why your program is not working it will be easier to see which variables are local to, in other words in the function and which variables are global to the program, or outside your function, but not in another function.
$ javac hello.java
+
</tt>
+
  
Notice how a new file was created after compilation:
+
Next the loop is started. The for statement indicates that the loop is a "for" loop. The next part surrounded in brackets "()" is a small bit of code telling the for loop how many times it should run. The fist bit "count = 0" sets the counter to 0 this is followed by a semicolon then the statement "count < 10" this meens that the code in the for loop should be repeated while the value of "count" is less than 10. This is followed by another semicolon and the statement count++. This part is run every time the for loop reaches the end. In this case the for loop increments, or increases, the value stored in count by 1. This could be replaced by "count = count + 1" if you wanted to and it would do the same thing.
  
<tt>
+
The code inside the for loop, in this case "printf("%d\n",count);" is used to display the value of count in the terminal.
$ ls
+
<br/>
+
hello.class hello.java
+
</tt>
+
  
To run your program:
+
As you may now see the loop has a few stages when the program is running.
  
<tt>
+
* First before the loop is started the "count" variable is set to 0
$ java hello
+
* Next the for loop begins by checking to see if "count" is less than 10.
</tt>
+
* Now the for loop runs the code inside.
 +
* Once the code has been run the for loop increases the value of "count" by one and checks to see if the value of "count" is still less than 10
 +
* If the value is still less than 10 the loop is repeated over and over again until the value of count is 10.
 +
* At this point the value of count is not less than 10 as it is 10 so the loop has to finish
 +
* As there is nothing more to do in the program the program quits with "return 0;"
  
It should respond with
+
For loops are very useful in programs in order to automatically repeat bits of code.
  
<tt>
+
Things to try,
$ Hello World!
+
* change the name of count in the "int count" statement and also wherever else count repeats. You will see that you can name it anything you like!
</tt>
+
* Try changing the printf line to another stament such as "printf("Hello, John! Or whatever your name is\n"); to repeat the statement 10 times.
 +
* change the number 10 in the count line, perhaps 100, 1000 or interestingly -1 and see what happens.
  
==Scratch==
+
==Bash For Loop==
==Greenfoot==
+
<syntaxhighlight lang="bash">
==Geogebra==
+
#! /bin/bash
 +
 
 +
COUNTER=0
 +
 
 +
for (( I=0; I<10; I++)); do
 +
    echo $COUNTER
 +
    let "COUNTER += 1"
 +
done
 +
</syntaxhighlight>
 +
 
 +
== Python "for" Loop ==
 +
 
 +
This is an example of a simple "for" loop in Python.
 +
 
 +
<syntaxhighlight lang="python">
 +
# Using a for loop
 +
# filename is for.py
 +
 
 +
for i in range (10,0, -1):
 +
    print("Looping: ", i)
 +
print ("Done")
 +
</syntaxhighlight>
 +
 
 +
The lines that begin with "#" are comments. They are ignored when the program is run, but help to make your code readable by humans.
 +
 
 +
In the "for" command we state that we are using the variable "i" as the counter in the loop. The section in brackets defines the start and end points, as well as the steps. Here, we are starting at 10 and going down to 0. (Although the last number we see will be one - when the loop hits 0 it will continue to the next instruction). The "-1" means we are counting down by one each time. The "for" line ends with a colon - this is important. The colon, together with the indentation, makes it clear to the Python interpreter that the block of code following is to be run each time through the loop. In Python, each level of indentation should be one tab or 4 spaces. You can use either, but not a mixture of both.
 +
 
 +
Inside the loop, we have a simple print statement. First, "Looping: " is printed and then the current value of "i".
 +
 
 +
The final line is not indented, and therefore is not part of the loop. This simply prints: "Done" once the loop has completed.
 +
 
 +
== Python "while" Loop ==
 +
 
 +
Here's a fun infinite loop.
 +
<syntaxhighlight lang="python">
 +
# This is a while loop.
 +
while 1:
 +
  print ("You suck and I rule.")
 +
</syntaxhighlight>
 +
 
 +
A comment line is hardly necessary here, but it's a good habit to get into. Just like the "for" loop, "while" statements need a colon at the end of the line and an indented block of code. The condition: "while 1:" means: "while 1 is true." As far as the computer is concerned any number apart from zero is "true" (this is an example of Boolean logic). You could try modifying the program to check this. You could also use any other condition that would always be true, for example:
 +
<syntaxhighlight lang="python">
 +
while 1>0:
 +
</syntaxhighlight>
 +
Since one is always going to be greater than zero, this loop will run forever (you can stop it by closing the window it is running in, or with the keyboard interrupt: "Control-C").
 +
 
 +
 
 +
 
 +
 
 +
===operators===
 +
* '''maybe we can just link to the SDKs that are shipped with the book?'''
 +
* [http://www.tizag.com/perlT/perloperators.php perl]
 +
* [http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html java]
 +
* [http://docs.python.org/library/operator.html#mapping-operators-to-functions python]
 +
* [http://tldp.org/LDP/abs/html/ops.html bash]
 +
 
 +
===functions===
 +
reusable blocks of code
 +
 
 +
== Python function example ==
 +
 
 +
<syntaxhighlight lang="python">
 +
# polygon.py
 +
# draws polygons
 +
 
 +
import turtle
 +
def polygon(length, sides):
 +
for i in range (sides):
 +
turtle.fd(length)
 +
turtle.left(360/sides)
 +
# main
 +
print ("Let's draw a polygon.")
 +
how_many = int(input("How many sides would you like?"))
 +
how_big = int(input("How long do you want the sides?"))
 +
polygon(how_big, how_many)
 +
input("Press enter to quit.")
 +
</syntaxhighlight>
 +
 
 +
Functions offer a way to make parts of your program re-usable. If you are going to do something several times in a program, it makes sense to write a function and call it each time, rather than repeating yourself. There are many advantages to this. For instance, it makes your programs shorter and if you need to change something, you only need to change it once - in the function definition. In this program, the function is only called once, as it's just an example of how to do it!
 +
 
 +
We begin with "import turtle" - this tells Python that we need to use the turtle graphics features of the language. In Python (like many other languages), some features have to be loaded in this way before you can use them.
 +
 
 +
Next comes the function definition. It's quite simple: "def" tells the interpreter we are defining a function and the next word will be its name ("polygon"). In Python, all functions have brackets following their names (for instance "print()" is a function). You can make a function that doesn't need anything inside those brackets, but this one takes two arguments. In this case, it is the number of sides and the length of the sides. After the definition, we use a colon and indent the following block of code.
 +
 
 +
Our function consists of a simple loop that makes the "turtle" move forward the required distance (in pixels) and turns through the appropriate angle (360 degrees divided by the number of sides).
 +
 
 +
After the definition of the function, there's a comment that now we are in the main part of the program. The function won't do anything until it is called. The next lines are fairly simple and just get some values from the user. You'll notice that the names of these variables are different from the ones used in the function definition. You could use the same names, but it will be less confusing if you do it this way; the function will store temporary copies of the data in its own "length" and "sides" variables. We call the function just like any other, with the name of the function and the arguments in brackets, separated by a comma. Once the function is complete, it will return control to the main part of the program - which just asks us to press enter.
 +
 
 +
 
 +
 
 +
===objects===
 +
are basically function containers, and yet so much more.
 +
 
 +
=Beginning=
 +
 
 +
Features, libraries, and limitations.
 +
 
 +
 
 +
==Bash==
 +
==C==
 +
==C++==
 +
==Java==
 +
==Perl==
 +
==Python==
 +
 
 +
=Intermediate=
 +
 
 +
Useful tools and fun toys.
 +
 
 +
==Theory and tools==
 +
* [[Version Control]]: Concepts, git, <del>svn, bzr, hg</del> etc
 +
* Iterative and Test Driven Development
 +
* Writing software for someone else (User Stories, Use Cases, requirements, contracts)
 +
* editors and IDEs: vim, gedit, eclipse, etc
 +
 
 +
==Bash==
 +
==C==
 +
==C++==
 +
==Java==
 +
==Perl==
 +
==Python==
  
 
=Advanced=
 
=Advanced=
Line 223: Line 366:
 
==Assembly==
 
==Assembly==
 
==Drivers==
 
==Drivers==
 +
 +
{{Template:Raspberry Pi}}

Latest revision as of 13:35, 23 May 2012

Please add any contributions to the educational user manual here. These should take the form of step-by-step guides or listings with descriptions. Alternatively, email your contribution by taking a look at this Raspberry Pi forum posting.


Intro

General

The objective is to educate people in computer science.

Hardware

Cheap hardware with 1/2 open specifications allow the masses to learn modern computer science.

  1. Plug in your RPi to your monitor with the hdmi and usb cable
  2. Plug in your mouse and keyboard to your monitor
  3. Plug in your monitor power and turn it on.

Software

Linux is used, it is open source, user friendly, and technically capable.

Language Selection

Beginners should select a high level language. Advanced users may select different languages combinations depending on the available libraries, programming paradigm, and optimizations.

All code is executed in binary assembled from assembly code compiled from a language sometimes in-turn compiled from other higher level languages.

There are 2 main interfaces for most all applications in linux CLI, and GUI, while GUIs are user friendly CLIs are more simple to build and can be used as building blocks for more complicated tools/toys.

It is considered good programming to use an iterative approach, using existing tools and patterns as much as possible, as such it is customary to start with a hello world:

Hello world

Bash

Bash is the language of the terminal.

  1. open the terminal application
  2. type:
echo Hello World!


That was a computer program,

If you want to learn more about the echo command you can type

man echo

(press q to quit)

Now let's make our program into runnable file:

  1. nano hi.sh
  2. echo Hello $1!
  3. [Ctrl]+[x],[y],[enter]
  4. bash hi.sh Tux

Which should ouput: Hello Tux!

Python

Make a file called hi.py, put
print("Hello, world!")
in it and run it with python hi.py

Now a GUI version:

#!/usr/bin/python
 
import pygtk
import gtk
class Whc:
        def __init__(self):
                self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
                self.window.connect("destroy", self.destroy)
                self.window.set_title("Title")
                self.window.set_default_size(200,100)
                self.label = gtk.Label("Hello, World!")
                self.window.add(self.label)
                self.label.show()
                self.window.show()
        def destroy(self, widget, data=None):
                gtk.main_quit()
def main(self):
        gtk.main()
        if __name__ == "__main__":
                base = Whc()
base.main()

java

Create a text file called 'Hello.java' with the following content:

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Now compile your file as follows:

javac Hello.java

To run your program:

java Hello

It should respond with Hello World!

C

Create a Text File called 'hello.c' which contains the following:

#include "stdio.h"
void main() {
        printf("Hello World!\n");
}


Now compile the file using 'cc' , like this:

cc hello.c


If all went well, there will no error messages and a new file called 'a.out' should have been created by the compiler. To run your program type:

./a.out

It should report back with your message:

Hello World!

C++


For starters the famous "Hello world!" example. Save the following code in a file called helloworld.cpp in a directory of your choice (e.g. ~/cpp). The filename can be chosen arbitrarily, but should describe the content.

 //Compile with: g++ helloworld.cpp -o helloworld
 #include <iostream>
 
 using namespace std;
 
 int main () {
     cout << "Hello world!" << endl;
     return 0;
 }

Open a terminal and switch to the directory, which contains the saved file.

cd ~/cpp

Make sure with ls that you are in the correct directory. It should output helloworld.cpp and all other files in this directory (if any).

Now it is time to translate your code so your computer can understand it. This is called compiling.

g++ helloworld.cpp -o helloworld

If everything went ok, nothing is printed. Now run your program.

./helloworld

This outputs Hello world! on the command line.

perl

A "Hello World" example in Perl.

Create a file called 'hello.pl' in a directory of your choice, with the following contents:

#!/usr/bin/perl
 
print "Hello World!\n";

To run your program type:

perl hello.pl

It should respond with:

Hello World!

Structure

Most all code is executed in order; from top to bottom, left to right, and in English.

Control flow statements

  • Decision-making statements (if-then, if-then-else, switch)
  • Looping statements (for, while, do-while, break, continue)
  • branching statements (fork join)

C For Loop

There are a number of loops in C but one of the most commonly used is the for loop. The for loop repeats the code inside it a certain number of times then stops. An example of how a for loop may be used is below.

In order to make this program run,

  • First open the terminal application and type in "cd ~/Documents", switches the folder that the terminals working in to your documents folder. Then open a text editor such as gedit. This can be done by opening a terminal and typing "gedit" then pressing enter on your keyboard, at this point a text editor should open up. If gedit doesn't start you probably don't have it, type "nano" and press return, you should have an application load in your terminal which you can type text in.
  • Next copy and past the code below into the text editor. This can be done by right clicking your mouse and clicking copy, then in the text editor right click your mouse and select paste. (HINT: in gedit you can enable syntax highlighting, which will make the important parts of the code coloured like in the example below.)
  • Now you need to save the code. In gedit click on file and save, a save window will then appear. Choose a name for your file, I suggest loop.c, but any name is fine so long it has a ".c" after it, and save it in the Documents folder. If you are using nano press and hold the control (ctrl) key on your keyboard and then press the 'x' key. There will be some text asking you to save the code before you exit type 'y' and press enter. Then type in loop.c and press enter. This has now saved your file as loop.c.
  • Now if you used type "gcc -o loop loop.c" replacing loop.c with whatever you called you code file. This should finish quite quickly and no text should appear. If any errors appear check what you have typed into your code file very carefully and make sure that it is exactly like the one in the example.
  • You should now have a new file in your documents folder called "loop", you can check this by typeing "ls" then press enter to display a list of files in you documents folder.
  • To run the program you need to type "./loop" and press enter. The program should now have the output:

0
1
2
3
4
5
6
7
8
9
The code is as follows:

#include <stdio.h>   // Load the standard input/output library which contains the "printf" function
 
int main(void)
{
   int count;    // Initialise the counter variable.
 
   for(count = 0; count < 10; count++)
   {
       printf("%d\n", count);   // print the value of the counter in the terminal
   } // The loop stops here, and checks to see if it has repeated 10 times.
 
   return 0;
}

The program starts by loading the "stdio" library. This library is required in order for you to output data onto the screen or make a file on the computer. Next the "main" function is started. The main function must exist in a C program and must be named "main" all lower case. The content of a function in C is surrounded by a scope. Scopes in C are indicated by curly braces '{' to start and '}' to finish. In the case of the main function in this program a "return 0;" statement is positioned at the end of a function. This lets the computer know that when the program finishes that everything ran properly.

The next statement "int count;" tells the computer to create a variable called count. Variables are used to store data such as numbers or sentences. In C variables should be created or "declared" at the beginning of a function, this is not completly nessesary as newer C compilers often allow you to ignore this rule. However it is recomended to stick to it, as when you are trying to find out why your program is not working it will be easier to see which variables are local to, in other words in the function and which variables are global to the program, or outside your function, but not in another function.

Next the loop is started. The for statement indicates that the loop is a "for" loop. The next part surrounded in brackets "()" is a small bit of code telling the for loop how many times it should run. The fist bit "count = 0" sets the counter to 0 this is followed by a semicolon then the statement "count < 10" this meens that the code in the for loop should be repeated while the value of "count" is less than 10. This is followed by another semicolon and the statement count++. This part is run every time the for loop reaches the end. In this case the for loop increments, or increases, the value stored in count by 1. This could be replaced by "count = count + 1" if you wanted to and it would do the same thing.

The code inside the for loop, in this case "printf("%d\n",count);" is used to display the value of count in the terminal.

As you may now see the loop has a few stages when the program is running.

  • First before the loop is started the "count" variable is set to 0
  • Next the for loop begins by checking to see if "count" is less than 10.
  • Now the for loop runs the code inside.
  • Once the code has been run the for loop increases the value of "count" by one and checks to see if the value of "count" is still less than 10
  • If the value is still less than 10 the loop is repeated over and over again until the value of count is 10.
  • At this point the value of count is not less than 10 as it is 10 so the loop has to finish
  • As there is nothing more to do in the program the program quits with "return 0;"

For loops are very useful in programs in order to automatically repeat bits of code.

Things to try,

  • change the name of count in the "int count" statement and also wherever else count repeats. You will see that you can name it anything you like!
  • Try changing the printf line to another stament such as "printf("Hello, John! Or whatever your name is\n"); to repeat the statement 10 times.
  • change the number 10 in the count line, perhaps 100, 1000 or interestingly -1 and see what happens.

Bash For Loop

#! /bin/bash
 
COUNTER=0
 
for (( I=0; I<10; I++)); do
    echo $COUNTER
    let "COUNTER += 1"
done

Python "for" Loop

This is an example of a simple "for" loop in Python.

# Using a for loop
# filename is for.py
 
for i in range (10,0, -1):
    print("Looping: ", i)
print ("Done")

The lines that begin with "#" are comments. They are ignored when the program is run, but help to make your code readable by humans.

In the "for" command we state that we are using the variable "i" as the counter in the loop. The section in brackets defines the start and end points, as well as the steps. Here, we are starting at 10 and going down to 0. (Although the last number we see will be one - when the loop hits 0 it will continue to the next instruction). The "-1" means we are counting down by one each time. The "for" line ends with a colon - this is important. The colon, together with the indentation, makes it clear to the Python interpreter that the block of code following is to be run each time through the loop. In Python, each level of indentation should be one tab or 4 spaces. You can use either, but not a mixture of both.

Inside the loop, we have a simple print statement. First, "Looping: " is printed and then the current value of "i".

The final line is not indented, and therefore is not part of the loop. This simply prints: "Done" once the loop has completed.

Python "while" Loop

Here's a fun infinite loop.

# This is a while loop.
while 1:
  print ("You suck and I rule.")

A comment line is hardly necessary here, but it's a good habit to get into. Just like the "for" loop, "while" statements need a colon at the end of the line and an indented block of code. The condition: "while 1:" means: "while 1 is true." As far as the computer is concerned any number apart from zero is "true" (this is an example of Boolean logic). You could try modifying the program to check this. You could also use any other condition that would always be true, for example:

while 1>0:

Since one is always going to be greater than zero, this loop will run forever (you can stop it by closing the window it is running in, or with the keyboard interrupt: "Control-C").



operators

  • maybe we can just link to the SDKs that are shipped with the book?
  • perl
  • java
  • python
  • bash

functions

reusable blocks of code

Python function example

# polygon.py
# draws polygons
 
import turtle
def polygon(length, sides):
		for i in range (sides):
			turtle.fd(length)
			turtle.left(360/sides)
# main
print ("Let's draw a polygon.")
how_many = int(input("How many sides would you like?"))
how_big = int(input("How long do you want the sides?"))
polygon(how_big, how_many)
input("Press enter to quit.")

Functions offer a way to make parts of your program re-usable. If you are going to do something several times in a program, it makes sense to write a function and call it each time, rather than repeating yourself. There are many advantages to this. For instance, it makes your programs shorter and if you need to change something, you only need to change it once - in the function definition. In this program, the function is only called once, as it's just an example of how to do it!

We begin with "import turtle" - this tells Python that we need to use the turtle graphics features of the language. In Python (like many other languages), some features have to be loaded in this way before you can use them.

Next comes the function definition. It's quite simple: "def" tells the interpreter we are defining a function and the next word will be its name ("polygon"). In Python, all functions have brackets following their names (for instance "print()" is a function). You can make a function that doesn't need anything inside those brackets, but this one takes two arguments. In this case, it is the number of sides and the length of the sides. After the definition, we use a colon and indent the following block of code.

Our function consists of a simple loop that makes the "turtle" move forward the required distance (in pixels) and turns through the appropriate angle (360 degrees divided by the number of sides).

After the definition of the function, there's a comment that now we are in the main part of the program. The function won't do anything until it is called. The next lines are fairly simple and just get some values from the user. You'll notice that the names of these variables are different from the ones used in the function definition. You could use the same names, but it will be less confusing if you do it this way; the function will store temporary copies of the data in its own "length" and "sides" variables. We call the function just like any other, with the name of the function and the arguments in brackets, separated by a comma. Once the function is complete, it will return control to the main part of the program - which just asks us to press enter.


objects

are basically function containers, and yet so much more.

Beginning

Features, libraries, and limitations.


Bash

C

C++

Java

Perl

Python

Intermediate

Useful tools and fun toys.

Theory and tools

  • Version Control: Concepts, git, svn, bzr, hg etc
  • Iterative and Test Driven Development
  • Writing software for someone else (User Stories, Use Cases, requirements, contracts)
  • editors and IDEs: vim, gedit, eclipse, etc

Bash

C

C++

Java

Perl

Python

Advanced

Algorithms, Heuristics, Design Patterns, and Optimization.

Hardware

Assembly

Drivers