Introduction to programming

Learn all the basic concepts by building a simple tree generator

This page teaches you the basics of programming. We are using the framework P5JS to do so. In the videos below we are going to build a little tree generator. As simple as this generator may seem, it actually teaches you all the basic concepts.

You can find the final code for it here,

The core concepts of programming in P5JS

Most programming languages consist of the same set of elements. Below I try to introduce you to the coding syntax and concepts of them. I made short videos for each core concept and its syntax. If you are new - I suggest you take it from the top. If you are more experienced then it may be enough to jump around a bit and more use it as a reference.

The core concepts are divided into the sections below.

1. Create an AccounT

First, we need to get you up and running. We could run p5.js locally, but it really shines running in the cloud. Most browsers will work, but all the examples on this site are optimised for Chrome, so it is recommended that you use that.

  1. Install the latest version of Google Chrome (https://www.google.com/chrome/)

  2. Create a user for P5.js web ide (https://editor.p5js.org/signup)

Also, while you are at it, do get familiar with the website especially get an overview of the references and the examples.

2. The P5.JS Interface


(screenshot of p5js ide)

Make sure to log in and save regularly, so you do not lose your work. Notice that you can debug with print("hello") and it will show in the console.


3. Setup and draw

Setup and draw are the two main functions that you use. Setup runs once you start the app and draw runs for every frame. This draw runs 60 frames pr. second, generating a frame each time.

function setup() {

//runs once at startup.

}


function draw() {

//runs for each frame

}

Notice how the curly brackets define the start and end of each function.

Read more about the p5js setup here and draw here.

4. The coordinate system of the canvas

The canvas defines the area in which you can draw when running the program.

  • It starts in the top left corner. The same as the reading direction, but opposite of normal graphs.

  • The x axis is left to right. The y axis is top to bottom.

The size of the canvas is typically defined in the setup function. Here it has a width of 500 and a height of 400:

createCanvas(500, 400);

Read more about createCanvas here.

Graphical illustration of the canvas coordinate system.

5. How to draw on the canvas

Drawing on the canvas can be done by calling different drawing commands. E.g. ellipse(x, y, width, height) will place a circle. fill(255,0,0) will define its fill colour. In this case, the circle will be red.

function setup() {

//runs once at startup.

}


function draw() {

fill(255,0,0);

ellipse(100,100,20,20);

}

Read more about how to use fill here and how to draw basic shapes such as an ellipse, a square or a triangle.

6. Decisions with if statements

A common mistake is to put a semicolon after if statements. This will not result in an error, but the scope beneath will always execute. Leading to utter confusion. See the following section about commands and scopes.

Interactive programming is essentially about making decisions. If x happens then do y. The basic syntax for making decisions are:

if (2==2) {

ellipse(200, 200, 70, 70);

}

If condition 2 equals 2 is met then the ellipse will be drawn on the screen.

Further, "else" can be used to execute something if the condition is not met:

if (2==3) {

ellipse(200, 200, 70, 70);

} else {

rect(200, 200, 70, 70);

}

In the above case, 2 is not equal to 3, so the ellipse will not be drawn, but the rectangle will.

Multiple if statements can be combined with "else if":

if (2==2 && 2>1) {

ellipse(200, 200, 70, 70);

} else if (true) {

rect(200, 200, 70, 70);

} else {

// do something here

}

Only the first condition which is true will run.

Different formulas can be made with: <, >, ==, != and conditions can be combined with && (and), II (or).

7. Grouping commands with curly brackets

A command is e.g. when you write print("xx"); to write into the console. A command typically ends with ";" EXCEPT when it is followed by a scope. E.g.:

print("hello world");

if(2==2)

{ // start of scope

print("Two does equals two");

print("Second command");

} // end if statement and scope

Notice where the ";" and the curly brackets are placed.

A scope is multiple commands grouped together. Scopes start and end with curly brackets. They define a group of code that is executed when a certain condition is met. In the previous, you learned about if statements. Notice how the scope after the command "if" is only executed when the condition of the if statement is met. And also, notice that there is no semicolon at the end of the if statement.

Also, scopes can be nested. A scope can have scope inside itself. This allows conditions to be more complex. E.g. if you are at the supermarket then buy milk if they have a low-fat version. This is two scopes nested inside each other.

if(inSuperMakert==true)

{// first scope start

if(hasLowFatMilk==true)

{ // nested scope

print("buying milk!");

}

}

It can be difficult to wrap your head around this concept. I often wonder if this is the most essential part of being able to program.

Read a detailed description of how to understand scopes here. This link presents some different versions of scopes that may come in handy.

Common mistakes and how to fix them

When starting out programming you will make a few common mistakes. This lists some of them and how to fix them:

  • Forgetting a semicolon: If you forget to put a semicolon at the end of a line the program will not run. Add the semicolon where missing (usually the line above the one that throws and error).

  • Adding a semicolon after an if statement: There should newer be a semicolon after an if statement. This one is hard to detect because the program will run, but it will always run the code inside the curly braces {}.

  • Too many or too few curly braces. Be very carefull with your curly braces if you add too many or have to few the program will not run. Make sure to indent your code properly so you are able to read it. Everything inside a curly brace should be indented.

8. variables for storing values in the memory

These are typical variables types:

A variable is a container of information that can be changed during runtime.

var x = 200;

In the above case, we have declared a variable with the name "x" and given it a value of 200. We can then change the value by:

x = 300;

To increment it by one:

x = x+1;

This also increments by one:

x++;

There are different kinds of variable types. They are defined implicitly by adding content to them. E.g. a boolean (true or false) can be defined like this:

var playMusic = true;

Through variables, we can execute different parts of the program with if statements:

if(playMusic == true)

{

// code to play music here

}

If playMusic is true, the code inside the curly brackets will run.

Notice how we use one equal sign (=) when defining variables and two equal signs (==) when comparing a variable to a value.

We typically declare a variable at the top. This way, we have global access to them since they are in the global scope. If we place the definition inside e.g. function draw() we will only have access to it inside the scope of the function, and it will be reset every time we run the function.

Read more about different data types here. In this link, you can find descriptions of booleans, numbers, strings, and more.

9. Loops for repeating blocks of code

A for loop can be converted to a while loop. This does the same as the for loop mentioned.

If we want to repeat a piece of code more than once, we can use different kinds of loops to do so. The most common is "for" loops. It is usually used when you have a specific amount of repetition you want to do:

for(var i = 0; i < 10; i = i +1)

{

print(i);

}

The above code will repeat itself ten times. "i" will be the counter that will increment one for each repetition as long as i is less than 10. Since the starting value is zero (a common logic in programming), the loop will repeat ten times until it reaches 9 (not ten, which is a common confusion, as it has to be less than 10).

for(initialization; condition; incrementation)

A for loop has three parameters separated by a semicolon:

  • Initialization: Sets the initial value.

  • Condition: Choose when to stop the repetition.

  • Incrementation: Defines how much the variable should increment.

Another loop used for repetition is a while loop. The following code will loop endlessly:

while(true)

{

// this loop will repeat itself forever.

}

Read more about for loops here and while loops here.

10. functions for reusing code

When programming, you often have a sequence of commands you want to run at different times in the duration of your code. This can be small macros like converting from inches to mm, and it can be more complex elements. These sequences are grouped in function. Let us say that we have an application that needs to draw a lot of houses. Instead of copying multiple drawing commands for each house, we can make a function to draw a house and call it multiple times:

function drawAHouse()

{

rect(50,50,20,20);

}

The house is, in this case, just a square. The problem is now that we do not have a way to place the house in different places. E.g. the house will always be drawn in position (50,50). We solve this by adding parameters to the function:

function drawAHouse(x,y)

{

rect(x,y,20,20);

}

x and y are local variables, which we could give these values:

drawAHouse(40,30)

This house will now be drawn in position (40,30), and we call it multiple times with different parameters.

Functions can also return something. Let's say that we want to have a function which converts from meters to millimetres:

function mToMM(length)

{

return length*1000;

}


print(mToMM(10.2));

Calling mToMM(10.2) will convert the 10.2m to 10200 MM.

Read more about creating functions here or in more detail here.

11. Arrays to make a list of variables

Often one wants to have a list of values (variables). This can be particles in a particle system or a list of employees in a company. For this to work, we need to group variables together in a list that we can iterate through. This is called an array. Square brackets are used to define it as a list instead of a normal variable. This is an empty list:

var names = [];

We can predefine it with content:

var names = ["Peter", "Lisa", "Olga"];

If we want to get the first name:

print(names[0]);

This prints "Peter".

We can add a name to the list like this:

names.push("Mads");

If we want to print out all the names in our list, we can use a for loop:

for(var i = 0; i < names.length; i=i+1)

{

print(names[i]);

}

Notice that the for loop repeats until it has reached the length of the list, and the "i" from the for loop is used to retrieve the individual names.

Read more about arrays here or in more detail here.

12. An object as grouping functions and variables

Read more about class and constructors here or here.

This is by far the most complex thing to understand. To simplify, we need to make an analogy. Put simply: I have a Toyota Car. My car is an object like any other object in this world (chairs, gloves, plants). My Toyota is of the classification "car" and not of the type "plant". So if we want to create my car as an object in code, we need to create a classification that we can make it from. Classification can then be used to create an instance of an object (e.g. "my Toyota" is made from the classification "a car"). We define a classification as follows:


class Car

{

constructor()

{

this.name="";

this.wheels=4;

this.topSpeed=200;

}

}

Notice the function "constructor". This is a special function that constructs the different variables that make up the car. "This" refers to the car class.

If we want to create an instance (object) of the classification car:

var myCar = new Car();

This executes the constructor that defines the variables (name, wheels and topSpeed).

We can then access and change the variables in our newly created car object:

print(myCar.wheels);

This will print the number of wheels (in this case, four).

Let us say that myCar has three wheels then we can set it to three:

myCar.wheels = 3;

The "." is called dot notation and is a central part of many programming languages. Dot notation allows us to access variables inside objects and also objects inside objects, etc.

We can embed functions inside an object like this:

class Car

{

honk()

{

//Play honk sound here.

}

}

This would be executed by calling:

myCar.honk();

Read more about classes in javascript here.