Programming For Beginners, THE Fundamentals: Volume 1: Theory
Programming For Beginners, THE Fundamentals: Volume 1: Theory
FOR BEGINNERS,
THE FUNDAMENTALS
Basic programming concepts with Fractals
Volume 1: Theory
PROGRAMMING
FOR BEGINNERS,
THE FUNDAMENTALS
Basic programming concepts with Fractals
Volume 1: Theory
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
2
A Bearing E-Book
The information in this text is distributed on an “As Is” basis, without warranty. While every precaution has
been taken in the preparation of this work, the author shall not have any liability to any person or entity
with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information
contained in it.
Product and company names mentioned herein may be the trademarks of their respective owners. In
place of using a trademark symbol with occurrences of trademarked names, I am using the names only in
an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 License.
You can find relevant license information at http://creativecommons.org/licenses/by-nc-sa/4.0/ .
CONTACT
If you have questions, requests, praise, criticism or just feel like saying hi, please email me at:
CONTRIBUTIONS
This book is provided free of charge, but who doesn’t like happy little surprises ? If you feel like
encouraging me to continue writing, I welcome your help in any of the following formats.
(This is entirely up to you ofcourse. If in doubt, do save your cryptocurrency for a rainy day.)
3
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
ATTRIBUTES
I have used content from Pixabay ( https://pixabay.com ) for some of the illustrations in this book. All
content were marked « Free for commercial use, no attribution required ». However, I figure it is only fair
to give credit where credit is due. These are [email protected] who have graciously created and made
available content of their own for free:
openclipart-vectors ( https://pixabay.com/users/openclipart-vectors-30363/ )
clker-free-vector-images ( https://pixabay.com/users/clker-free-vector-images-3736/ )
stux ( https://pixabay.com/users/stux-12364/ )
mahuasarkar ( https://pixabay.com/users/mahuasarkar-5775515/ )
jjuni ( https://pixabay.com/users/jjuni-27151/ )
mocho ( https://pixabay.com/users/mocho-156870/ )
200degrees ( https://pixabay.com/users/200degrees-2051452/ )
mohamed_hassan ( https://pixabay.com/users/mohamed_hassan-5229782/ )
pagdev ( https://pixabay.com/users/pagdev-4749277/ )
tkaucic ( https://pixabay.com/users/tkaucic-1450822/ )
haticeerol ( https://pixabay.com/users/haticeerol-14967706 )
mashiromomo ( https://pixabay.com/users/mashiromomo-3944009/ )
jorgeduardo ( https://pixabay.com/users/jorgeduardo-8516248/ )
janjf93 ( https://pixabay.com/users/janjf93-3084263/ )
davidrockdesign ( https://pixabay.com/users/davidrockdesign-2595351/ )
thedigitalartist ( https://pixabay.com/users/thedigitalartist-202249/ )
workandpix ( https://pixabay.com/users/wokandapix-614097/ )
martinelle ( https://pixabay.com/users/martinelle-495565/ )
ryanmcguire ( https://pixabay.com/users/ryanmcguire-123690/ )
Startupstockphotos ( https://pixabay.com/users/startupstockphotos-690514/ )
Should you find that the list is incomplete, or that I have made use content that is not free to use, please
contact me with the proper details so I can act accordingly.
10 9 8 7 6 5 4 3 2 1
4
A Bearing E-Book
5
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
6
A Bearing E-Book
About t he author
Hi there! My name is Bjørn Inge Westerheim. I hold a masters degree in
industrial engineering and am part owner of an IT company in Norway.
I have worked in the field of IT for more than two decades. I was part of the
development team that pioneered conversion to Digital Cinema in Norway,
creating both hardware and software solutions. Over the years, I helped training
cinema technicians in the use of some of these systems and I have helped
people of all ages learn how to build and use computers.
About t he book
This book is conceptualized, prewritten, drafted, proofread, illustrated, edited
and published by the author alone. All done purely in my spare time.
I have tried to weed out typos and wordy sentences, but every time I think I am
done, I find another section wordy of rewriting or diagram that needs adjusting.
I feel I have passed the 80%-threshold and reached the point where it is worth
sharing. Otherwise, I am afraid it would never see the light of day.
7
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Throughout the book, I will touch on basic math to explain certain topics. You
may benefit from having at least a passing knowledge of basic math, but I will
do my best to explain everything in detail.
If you had some previous experience in programming (e.g. you took a basic
course in programming at some point), but you forgot all about it, this course
may be for you as well.
If you are familiar with programming concepts, but feel the urge to get back in
to programming, you may want to quickly skim through this book, and then jump
quickly over to “Volume 2: Creating code”
If you already know the basics, but want to know how to build a basic fractal
image generator, you probably can find a tip or two herein.
What i s in Volume 2?
I have divided the tutorial into two parts. Each part covers the same material,
but from different perspectives.
In the book you are reading now, I will try to expose you to all the basics you
need to get started programming. It contains all the dry theoretical parts.
8
A Bearing E-Book
C O N TE NTS
9
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
10
A Bearing E-Book
TABLE OF FIGURES
Figure 1-1 Traditional computing devices ............................................................................................................................................ 2
Figure 1-2 Non-traditional computing devices ................................................................................................................................... 2
Figure 1-3 Moving data.................................................................................................................................................................................3
Figure 1-4 The programming vehicle..................................................................................................................................................... 5
Figure 1-5 The compile process ............................................................................................................................................................... 6
Figure 1-6 Snapshot of in memory commands ................................................................................................................................... 7
Figure 1-7 Long term memory storage ................................................................................................................................................... 8
Figure 1-8 QR Code ........................................................................................................................................................................................ 9
Figure 1-9 Saving progress........................................................................................................................................................................ 9
Figure 1-10 Permanent storage fallback ............................................................................................................................................. 10
Figure 1-11 Memory blocks ....................................................................................................................................................................... 10
Figure 1-12 20k memory .............................................................................................................................................................................. 11
Figure 1-13 Storing string data ................................................................................................................................................................ 11
Figure 2-1 The concerns of a computer program ........................................................................................................................... 14
Figure 2-2 Stripping comments during compile process ............................................................................................................ 15
Figure 2-3 String comparison ................................................................................................................................................................. 17
Figure 2-4 Object holding collection of decimal numbers .......................................................................................................... 18
Figure 2-5 The String object .................................................................................................................................................................... 19
Figure 2-6 Empty String object ............................................................................................................................................................... 19
Figure 2-7 Data type symbols ................................................................................................................................................................. 20
Figure 2-8 Symbol usage examples .................................................................................................................................................... 20
Figure 2-9 The variable ............................................................................................................................................................................. 21
Figure 2-10 Storing data in memory through variable assignment ........................................................................................ 21
Figure 2-11 Assigning a value to a variable ...................................................................................................................................... 22
Figure 2-12 Matching data types and variables .............................................................................................................................24
Figure 2-13 Applying formula for circumference of a circle........................................................................................................24
Figure 2-14 Applying division and modulus operations .............................................................................................................25
Figure 2-15 Remainder only result ....................................................................................................................................................... 26
Figure 2-16 Elements of a divison......................................................................................................................................................... 26
Figure 2-17 Storing the wrong data type to a variable ................................................................................................................ 28
Figure 2-18 Automatic cast of integer value to decimal.............................................................................................................. 28
Figure 2-19 Multiplying an integer and decimal with decimal result ..................................................................................... 31
Figure 2-20 Multiplying an integer and decimal value with integer result ..........................................................................32
Figure 2-21 Collection types .................................................................................................................................................................... 33
Figure 2-22 Memory arrangement ...................................................................................................................................................... 35
Figure 2-23 Managing data with List<int> ....................................................................................................................................... 35
Figure 2-24 List containers ..................................................................................................................................................................... 36
Figure 2-25 Managing items with List<int> ......................................................................................................................................37
Figure 2-26 Object function..................................................................................................................................................................... 38
Figure 2-27 The Function definition ..................................................................................................................................................... 39
Figure 2-28 Calling functions on the List<> object ........................................................................................................................ 39
Figure 2-29 Memory arrangment in List object .............................................................................................................................. 40
Figure 2-30 Storing int in List<int> collection ................................................................................................................................... 41
Figure 2-31 Storing and representing 2-dimensional lists ........................................................................................................ 44
Figure 3-1 Documenting code with diagrams................................................................................................................................. 53
Figure 3-2 Function with input and output ........................................................................................................................................57
Figure 3-3 The ‘getPi’ function ............................................................................................................................................................... 58
Figure 3-4 The ‘add’ function with two inputs................................................................................................................................. 59
Figure 3-5 Slope of P1-P2 ......................................................................................................................................................................... 62
11
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
12
A Bearing E-Book
13
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
14
A Bearing E-Book
Now, where do we find a topic that covers all of this, while also being simple
enough for complete beginners to grasp?
Eventually this approach has led me to the wonder of fractals. You have
probably seen them in their various shapes at some point. They come in
different forms, but all have this recognizable complex quality to them.
15
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The image below shows a section of a fractal known as the Mandelbrot fractal.
It looks like the code needed to create this is very complex. Luckily, that is not
the case at all. In fact, the nice thing about fractals is exactly that. They exhibit
complex properties, but are born from very simple rules.
If you were feeling brave, you could actually do the calculations by hand. The
calculations only require basic math skills, but you would need a lot of extra time
on your hands. A high-resolution image could require hundreds of millions of
calculations. It would take you a lifetime by hand, but with the help of a
computer, you can have the image ready in seconds.
It sounds a lot more fun than building a calculator app, doesn’t it?
16
A Bearing E-Book
The problem with programming is that you need to understand both the big
picture and the small picture all at once.
is the book you are reading now. It aims to introduce you to the basic
concepts of programming as succinctly as possible.
walks you through all material from , but in the context of writing
and executing code.
17
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
In general, there are alot of dependencies. Most of these are possible to learn
just fine, but we want to avoid having to worry about too many details all at once.
That is why I shall save all those gritty details for “Volume 2”. In this book, we
will only focus on the matter at hand; the basics of programming. We want to
explore programming concepts and the language we use to implement them.
We shall do so in the scope of building a graphical application.
The book
The examples
18
A Bearing E-Book
If you hate fractals with a passion, I guess you are out of luck though. My sincere
apologies about that.
The student
You do not have to arm yourself with pen and paper to read this book. Just come
at it casually, but with an openminded attitude and an intention to learn. Try to
focus on the main concepts presented. Most important of all; take your time.
If you feel they do not help, skip them. Just skim through til
you reach the next paragraph. Try to make a note of the
programming concept being taught, but do not get hung up
on the content of examples.
19
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Avoid letting frustration derail you. Focus on the big picture and your intention
to learn.
I will repeat myself throughout the book, so chances are you will have more than
one chance at comprehending a specific topic.
The outcome
Once you feel you grokked everything in this book, it is time to get your feet wet.
In “Volume 2: Creating code” I will show you exactly how to get up and running
with your programming environment and producing applications of your own.
Since content in the next volume deal with specifics on creating code, it ties in
with specifics of programming such as choice of programming language and
environment.
Different languages will implement the same concepts in their own way.
Sometimes the only difference is in naming schemes, other times there are
conceptual differences
20
A Bearing E-Book
I have planned multiple language editions of the second volume. Either book will
follow the outline laid in this book, but the chosen language will dictate the final
form of each book.
The first two editions are based around ‘Visual C#’ and ‘Python’. God willing, I
will be able to expand the selection with editions covering more languages and
perhaps on multiple platforms.
21
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
22
CHAPTER 1
The Background
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
1. THE BACKGROUND
However, these days just about everything around us come with computing
devices embedded. Anything from the car to the fridge may have some sort of
smart functionality.
2
A Bearing E-Book
Furio us ly f ast
A modern computer is extremely good at calculations. It is also very good at
moving bits of data around. Data can be text, numbers, images, documents,
video clips, audio clips etc. Anything you can find stored on your mobile phone
or computer.
Moving data
Writing code
The process involved when creating a computer program will involve a lot of
planning. There will be doodling on paper or whiteboards and a lot of thinking,
but eventually we need to tell the computer exactly what it should do.
3
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
When your collection of commands fully solves a problem, you have yourself a
program. Or rather, you have the code necessary to create your program.
Programmin g languages
There is a multitude of different of computer languages available to us. We have
Java, C/C++, C#, VB.Net, Go, Python, PHP, Javascript and many many more.
Different languages may serve different purposes. Some are good for
programming robots, while others are suited for building web content.
Some give you a high degree of flexibility and responsibility, while others
safeguard you through restrictive measures.
Which language to choose, will depend on your specific requirements, but also
on your preferences.
Programming can vary in all sorts of manners, but we can roughly divide them
into two categories:
We shall focus on the first type, also known as imperative languages. We will
program the computer by telling it how it should do things.
4
A Bearing E-Book
Choice of language
So, which language are we going to use in this book? Well here is the twist: I am
not going to tell you.
The thing is; you do not really need to know. At least not yet. The language itself
is just a vehicle to explore the concepts of programming.
Exactly which language we use, is irrelevant for now. Once you understand the
concepts presented in this book, you can easily apply them to most (imperative)
programming languages.
Some books make use of something called ‘pseudo-code’. That is; English
language disguised as a programming language or perhaps a programming
language disguised as English. The idea is to make it independent of any
specific programming language.
I figure we will reach our goal much faster, if we take advantage of a real
language right away. It saves us some effort, and you can easily convert it to a
language of your choosing when the time comes. This is especially true because
several of the popular programming languages are quite similar.
5
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Compiling code
Once we have finished writing our code, we must run it through a compiler. The
compiler converts our code into a binary format that can run on your computer.
The computer does not understand text as humans do. It understands numbers.
It must translate every piece of data into numbers to be able to comprehend it.
It does not matter if it is a text file, a picture or a music video; to a computer
everything is numbers.
Let us say we wanted the computer to store the value ‘2’. From the computer’s
perspective, the command could look something like this:
B8 22 11 00 02
It looks rather cryptic. It is possible to figure out what it does ofcourse, but it is
incomprehensible for the uninitiated, and it gets even worse. Even a small
6
A Bearing E-Book
To fix it, we make use of labels. We assign names to commands and memory
locations that are much easier for us to work with.
position = 2
We simply need to have this translated into the previous format so the
computer can easily make sense of it. This is exactly what the compiler does for
us.
The actual process is a little bit more complicated, but that is the gist of it.
7
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
1.2 . M E MO RY
The computer needs access to the data it is supposed to work on. We store
data in computer memory, which comes in different flavors. They can vary
greatly in how they perform, so we shall categorize them by how fast the
computer can access them:
SLO W MEMORY
The term “slow memory” is a bit misleading. It is not slow by any means. The
main attribute of this memory type, is that it can hold on to data without power.
You may wonder why I did not categorize it according to that attribute instead,
but hold on to that thought. I will tell you why in a moment.
This type of memory needs power to operate, but once data is stored, it stays
there even after you unplug it. It is also relatively cheap, so it it is well suited for
long-term storage of data of any size.
USB Sticks
Memory cards
A piece of paper
Long term memory storage
This is where we store our documents,
videos, drawings etc. between uses. The data will always be there when you
choose to retrieve it.
8
A Bearing E-Book
You would think I was in error on that last item, but a piece of paper does indeed
qualify as computer storage. It does not share features with any of the other
storage types, so how does that work?
If we print the QR code onto a piece of paper, we have in fact stored the data
permanently or at least for as long as the paper lasts.
Comparedc to other storages, the QR code can store a very limited amount of
data, so would we ever use this for long-term storage? Well, yes we do. They
are quite common in public spaces to promote some company or government
website, which is where you would probably have seen them. They are also
popular with paper wallets for crypto currency.
FAST MEMORY
Fast memory loses its data if you disconnect power. If you need to resume
working on something later, you would have to transfer it from fast memory to
one of the slow memory alternatives. This is exactly what happens when you
choose "Save as" in an application.
Saving progress
9
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Having to worry about saving your work all the time seems like a big drawback.
You could be tempted to think it is better to make use of ‘Slow memory’ all the
time. The proof is in the pudding as they say.
however, is exceptionally
fast. It can easily march in lockstep with
the rest of your computer.
These blocks are all lined up on an exceptionally (imaginary) long line, one after
another.
Memory blocks
10
A Bearing E-Book
If we want to write some data into a single memory block, we have to explain
exactly which block we want to access. The most straightforward way would
simply be to count the blocks.
Referencing memory
Imagine we have a memory that is 20.000 blocks long. We want to store the
string “OggiTheCat” somewhere. Every block holds one character.
20k memory
If we know there is free memory starting at the 8888th block, we can simply tell
the computer that we want to store our data at that position:
11
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Getting to data in memory is actually as easy as that. You simply provide the
position in memory where you want to store or retrieve data. To read or write
data, you must also indicate how many memory blocks you want to modify, but
that is all there is to it.
Let us see what the computer can do to help us in the next chapter.
SUMMARY
When we build programs, we write commands in text files. We use a compiler
to convert these into something the computer understands natively and can
execute.
Computers are exceptionally fast. When they work with data, those data must
be stored somewhere that can deliver the goods equally fast.
When we are done working with our data, we store them for safekeeping in
slower, less expensive memory.
The computer, reference memory in distinct blocks, where each block has a
unique address. It can read or write segments of data to and from memory as
needed.
12
A Bearing E-Book
CHAPTER 2
T he Building blo cks
13
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
2 . B U I L D I N G B L O C KS
When programming a computer, we must provide some basic information:
The computer always works with data, in one way or another. We need to tell it
where the data is, what type of data it is and what to do with it.
Before we can say anything about location of the data, we need to know what
they are. We need the concept of .
We shall have a look at data types right after we cover one of the most
important tools you have as a programmer;
14
A Bearing E-Book
2 .1 . COM M ENTS
The intention behind our code is not always obvious. Sometimes it is clear in
your head while typing, but give it a week and you will have no idea what you
were thinking. It happens more often than you would think.
The ability to comment on sourcecode directly is very useful. We can add these
comments, by using an identifier. It may sound difficult, but the identifier is
simply a string of letters that indicates the start of a comment.
Let me demonstrate:
We will have a more detailed look at the use of comments in a later chapter.
15
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
2 .2 . THE DA TA TY PE
Let us look at the available data types. Most programming languages has quite
a few, but the following selection will serve us quite well:
Data types
specifies a data type in your code. The compiler uses the keyword to
convert our sourcecode to binary code.
Every programming languages has its own set of naming rules for keywords.
Our keywords are all in lowercase, because our language is case-sensitive.
16
A Bearing E-Book
Integers (int)
This data type holds whole numbers. An integer can be negative,
positive or zero, but it cannot contain fractions.
In practice, we use a representation that is close but not exact. This works fine
in most cases as we can safely assume ‘0.000000000000001’ and ‘0’ is the
same thing for most practical purposes.
A language usually offers more than one decimal data type. Each can represent
a decimal number, but with different precision. We can use higher precision
data types when needed, but they may be slower to work with. Alternatively, we
can use ones that are fast to work with, but they may be less precise.
17
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The object
Sometimes we have data and functionality that belong together.
We can wrap it all up into a single unit and pass it around. We
refer to that unit as an .
The diagram above shows an object that hold a list of decimal numbers and
provide functionality that exposes statistics about its content.
18
A Bearing E-Book
A null value has no value other than It has no numeric value, no length or
any properties you can work with. It simply means there is nothing there.
19
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The symbols
We will describe all the data types in more detail, as soon as we start using them.
I have introduced a set of geometrical shapes to visualize different types of data
types. I will make use of these in diagrams in this book to visualize data types
and their interactions.
Note that this is not following any software standard. It is simply a visual tool
used within this book.
20
A Bearing E-Book
We saw earlier that data can be stored at a given memory address. Given the
size of the memory, the address could be a very long number.
21
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Let us say we want to store a decimal value. Our code would look something
like this:
double Pi
The keyword , informs the compiler that we want to store a decimal value
somewhere in memory. We want to refer to our data, as Pi .
I included the memory arrangement in the previous diagram, but at this point,
you can safely tuck away details on addressing memory. All we care about is
our variable Pi and that it holds a single decimal value. The programming
language takes of the rest.
Assigning a value
Once we have defined a variable, we can store a value into it:
Pi = 3.14
The equal sign is used to assign a value. The command tells the compiler to
take the value on the right hand side of the equal sign (3.14), and store it into our
variable ‘Pi’.
22
A Bearing E-Book
Addition
Subtraction
Multiplication
Divison
Simple calculations
Let us use the information we have and try to calculate the circumference of a
circle:
I have commented each command as they occur. Normally we will not be this
heavy-handed on the comments while coding, but for now, they will make it
easier to follow along.
23
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The result of the calculation is ‘18.84’. Once the command has completed, this
value is then stored in the variable ‘Circumference’.
When performing calculations, we must ensure all data types are the same.
Mixing data types, may lead us into trouble. The diagram below indicates how
values with datatypes and , are stored in variables of the
corresponding data type.
24
A Bearing E-Book
When dividing two integers you get an integer value and a remainder. In code,
the result of the division operation is an integer value. The language simply
discards the remainder, but sometimes we may be interested in knowing the
value of the remainder.
Let’s say we want to know the remainder of dividing ‘3’ by ‘2’. We can rewrite
this as shown below:
In other words ‘3’ divided by ‘2’ can be expressed as the whole number ‘1’ plus
the remainder of one ‘1/2’. The modulus opertiona therefore returns ‘1’:
3 % 2 // Returns 1
25
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
4 / 5 // Returns 0
4 % 5 // Returns 4
Remainder only result
You may find this easier to understand if we see it in action. Let us go through
a few examples where we divide an integer by 256.
The remainder increases from ‘0’ up to ‘255’ and then resets back to ‘0’. It will
always be a value in the range [0 to 255].
Do you see where we are going with this? We can use the modulus operator to
clip a value to a range.
26
A Bearing E-Book
0%256 = 0 0/256 0 0
1%256 = 1 1/256 0 1
2%256=2 2/256 0 2
… … … ..
256%256 = 0 256/256 1 0
The code below will always result in a value in the range [0 to 255], no matter
how large the variable ‘myintegervalue’ is:
myintegervalue % 256
We can use this to guarantee that a value stays inside a given range. This shall
come in handy later in the course.
27
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We should ask ourselves what it is we are trying to do. Should we drop the
fractional part? Should we round the decimal to the nearest integer? Do we
know at all? Well, if we do not know, how would the computer know?
The diagram below demonstrates a property that can work to our advantage. It
is unproblematic to use a decimal to describe an integer value.
That may make sense to you, if you think about it for a second. ‘24’ is the same
as ‘24.0’, ‘3’ is the same as ‘3.0’ , ‘-5’ is the same as ‘-5.0’ etc.
28
A Bearing E-Book
We declare the variables ‘sum’, ‘x’ and ‘y’. All of them hold integer values. We
then calculate the sum of ‘x’ and ‘y’, and store the result in ‘sum’.
The major difference from our previous example is that we add the values
instead of multiplying them.
There is a big chance this will give your compiler hiccups. After all; what does
the expression ‘3 + “Person”’ even mean?
Even if this was what we intended to do, the compiler has no way of knowing
that we did, so it will simply stop and tell you to fix it.
In some languages, the compiler may attempt to infer the operation. It could try
to assign a numeric value to the string “Person” and use that value to calculate
29
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
a final value. It could assume you meant to merge the two into the string
“3Person”. The actual result would depend on your chosen language.
Automatic casting
What happens if we mix data types that seems like they should work together,
allthough the data types are different?
The code below multiplies a decimal value with an integer value, and stores it in
a variable expecting a :
At first glance, it seems this should work just fine. It is just ‘3 times ‘5’, right? Well,
computers can be quirky about these things.
It is essential for the compiler that the data types match. The variable ‘product’
must hold values of type since that is how we declared it.
We must ensure that the value we want to store in ‘product’ have that same
data type. For the product calculation to work, this statement must result in a
x * y
Luckily, the compiler is smart enough to figure this out on its own. An integer
value will always have a decimal counterpart. The integer ‘5’ represents the
same quantity as the decimal value ‘5.0’.
30
A Bearing E-Book
The compiler can do this conversion on the fly. It converts the value of ‘y’ into a
as needed. This ensures that every value in the calculation have the
same datatype and that the result is of type
Problem solved! Great, so it turned out not to be such a big problem after all.
From here on, we go ahead and let the compiler take care of things. Right?
31
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Since ‘product’ expects an integer, our calculation must also produce an integer.
For that to work, the compiler must convert the value to
That poses a problem. We can convert by rounding the decimal value to the
nearest integer ‘4’, but as far as the compiler is concerned, ‘3.6’ and ‘4’ are
completely different values. So how would it know if that conversion is valid or
not?
There is a better way. We choose the datatype that makes sense to use for a
given scenario. If we expect calculations that deal with decimal data, we choose
the datatype. If we work with text data, we choose etc.
32
A Bearing E-Book
First, let us look at how to work with a range of data without a dedicated
collection data type.
Summing variables
Note that I have combined declaration and assignment of each variable onto
one line. It makes the code more compact and a little easier to read.
33
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Computers can manage data sets that have a lot of data. There can be millions
of items in one data set. Now imagine using the solution above, to sum up a
million integers. It would be a nightmare.
Introducing Li st<>
The name looks a bit alien, but it is not that complicated. The ‘<>’ is jsut a
placeholder for the data type the list works with:
Before we continue to make use of these types, let us look at how we would go
about to manage several items of data.
34
A Bearing E-Book
Invoking List<>
When we introduced variables, we talked about how data is stored in memory.
We can arrange all these variables so they are located one after another, like
this:
Memory arrangement
As long as we retain their order, we can easily access these values by their
position rather than name.
Now hold on just a minute! This is starting to look an awfully lot like the topic of
memory addressing that we dealt with in the first chapter. Didn’t we introduce
variables to get away from all of that? Well yes, we did, and for good reason.
The type takes care of all the minute details, and lets us refer to an item
in the collection by position. It makes it very easy for us to store and retrieve
data from within a collection.
35
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
All variables in a collection must have the same data type. This is usually the
case, so it is not a very limiting restriction. At least not for the purpose of this
book.
Let us look at some code to see how this can benefit us. The following code,
uses a object, to build a list of five integers, as we did earlier:
First, we declare the variable ‘manager’ The name of the variable is not
important. We could have chosen ‘serialnumbers’, ‘data’, ‘piggybank’ or any
other name. It is simply a label.
36
A Bearing E-Book
List<int> manager
The syntax may seem new and weird, but don’t get hung up on it. It simply
creates a new object of type before storing it in the variable.
The assignment works the same as for any variable declaration. The difference
lies in how we access our data.
For other data types we have seen, there is a one-to-one relationship between
the value and the variable. When working with collections we access items in
our collection through the object.
37
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
This calls ‘Add’ on the ‘manager’ to populate our collection with new values. By
calling, I mean that we make use of the function. We commonly refer to this as
‘calling’ a function.
Object function
38
A Bearing E-Book
In short, a function is a piece of code given a name. It may take some input and
it may provide some return value.
We can keep making calls to ‘Add’ to fill in more items in our collection:
I want you to realize how easily we can add new items to our collection. We do
not have to worry about memory allocation or managing collection items. We
simply make use of the functionality available to us through the object.
39
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We can now access any element in the collection by referring to its position in
the collection.
We refer to the numeric value of the position as the . The first item added
is at index 0, the starting point of our list. The second item added is located at
index 1, the third at index 2, and so on.
For example, if we wish to assign a new value to the third item in the list, we
address the item with index 2.
manager[2] = 888
In the diagram below, I have illustrated the action of storing the integer value
‘888’ into the third element in collection.
40
A Bearing E-Book
Let us try a complete example, where we sum up all the values in our list:
41
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We add values to the list. Note that I have put multiple commands per line. This
is just to save space. We use semi-colon to mark where a command ends, and
a new one starts.
42
A Bearing E-Book
It reads almost as if written in plain English. “For each item in the collection, add
the item value to the sum”.
You may ignore the details about the code for now. I simply want you to
appreciate how the calculation part of the code, was reduced from ‘6’ to ‘2’ lines
of code.
Looping constructs will come in handy when working with screen data. We shall
cover them in full detail in “Chapter 4”.
2-dimensional lists
When I first introduced the type I said it could handle any of the data
types I have introduced to you, including itself.
That means we can create a list of lists, which will serve as a 2-dimensional list.
The diagram in illustrates how this would work for a 5 by 3 list of
integers
43
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We have a collection of three lists, one for each line in our table. We address the
line by providing an index into to this collection.
I have named it the ‘line index’ in the diagram. Once we have identified a line,
we provide a second index to identify the item we wish to access.
List<List<int>> screen
Given two index variables ‘x’ and ‘y’, this is how we index items:
screen[y][x]
44
A Bearing E-Book
Let us look a bit closer at this, to understand how the indexing works.
We use ‘y’ to address a specific line in the screen collection. ‘x’ identifies the
item in that line. We can skip the extra variable:
( Screen[y] )[x] = 0
Screen[y][x] = 0
and we are back to the form I first showed you. Note that The order is
and not as some would have expected.
// DECLARATION OF ARRAY
string[] s // Declares a string array variable
s = new string [3] // Create a new array with room for 3 elements
// POPULATE ARRAY
s[0] = “one” // Store the string “one” in the 1st position
s[1] = “two” // Store the string “two” in the 2nd position
s[2] = “three” // Store the string “three” in the 3rd position
45
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The brackets following the typename indicates that we are working with an
. Just like for you can access each item through indexes.
new string [3] // Create a new array with room for 3 elements
The number between brackets, determine the size of the array so it can hold
three items.. It can only hold items with a data of type .
s = new string[]{“one”,”two”,”three” }
We will use in most cases, as it does most things do, but is easier to
use. However, we can take advantage of the shorthand way of populating
arrays when initializing a object.
We used this code earlier to declare and populate a list with integers:
It is shorter and easier to read, so we will use this method to initialize lists from
hereon.
46
A Bearing E-Book
2 .5 . S UM MA RY
We talked about data types and storage. We explored how to work with
variables, and how we could go about to do simple calculations. We spent some
time looking at the creation and use of collections.
Do not worry if you feel a bit shaky on some details. As with any technical text,
it might be worthwhile to revisit topics that was unclear, but it is quite normal to
feel a bit overwhelmed at this stage. Just make sure your focus is on
understanding the main concepts.
You should aim be at least somewhat familiar with the following concepts:
Data types
Variables
Performing basic calculations
Working with collections
Try to explain these concepts to yourself in plain English. What does each
concept entail? How do we relate to these concepts as programmers?
47
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
48
A Bearing E-Book
CHAPTER 3
Better Code
49
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
3. BET T ER CODE
Now we know how to store and access our data. Next, we must find ways to
work with them. We need to know how to traverse large amounts of data, how
to repeat calculations, how to make choices and more.
We shall cover these concepts in the next chapter, but first I want to cover the
aspects of building good code.
It is very easy to write bad code. Bad code may compile into a working program,
but can be very difficult to understand. Even experienced programmers may
struggle with reading badly written code.
The compiler has no issues with the complexity of your code. It deals with rules
and numbers. If you avoid breaking any of the rules, it will not complain. That is
not a luxury afforded to the average developer. If things gets too large or to
complicated we struggle to understand.
Unfortunately, code tend to grow fast, even for simple applications. A basic text
editor can reach thousands of lines of code. That is the size of a small book. How
do we go about handling this amount of code?
The better you are at writing good code, the easier it is to understand it. The
better you are at comprehending code, the faster you will be able to spot good
or bad code. It does not matter if you wrote it yourself a month ago, or someone
else wrote the code. Good code is generally easy to read, bad code is not.
50
A Bearing E-Book
Similarly, if your code is just a long list of commands with no breaks or spacing,
it will be difficult to read.
double a,A,px1=10.0,py1=2.0,px2=20.0,py2=3.0,x1=11.0,x2=15.8
a=( py2-py1 ) / ( px2 - px1 )
A=a*(x2 - x1)*(x2-x1)/2
It is not a very long code snippet, and it is actually not that complex, but what
does it do? It is not at all obvious. There are no comments or anything to shed
light on its intention.
Let us examine it. The top line defines a bunch of variables, and assign some
values to some of them.
When you define multiple variables of the same type, you do not have to repeat
the data type. We can write code to declare four variables as follows:
double a,A,px1,px1
51
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The idea is ofcourse to save space. Sometimes it makes sense to push multiple
commands onto a single line, but in our example, it has become cluttered. Let
us try to reorganize the code, to make it clearer:
double a; double A;
double px1=10.0
double py1=2.0
double px2=20.0
double py2=3.0
double x1=11.0
double x2=15.8
a = ( py2-py1 ) / ( px2 - px1 )
A = a*(x2 - x1)*(x2-x1)/2
We have put comments to good use in this book so far. Let us introduce some
comments to our program:
// VARIABLE DECLARATIONS
double a; double A;
// CONTROL POINT P1
double px1=10.0 // X coordinate
double py1=2.0 // Y coordinate
// CONTROL POINT P2
double px2=20.0 // X coordinate
double py2=3.0 // Y coordinate
Right! That is much better. The comments now reveals that we have two
control points ‘P1 and ‘P2 . The line between them limits the range of two other
52
A Bearing E-Book
values ‘x1’ and ‘x2’. We calculate the slope of this line and use it to calculate an
area of a triangle.
Admittedlyi, we may not have deciphered it completely, but a simple glance now
tells you it is calculating the area of a triangle. Looking at the original code, we
did not get much wiser at all.
Comments are good for explaining immediate details. To get a general view, we
would require more structured documentation.
For example, diagrams or images can be very helpful in providing context. The
diagram below gives us a clearer view of the data the code is working with.
Building such documentation is a whole topic by itself, and is outside the scope
of this book. However, I want you to realize how readily available such
information is in the shape of a diagram.
Do not let the math involved distract you too much. Try to focus on the
programming aspects of the code. This is all about the formatting of code and
using the tools at our disposal to make it readable. Note how accessible the
reformatted code is, compared to the original.
53
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
However, single letter variable names do not reveal their purpose. Without
context, you cannot say much about a variable if it is called ‘Z’, ‘a’ or ‘q’. A variable
called ‘ListOfNames’ however, clues you in right off the bat.
Now, building good code takes time. It takes foresight. It takes planning. In
general, you will spend way more time reading code than writing it.
The upside of that statement is that you do not have to worry about the length
of your variable names. In fact, your code will benefit from using variables with
descriptive names.
Let us rewrite our code example. We will use the naming scheme as shown to
the right:
// VARIABLE DECLARATIONS
double Slope; double Area;
a → Slope
// CONTROL POINTS
double Point1_X = 10.0, Point1_Y = 2.0 A → Area
double Point2_X = 20.0 , Point2_Y = 3.0
px1 → Point1_X
// TRIANGLE BOTTOM CORNERS
double Left_X = 11.0 // On the line P1->P2 py1 → Point1_Y
double Right_X = 15.8 // … ditto
px2 → Point2_X
// AREA OF RIGHT ANGLED TRIANGLE py2 → Point2_Y
// Slope P1 and P2
Slope = (Point2_Y-Point1_Y) / (Point2_X- Point1_X)
Area = Slope*(Right_X-Left_)*(Right_Y-Left_Y)/2
Choosing good variable names is not easy, but as long as we put some thought
into naming our variables, it will lead to better code.
54
A Bearing E-Book
We should try to choose names that describe the purpose well. It makes the
code easier to read. In general, you should aim for code that reads like English,
as much as possible.
We introduced the intermediary calculations for ‘RateX’ and ‘RateY’. The slope
calculation now looks like the formula for the slope of a line:
55
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Did you notice how we could remove some of the comments? We no longer
needed them, as the code clearly communicates what it does.
Let us have a look at the whole program, with all changes implemented.
// VARIABLE DECLARATIONS
double Slope; double Area;
// CONTROL POINTS
double Point1_X = 10.0, Point1_Y = 2.0
double Point2_X = 20.0 , Point2_Y = 3.0
Compared to the original, this code is much clearer. It is easier to understand its
purpose.
Our code has grown quite a bit. The original was five lines long. It is now close to
twenty. You would be tempted to think this is a bad thing.
On the other hand, the number of lines must grow as we keep adding comments
and splitting up code. A bit of a conundrum!
We can rectify that, by splitting up the code. Let us look at how to do that next.
56
A Bearing E-Book
3 .5 . THE F UN CTIO N
Allow me to introduce a very helpful tool in our arsenal; the function. We briefly
talked about them in an earlier chapter. Back then, I defined a function as ‘a set
of code, given a name’. It may require input and it may return some value of a
given data type:
Assume we want to call a function getPi that returns the value of Pi:
double PI = getPI()
double getPI()
{
double pi = 3.14
return pi
}
The parentheses are used to provide input. In this case, none was needed, so
they remain empty. The curly brackets define the start and the end of the
function code. I will refer to this as the .
57
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Functio n arguments
Let us have a look at an example where the function requires arguments.
Imagine a function that returns the sum of two integers in its input. The calling
code looks like this:
The function add takes the numbers ‘1’ and ‘2’ and returns an integer. This
returned value is then stored in the integer variable ‘sum
58
A Bearing E-Book
This time, the parentheses are no longer empty. We need to provide the
function with the values it should add together. In general, a function may
require any number of arguments. If there are more than one, we use a comma
to separate them.
Each argument is an integer variable. We can use these in our code, just as any
other variable declared inside the function.
In the function body (between the curly braces), we calculate the sum of ‘x’ and
‘y’, and return the result:
Note that the ‘result’ variable must be of data type since the function
definition states that the function should return an integer value
The diagram below, visualize the inner workings of ‘add’ given inputs ‘3’ and ‘5’,
59
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Returning values
Imagine we want to return a coordinate pair. That is, we want to return two
values from the same function call.
int a,b
(a,b) = getCoordinates()
For example, if our function returned (3,4), the previous command is just a
compact way of writing:
a = 3
b = 4
Now that we have seen how to define and use functions, let us try to improve
our program from before.
60
A Bearing E-Book
Splitting up cod e
In the previous chapter, we introduced and analyzed a piece of code to make it
easier to read. When we left it, it looked like this:
// VARIABLE DECLARATIONS
double Slope; double Area;
// CONTROL POINTS
double Point1_X = 10.0, Point1_Y = 2.0
double Point2_X = 20.0 , Point2_Y = 3.0
// VARIABLE DECLARATIONS
double Slope; double Area;
// CONTROL POINTS
double Point1_X = 10.0, Point1_Y = 2.0
double Point2_X = 20.0 , Point2_Y = 3.0
Slope calculation
Ordinate pairs calculation
Area calculation
61
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
It takes four arguments, performs the slope calculation and returns the result.
62
A Bearing E-Book
I have taken the liberty of shortening the names of the function arguments. You
may remember that I previously stressed the importance of using descriptive
variable names.
Presenting code in a book format, makes it hard to stick with long names
sometimes, but even from a programming perspective it does not seem to have
hurt readability that much.
The code is still concise and obvious. The shorter names, does not hinder
readability, in fact they make the code easier to read.
So when should we use long descriptive names, and when can we shorten? Only
if the context is very clear, should you consider using shortened names. If you
are in doubt, use descriptive names.
In this case, the function itself provides contextual clues. To be perfectly clear
within my code, I also provided a description in a comment preceeding the
function.
Next up is the calculation of y-values of points that fall on the line P1-P2.
We want to calculate the two corresponding Y-values for the given X-values
and return them simultaneously.
63
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The function must receive the values of ‘Slope’, ‘Left_X and ‘Right_X’.
It takes the slope value and the two x-values as inputs and use them to calculate
and return the corresponding values of y.
Due to the short function body, shortening variable names still works well.
64
A Bearing E-Book
At last, we want to extract the code for calculating the area. Let us figure out
the necessary inputs and outputs, from studying the original code:
Our function needs to know the point coordinates that define the triangle. That
is ‘Left_X’, ‘Left_Y’, ‘Right_X’ and Right_Y
65
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Again, I am using shortened variable names for the arguments, but otherwise
the calculations have not changed.
66
A Bearing E-Book
We can now replace the original code with calls to the appropriate functions:
// VARIABLE DECLARATIONS
double Slope; double Area;
// INPUTS
double Point1_X = 10.0, Point1_Y = 2.0
double Point2_X = 20.0, Point2_Y = 3.0
double Left_X = 11.0 // Lies on the line P1->P2
double Right_X = 15.8 // Lies on the line P1->P2
That is quite an improvement. The area calculation code is down to three lines!
There is ofcourse a lot more code when you count in the code hiding in our
functions, but as long as they do what they say they do, that is not a concern of
ours anymore. At least not as far as the main code goes.
There is one last improvement awaiting. Our code executes a very specific
operation. It makes sense to limit this code by putting it inside a function.
67
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The function should calculate and return the value of the area inside this triangle.
Let us create a function called ‘findTriangleArea’. We move the main code into
‘findTriangleArea’ and can then call this function from our main code:
// ARGUMENTS:
// P1_X, P1_Y: coordinates of first control point
// P2_X, P2_Y: coordinates of second control point
// x1, x2: x coordinates of points on the line P1->P2
double findTriangleArea( double P1_X,double P1_Y,
double P2_X,double P2_Y,
double X1,double X2)
{
double Slope; double Area;
Slope = getSlope(P1_X,P1_Y,P2_X,P2_Y)
(Y1,Y2) = getYCoordinates (Slope, X1, X2)
Area = calculateArea(X1,Y1,X2,Y2)
return Area
}
That looks quite clean. The function name along with the variable names
conveys the intent, without getting overly verbose. It is common to describe the
purpose of a function along with the code. I included this along with a short
description of the expected input.
Our main program has now turned into one line of code:
We can reuse this code. We call the function more than once for different inputs:
68
A Bearing E-Book
For reference, let us list the whole program, functions and all:
// MAIN
double Area_1 = findTriangleArea(10.0, 2.0, 20.0, 30.0, 11.0 )
double Area_2 = findTriangleArea(10.0, 2.0, 20.0, 5.0, 6.0 )
double Area_3 = findTriangleArea(10.0, 2.0, 20.0, 10.5, 10.55 )
// ARGUMENTS:
// P1_X, P1_Y: coordinates of first control point
// P2_X, P2_Y: coordinates of second control point
// x1, x2: x coordinates of points on the line P1->P2
double findTriangleArea( double P1_X,double P1_Y,
double P2_X,double P2_Y,
double X1,double X2)
{
double Slope; double Area;
Slope = getSlope(P1_X,P1_Y,P2_X,P2_Y)
(Y1,Y2) = getYValues (Slope, X1, X2)
Area = calculateArea(X1,Y1,X2,Y2)
return Area
} // ===========================================================
69
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Black box
This means that, as long as the expected inputs and output stay the same, you
can modify the implementation of the function as you wish. Your changes will
not affect any calling code. All they see is a “black box” with a given set of inputs
and output.
70
A Bearing E-Book
3 .6. S u mmary
We have looked at various ways to improve communicating the intent of our
code. We used comments to elaborate and to section code.
Careful use of variables and variable names can make code much easier to read.
In fact, properly named variables may eliminate the need for comments
alltogether.
As always, do not worry if you did not quite understand every example. The
most important take-away is to recognize how we can make our code easier to
understand and work with through good use of comments, variables and
functions.
71
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
72
A Bearing E-Book
CHAPTER 4
Work ing W ith Dat a
73
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
4 . W O R K I N G W I T H D A TA
4.1. M AKING CH O IC ES
The co nditio n
A program will on occasion need to make
Condition In code
decisions. The computer bases such
decisions on the output of tests that
Is X equal to Y? X == Y
return ‘true’ or ‘false’.
X>Y False
X == Y
X=0,Y=0
74
A Bearing E-Book
If we wrote it with only one equal sign, it would be difficult to tell the condition
test apart from an assignment:
X = Y // Condition or assignment?
Below are some samples of condition output, for values of ‘X’ and ‘Y’:
75
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The function isNegative' takes one integer and returns a string value. It returns
"yes" if the input is negative or "no" otherwise. We test if the input is less than
zero, and assign the result to ‘isNegativeValue’
The code reads almost like plain English: ‘If the value is negative, we return “yes”,
otherwise we return “no”’. The code explains itself, which is obviously a good
thing.
Have a look at the illustration in . I have illustrated the flow of code for
the function when the input is ‘5’.
The function receives the value ‘5’ and stores the value in the variable ‘input’.
It then tests if the input is less than zero. That is not the case so it returns ‘false’.
This Boolean result is stored in ‘isNegative’.
Finally, the -statement uses ‘isNegative’ to test which code block to run. The
first block runs in case the condition is ‘true’. The second block runs in case the
condition is ‘false’.
‘isNegative’ is ‘false’ so the block following the ‘else’ statement runs and the
function returns “no”.
76
A Bearing E-Book
For such a simple statement, the code is more readable pulling everything onto
one line, but the formatting is up to us. We could
spread the -statement over multiple lines if we
wanted to. if( isNegativeValue )
{ return "yes" }
The curly brackets group code just like for the else
function. Here we use them to group code that { return "no" }
It is all a matter of preference. If the condition is short and simple, like in this
case, it may make sense to skip the extra variable. If it is long and convoluted,
pulling it out to its own variable will make it easier for you to explain what is going
on.
77
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
If you turn that on its head, it means that a single operation takes almost no time
at all, quite literally. At least from our perspective. That is quite an amazing
power available to us, but how do we wield it?
The for-loop
The while-loop
The foreach-loop
78
A Bearing E-Book
We refer to the action of running through the code once as ‘one’ . When we
run through the same code multiple times, we refer to it as .
The -loop and -loop mainly differ in when they check the condition for
continued looping. The -loop is a variety of the for-loop.
We want to sum up the values of every integer in a list. The code to do this looks
as follows:
// RUN LOOP
while( index < maxIndex)
{
total = total + numbers[index] // Tally up the total
index = index + 1 // Pointing to next item in list
}
79
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
‘index’ goes through the values ‘0’,’1’,’2’,’3’ and ‘4’ in order. We use the current
index to retrieve an item value from ‘numbers’. Finally, we calculate the new sum
and update ‘total’ accordingly.
80
A Bearing E-Book
Let us trace the values as they change. The table below shows key values at
every loop:
The loop keeps going, untill we reach the end of the fifth step. After increasing
‘index’ it now has the value ‘5’.
81
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The fo r-loop
The while loop is great when you just want to keep doing something untill a
condition is met. Typically, you use it when you do not know ahead of time how
many times you need to execute your code.
When you want to repeat an action a given number of times, the for-loop is
often a better alternative.
// RUN LOOP
for (int i=0;i< maxIndex; i=i+1){ total = total + numbers[index]}
That looks shorter, but the for-statement looks a bit scary the first time you see
it. Let us have a closer look.
The command above runs through values of ‘i’, where ‘i’ takes the values:
‘0’,’1’,’2’,’3’ and ‘4’. The for-loop body executes for each value of ‘i’.
You may recall that we used the semi-colon to separate commands, when we
put more than one command on a line. It is the same thing happening here.
82
A Bearing E-Book
int i=0
The first part declares a looping variable and sets its value to ‘0’.
I am using a shortened name for the looping variable. We often use looping
variables as list indexes. To keep expressions short, it is quite common to use
single-letter names for these sort of variables. It is only a matter of preference
though. I could just as easily have named it ‘index’.
i < maxIndex
The second part tests whether the loop should continue or not. It ensures that
the loop variable ‘i’ holds a valid list index that point to an item in the list. , If it
does not, we exit the for-loop. Note that this test is performed before running
the loop.
i = i+1
The last part increases the value of the looping variable by ‘1’. The for-statement
executes this code after the code in the for-loop has completed.
83
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We count by one, but there is nothing preventing you from changing it in other
ways. You can count up in steps of ‘2’,’3’,’4’ or any other integer. You can even
count downards if you so please.
Let us illustrate with a few examples on how we can vary the counting variable:
The variable ‘x’ starts at ‘0’ and counts up by one as long as the value is less than
‘5’. It goes through the values: ‘0’,’1’,’2’,’3’ and ‘4’. The loop executes five times.
for(int birds =10 ; birds < 13 ; birds = birds +1) // birds = 10,11,12
{ sum = sum + 1} // some loop code
The variable ‘birds’ starts at ‘10’ and counts up by one as long as the value is less
than ‘13’. It goes through the values: ‘10’,’11’ and ‘12’. The loop executes three
times.
The variable ‘index’ starts at ‘0’ and counts up by ‘2’ as long as the value is less
than ‘6’. It goes through the values: ‘0’,’2’ and ‘4’. The loop executes three times.
84
A Bearing E-Book
The variable ‘q’ starts at ‘5’. It counts down by ‘1’ as long as the value is greater
than zero. It goes through the values: ‘5’,’4’,’3’,’2’ and ‘1’. The loop executes five
times.
The difference from the last examples is that we subtract one from ‘q’ at each
loop. Since ‘q’ is decreasing, we must adjust the condition so that it tests for
when ‘q’ goes negative
Loopi ng collections
In the chapter on data types, we introduced the type. It allows you to work
with collections of data. You can combine this with a looping-construct to easily
process large amounts of data.
Earlier, we saw an example on how to find the total of the items in a collection:
// RUN LOOP
for (int i=0;i< maxIndex; i=i+1){ total = total + numbers[index]}
85
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Assume we have two lists of integers instead of one. We wish to multiply items
at the same position and then find the sum of all products.
// RUN LOOP
for (int i=0;i< maxIndex; i=i+1)
{
int X = listA[index]
int Y = listB[index]
int product = X * Y
total = total + product
}
86
A Bearing E-Book
First, we set up two lists ‘listX’ and ‘listY and fill in some data:
Remember, the looping variable counts one by one from zero, untill it reaches
the ‘maxIndex’ value.
In effect ‘i’ goes through ‘0’,’1’,’2’,’3’ and ‘4’. We do not include ‘5’ since ‘i’ must
be less than the ‘maxIndex’ value.
Inside the loop, we reference the item in each list for the current index
int X = listA[index]
int Y = listB[index]
int product = X * Y
total = total + product
Let us look at this from a different perspective. Assume the looping variable ‘i’
just counted to ‘2’. The diagram in show how we use ‘i’ as an index into
our data.
When ‘i’ is ‘2’, we reference the third item in each list. The value of the third item
in ‘listA’ is ‘30’, while that of ‘listB’ is ‘0’.
87
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We do this for every pass of the loop, and add the result to our total.
Note that I have used several helper variables. We use them to make the code
easier to read.
I could have chosen to reference the list data directly. The for-loop body would
then have looked like this:
It uses much less space, but is not quite as clear. In the end, what approach you
shoose is a matter of style and preference.
88
A Bearing E-Book
We can use for-loops to identify data. Assume we want to search through a list
of names for a specific match.
The function 'hasName' should verify whether a name exists in a given list of
names:
It takes two arguments. The variable ‘search’ represents the name we are
looking for. The variable ‘names’ holds the list of names we want to search.
Let us trace the code, starting at the first function call. We call ‘hasName’ with
two arguments:
89
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
wel see that the variable ‘search’ takes on the value “simon” and ‘names’ now
receives the list of names provided to us. We determine the index for the last
item in the list:
The variable ‘names’ is a type. It has a ‘Count’ property, which tells us how
many items there are in the list. , We use it to determine the number of items in
the list.
The diagram below visualize the logic behind this calculation.To make things
easy on us, I have limited the list size in the diagram to four, but the same
concept applies regardless of list size:
The index of the first item is ‘0’, the second is ‘1’, the third is ‘2’ and so forth. The
index is always one less than the position.
The position of the last item is the same as the number of items in the list.
90
A Bearing E-Book
If we combine this information, we find that we can determine the index of the
last item by ‘the number of items in the list minus 1’.
We have prepared all the variables we need for the loop, and are ready to start.
The looping variable ‘idx’ counts one by one, from ‘0’ up to the index of the last
item. We execute the loop once for each index value.
Inside the loop, we retrieve the list item for the current index and compare it to
‘search’. If they match, we exit the function with a value.
The function received “simon” as the search-term. That string is not present in
‘names’, so this condition will never hit.
Eventually we exhaust the list and exit the for-loop. We return , to indicate
that there were no matches:
No match on “simon”
91
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
92
A Bearing E-Book
We call ‘hasName’ with the search value “sam”. We want to search the same
list of data as before; ‘names’.
The function loops through the items in the list. Inside the looping body, it
checks for matches:
This time around, the name list contains the string “sam”.
Eventually the search condition matches and we exit the function with a
value. The calling code stores the result in the variable ‘hasSam’.
93
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The fo rea ch lo op
The for-loop is great for when we know how many times we want to repeat. It
provides great flexibility that allows us to be quite creative in how we step
through a list.
It feels a bit clunky though. Like being handed a swiss army knife, when what
you really wanted was a pair of scissors.
List<string> names
... // Code to populate collection
There are two parts to the statement, the ‘loop item’ and ‘data source’
Elements of foreach
94
A Bearing E-Book
This declares the variable used to hold a list item at each loop.
string name
The data type must line up with the data source. In this case, ‘names’ is of type
In other words, it holds items of type , thus ‘name’ must also
be of type .
names
// LOOPING PARAMETERS
int maxIndex = names.Count -1 //Index of last list-item
95
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
// NO MATCH
return false;
}
That is quite remarkable don’t you think? We did not have to mess about with
any indexes or collection references, yet it does exactly the same as the
previous code.
96
A Bearing E-Book
You can easily do simple things like making decisions, traversing data and
performing simple calculations, but imagine you want to connect to a database
or draw something to the the screen. Building these things from scratch would
take you an inordinate amount of effort.
Programmers have done these things before. Surely, we can make use of their
work somehow. They have, and we shall most decidedly use that to our
advantage.
Functions
When we introduced the concept of functions, it allowed us to separate our
code into smaller self-contained modules. It made code easier to read and
easier to manage. Another benefit was that we could more easily reuse code
between projects.
97
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Consider a function that verifies text input. It could look like this:
It takes a string variable as input, and returns if has valid content. Otherwise,
it returns .
A variable that is never assigned to holds the special value . It means there
is nothing there.
This is not the same as an empty string. An empty string is still a string with
defined properties and functionality.
The function ‘isValidString’ consider either value as invalid, so it must test for
the presence of both of them.
You can easily use this function in any project where you need to test if a string
has content. It does not rely on your project code, and your code only relies on
the function interface.
98
A Bearing E-Book
Libraries
As we keep working with different projects, we will start to build up a collection
of reusable code snippets. It makes sense to arrange them so it is easy for us
to use them when needed.
Utilizing libraries
We refer to the mechanism we use to support this as libraries. We can use them
to organize our own code or to distribute it to the benefit of others.
With reusable code, we can build upon previous effort by plugging existing code
into new projects. This concept is valid whether we are talking about small
personal projects or large-scale ones.
99
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The core of a language defines the basic building blocks needed to build
software. Actual details would ofcourse depend on the language itself. Some
languages are more extensive in what they offer than others.
Either way, you could build just about anything with the basics provided.At least
in theory.
Writing even a simple GUI application, could take you years if you had to do it
from scratch. You would have to write code to interact with display hardware
and sound hardware. You would have to write code to display windows, move
them around and resize them. You would have to write code to display the
mouse cursor, act on mouse input and key strokes. All this, before you have
even gotten around to writing your "actual" application.
Luckily, programming has been an ongoing activity for quite some time. For
most languages, there are libraries for just about any conceivable topic available
to us.
A web-browser component
Robotics
Physics calculations
Mathematical calculations
Language dictionaries
AI driven tools
Etc.
100
A Bearing E-Book
A library may give you access to functions, key values, data etc. Anything that is
necessary for us to perform a specific task.
They address a specific concern. If you want to build 3D graphics, you use a
library for 3D graphics. If you want to build a text-editor, perhaps you make use
of a language dictionary. And so forth.
Realize that anyone could write and publish a library. You can build private
libraries to assist you in reusing your own code, or you can take advantage of
libraries created by others. Either way it relieves you of the effort of having to
build more code.
La ngua ge Framework
A framework is something that provides extra support for what you are building.
The language or environment you use for development often come with a set
of base libraries. These libraries are not part of the core language, but is
essential for your day-to-day programming tasks.
For example, a GUI framework will give you easy access to tools that takes care
of all the boilerplate code that is necessary to get an application running with
window frames, buttons, grids etc.
It does not make much sense to talk about frameworks and libraries in generic
terms, so I shall come back to you with examples on how to use frameworks
and libraries once we need to access them.
101
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
4.4. S u mmary
That is about it.
We first introduced the basic building blocks such as variables and operators
along with information on the proper way to put them together to make our first
programs.
Combining these with the concepts introduced in this chapter, we have covered
everything we need to become a programmer!
Well, maybe not quite. What we have covered however, is everything you need
to know in order to build a fractal image generator. In other words, we have gone
through all you need in order to follow along in this book.
Subtract
102
A Bearing E-Book
Multiply
Divide
Greater
than
Less than
or equal to
Greater
than or
equal to
Not equal
to
Libraries and
frameworks
In all the examples, we have borrowed keywords and naming conventions from
an actual programming language. Consequently, the code you have seen so far
would compile and run with very few modifications.
103
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
If we look at the level of complexity for each item listed in the summary, it is
hardly balanced. "Libraries and frameworks" stands out as way more complex
than anything else in the list.
What is interesting though, is that things that may be hard to build can be quite
easy to use. In fact, well-made code is generally easy to use. Well, more or less.
For example the type is far more complex than an , but we can quite
easily include either one in our code.
Libraries and frameworks allows you to perform complex tasks, while hiding the
complexity from you. You can then use the core commands of your language to
bind it all together.
There are four perhaps noticeable omissions. Let us quickly talk about each one
of these.
Validation
104
A Bearing E-Book
We declare the variable ‘data’ and assign an empty list. We use the ‘Count’
property on the object to get the number of items in the collection.
Perhaps you remember from an earlier chapter, that if we do not assign a value
to a variable it may contain the special value This value signifies that there
is no data.
In this case, ‘data’ contains , but there is no such thing as a ‘Count’ property
on a value, so this operation will cause trouble.
For production ready code, we must ensure variables contain what we expect
them to before using them. This is especially important for function input, since
we may not have created the argument values ourselves.
We are still learning, so we do not want to clutter the examples with validation
code. This is fine, since I have total control over the data we use and can vouch
for their content.
Object oriented programming, or OOP for short, is sort of like working with
turbo-charged functions. We are already familiar with the function.
105
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
A function has its own code that it executes when called. It has a set of
arguments and it can return data.
The function
The OOP object executes code, it can take arguments that affect operation and
it can return data.
The object
The object may have properties, multiple functions, other objects and data
baked into it. It can choose to make any of these visible or invisible to the calling
code.
We refer to the the set of functions exposed by an object as the interface. You
can perform some action on the object by calling a function in its interface.
106
A Bearing E-Book
This may sound vaguely familiar to you. We have in fact taken advantage of
OOP several times in this book.
It keeps track of our data. It has properties and other functionality we can use
to work with the collection data.
We have used its ‘Count property and ‘Add’ function on several occasions.
This is one of the great things about Object oriented programming. When done
right, you end up using it without even realizing it is there. It just works.
It is a huge subject worth a book of its own, but for our purposes, this is all you
need to know.
107
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Debugging
Debugging is the process of removing errors, or bugs from your program. Thus
the name; 'de-bug'-ing. It involves studying and tracing code along with mental
gymnastics to figure out why the computer is not doing what we told it to do.
Remember; a computer always does exactly what we tell it to do. Our task is to
identify where we went wrong.
Whatever the source of the error, it can be quite a laborious process and is
almost unavoidable.
This topic requires us to dip our proverbial toes in the water. We will revisit it
once we have gotten some actual coding done in ‘Volume 2’.
Testing
How do you know there are errors in your code in the first place? One way is to
hand your program to your customer, and deal when the angry phonecalls when
the program fails.
A better way is to test everything you do. We know what we expect our
program to do. Given a known starting condition, we know what the result
should be. Testing means to confirm that we get the expected results. If they
do not, there is an error in there somewhere, or we misunderstood our task.
When building small programs, we can get by just fine without doing structured
testing, but is definitely something to look into once you master the basics.
108
A Bearing E-Book
CHAPTER 5
Building Code
109
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
5 .1 . THE CA NV AS
The Pixel
We need a way to identify a point on the screen and assign a color to it.
The image
An image is a constellation of color data. Like the screen, it has a width and a
height. We usually refer to each point within the image as pixels, just like for the
screen.
110
A Bearing E-Book
An image can be any size. E.g. It can be ‘3x3’ or it can be ‘10000x2’. The screen
format is much less variant. There are a selection of commonly used
dimensions, such as ‘1280x1024’,’1600x1200’, ‘1920x1280’ etc.
The diagram below shows an image with width 800 and height 600. We refer
to this as an “800 by 600” image or simply 800x600:
We represent the position of a pixel by its horizontal position and its vertical
position. We group these two numbers into a coordinate pair.
111
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
For the vertical position we start counting from the top and go
downwards. An index value of ‘4’, place us at the fifth pixel.
Note that I am making a distinction between the position and
the index. Indexes start at ‘0’ while positions start at ‘1’.
addressing rows
At ‘0’, the contribution is 0%. At ‘255’, the contribution is 100%. Any values in
between represents a percentage of the max value.
Component value
Assume you wanted to set value to 60%. 60% of 255 is 153, so the component
value is 153.
112
A Bearing E-Book
You will get this once you start playing around with colors in actual code. Just
realize that you can define a color by providing three integer values between ‘0’
and ‘255’.
113
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
What separates it from other data structures is that it maps the layout of your
screen in a one-to-one manner. It has the same width and height so you can
address a particular point by its coordinates ( and ).
114
A Bearing E-Book
If we want to display an image with a different resolution than our screen buffer,
we can scale it to fit or extract parts of the source that fits.
Source data can be loaded from file, memory or you could generate it with code.
For us, the details of how to decode and load a picture from a file are
unimportant. There are libraries that take care of this for us. We simply want to
focus on how to modify colors of individual pixels.
One final note. For the examples in this chapter, I used a picture with dimension
800 by 600 pixels. That is a low-resolution image, yet it contains 480.000
pixels.
Imagine we want to do some calculation for every single pixel in this image. If
each one took us a second, it would take us the better part of a week to finish!
Luckily, modern computers are much faster than that.
115
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
That would be nice, but 3D calculations would complicate things for us. Instead,
we shall assign some sort of color scheme to the output of the function.
We traverse the screen coordinates ‘sx and ‘sy For every position, we feed
the coordinates to the function. The function outputs a value that we use to
determine a color we can plot to the current screen position.
116
A Bearing E-Book
To set a color value for every pixel in the image we traverse pixels line by line,
starting at the top. At each line, we traverse pixels going left to right.
After we have completed filling in one line, we move on to the line below.
Traversing lines
117
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
You may remember from earlier how we calculate the index. The index of the
last item in a list is given by the number of items in the list minus ‘1’ as shown in
the diagram in .
118
A Bearing E-Book
int r = 0
int g = 0
int b = 0
By setting all component values to '0', we end up with the color 'black'.
The outer loop goes through indexes for every line in our image:
Inside the outer loop, we set up a second loop that goes through indexes for
every pixel on a line:
The two for-loops work together to cover all combinations of ‘x’ and ‘y’ values.
119
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We use the variable ‘x’ to describe position horizontally and ‘y’ to describe
position downwards. The body of the inner loop will therefore execute for every
single pixel on screen.
We simply want to fill the screen with the same color, so we set the value of the
current pixel to :
We chose the variable names ‘x’ and ‘y’ to denote position, simply because they
are short and commonly known for this purpose.
120
A Bearing E-Book
Generating pi ctures
Finally, we get to the fun part! The function ‘clear’ that we built in the previous
section provides a framework for painting any sort of picture to the screen. We
simply need to change the inner loop.
Instead of assigning the same color value every time, we can decide the color
by calling a function. Assuming there is a function ‘getColor’ that generates a
‘getColor’ would take ‘x’ and ‘y’ as input, and return a color value which would be
used to paint the pixel at the given position.
//PERFORM CALCULATIONS
double maxval = w*h // Max possible value
double smooth = (a*b)/maxval // Performing calculation
int componentvalue = (int) Math.Round(255*smooth)
//DEFINE COLOR
int red = componentvalue, green = 0, blue = 0
//RETURN RESULT
return (red,green,blue)
}
121
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
So what does this function do? It calculates a smoothing value based on the
value of ‘x’ and ‘y’. The variable ‘smooth’ varies in value between ‘0’ and ‘1’. This
results in the image below:
Let us dive into the code and explain how it creates this image.
//CASTING VALUES
double a = (double) x, b = (double) y
double w = (double) width, h = (double) height
The variables ‘x’, ‘y’, ‘width’ and ‘height’ are integer values, but we want to
perform calculations that involves decimal values. To ensure consistency, and
avoid any surprises we convert our variables to . You may remember that
we called this operation a cast.
122
A Bearing E-Book
This is unproblematic since a decimal value can represent integer values just
fine. We store the the cast values into ‘a’, ‘b’,’w’ and ‘h’
//PERFORM CALCULATIONS
double maxval = w*h // Max possible value
double smooth = (a*b)/maxval // Performing calculation
‘x’ or ‘y’ is at ‘0’, in which case the product is also ‘0’. The highest value occurs
at ‘xmax’ and ‘ymax’.
We find the value of ‘smooth’ by dividing the product with the maxvalue. Since
the product varies from 0 to ‘maxval’, the value of ‘smooth’ must vary from ‘0’
to ‘1’.
123
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Looking at the diagram below, the product ends up at the minimum value ‘0’ in
three corners. The last corner results in a product at max value.
Back to our code, the next line converts the result into an integer value in the
range [0 to 255]:
Our component value should be an integer so we need to round off the value.
However, our core language does not provide functionality for that.
We could have created a function to do the job, but we might as well take
advantage of a library for this.
124
A Bearing E-Book
In fact, math operations are so common that a math library is already part of our
basic environment!
Our math library has a ‘ ’ function that does exactly what we want.
We only have to tell the compiler what library and function we want to use:
(int) Math.Round(decimalvalue)
//DEFINE COLOR
int red = roundedresult, green = 0, blue = 0
//RETURN RESULT
return (red,green,blue) }
125
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Since we only vary the red component, our picture turned out in shades of red.
Do not ponder too much upon explanations or diagrams. It is great if they are
helpful to you, as that was ofcourse their intention. However, if they do not, skim
through them and focus on the code itself. You will still reap the full benefit of
these examples once we start coding for real.
With the code from our previous example, we have established a good
foundation for our fractal picture generator. Before we continue, I want to play
around with the code a bit. Let us try some fancier calculations:
//PERFORM CALCULATIONS
double a = (double) x // Casting x to a double
double b = (double) y // Casting y to a double
double calc1 = 128.0 + 127.0 *(Math.Cos(0.0021*(a*b)))
double calc2 = 128.0 + 127.0 *((Math.Sin(0.002*a*b)-
Math.Cos(0.004*(y)))/2.0)
We use three formulas to generate values for each color component. The hope
is ofcourse that this would produce a picture with a bit more pizazz.
126
A Bearing E-Book
The ‘sine’ and ‘cosine’ functions are cyclic; their output are values that repeat
and are in the range [-1.0 to 1.0]. That makes it easy for us to ensure we generate
numbers that vary inside a given range.
We call the ‘Cos’ function from our Math library. It produces a value in the range
[-1.0 to +1.0]. Inserting the range limits into the calculation, gives:
In other words, the calculation results in values safely within the required range
of [0 to 255].
In our code, we have three different calculations. Each for one color component.
We assign each result to its component variable.
Note that the calculated values were decimal values, so we had to cast them to
integers:
//DEFINE COLOR
int red = (int) calc1
int green = (int) calc2
int bluee = (int) calc3
127
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
It has patterns and color variations that far surpass our previous efforts.
Perhaps it looks too uniform though. We do not see the complex patterns we
typically find in a fractal image.
Messing around with the formulas, resulted in some other interesting finds:
128
A Bearing E-Book
Some of these almost look fractal, but we are still looking at simple 2D color
plots. Each plot is simply a visualization of an ordinary functon of two variables.
If math is not exactly your cup of tea, I may have scared you a little in this chapter.
Do not panic though. The previous pictures is just a result of me messing about
with the formulas untill they produced something nice.
There are no complicated theories to derive them. They have only one purpose;
to create nice colorful patterns.
What I am trying to say, is that you do not actually have to understand the
formulas to play with them.
129
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
= +
The idea, is that we use an initial value of ‘Z’ and ‘C’ to perform the calculation
We assign the result to ‘Z’ and repeat the calculation with the new value of ‘Z’.
We keep repeating these calculations while we observe how the value ‘Z’
behaves. Note that for the entire calculation ‘Z’ is continuosly updated, while ‘C’
is set just once.
130
A Bearing E-Book
Complex numbers
The ‘Z’ and ‘C’ variables are a little different from normal variables, in the sense
that they consist of two numeric values, not just one.
= 1.5 + ⋅ 3.0
= 2.0 + ⋅ 8.0
= [1.5 , 3.0]
= [2.0,8.0]
That looks a little bit more on point. Each variable has a name and two
associated numeric values.
=[ , ]
131
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
In our Mandelbrot formula we have two complex numbers, ‘Z’ and ‘C’:
=[ , ]
=[ , ]
I have given the components of ‘C’ and ‘Z’ different names to make it easier to
tell which is which later on.
Given this information, we can derive a set of formulas that are relatively easy
to implement in code.
The derivation is not complicated, nor very exciting, so I shall skip that for now.
Let us go straight to the resulting equations:
= ⋅ − ⋅ +
= 2⋅ ⋅ +
We express these new equations in terms of the components of ‘Z’ and ‘C’.
If you look at it from the perspective of a programmer, they actually do not look
too complicated. You could almost be tempted to think they look too simple.
How can complex fractals pictures arise from these?
132
A Bearing E-Book
Feedback system
We apply the inputs for each equation and assign the results back into ‘a’ and
‘b’. In other words, we take the output and put it back into the equations again.
Ok, now what? That seems to create a neverending loop of calculations. Indeed
it does. When we feed result back like this, one of two things may happen.
For some inputs, the values may start to grow and grow. I will use the term
‘explode’ to describe this beavior.
133
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
System explosion
For other inputs, the values will settle in some fashion. Settling means that the
system does not explode. It does not necessarily mean that variables within the
system end up with a static value.
They could start to oscillate or forever move towards a limit. However, all we
care about is whether the system exploded or not.
Just as for our 2D color plots, we need a value we can bind to a color. Our
equations does not produce fixed values we can use, so how do we select the
colors?
Selecting colors
134
A Bearing E-Book
We plot a fractal exactly the same way we plotted 3D plots in the previous
chapter. We simply have to change how the ‘getColor’ function decides what
color to generate.
//PARAMETERS
int maxLoopCount = 256 ; double explodeThreshold = 4.0
//INITIALIZATION
double a = 0.0, b=0.0; // Z = 0
double Ca = (double) (x * 0.001) // Setting a component of C
double Cb = (double) (y * 0.001) // Setting b component of C
//CALCULATE Z = Z^2+C
double exploded = false
for(int i=0;i<maxLoopCount;i = i+1) // Keep iterating
{
//APPLYING MANDELBROT FORMULAS (Z= Z^2+C)
double a_new = aa - bb + Ca // a component of new Z value
double b_new = 2ab + Cb // b component of new Z value
a = a_new; b = b_new // Set new Z value
135
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
This is by far the most complex function we have built so far. Let us analyze it to
understand what is going on.
We start by defining define our colors. One for each possible outcome of our
equations:
// COLOR SCHEME
(int, int, int) explodedColor = (30,30,255) // Light blue
(int, int, int) settledColor = (0,0,0) // Black color
We could have used the values directly in our code, but introducing nicely
named variables makes our code easier to read.
//PARAMETERS
int maxLoopCount = 256
double explodedThreshold = 4.0
The variable ‘explodedThreshold’ is part of the test to determine if the value will
explode or not. I will explain iits use further down.
We get ready to run the loop code. Every calculation is based of a previous value,
so we must set the initial values for ‘a’,’b’, ‘Ca’ and ‘Cb’:
//INITIALIZATION
double a = 0.0, b=0.0; // Z = 0
double Ca = (double) (x * 0.001) // Setting a component of C
double Cb = (double) (y * 0.001) // Setting b component of C
136
A Bearing E-Book
= [ , ] = [0,0]
At the start of a calculation we set ‘Z’ to ‘0’, by setting the components ‘a’ and
‘b’ to ‘0’. We seed the calculation with ‘C’ by filling the components ‘ca’ and ‘cb’
with the values of the the current position [x,y]. Note that ‘C’ is only set once.
I will explain why we multiply the coordinates by 0.001 in the next example. For
now just consider them magic numbers that tweaks the output.
//CALCULATE Z = Z^2+C
double exploded = false
for(int i=0;i<maxLoopCount;i = i+1) {...} // Keep iterating
Inside the loop, we evaluate the Mandelbrot equations. We assign the results
to temporary variables before storing them to ‘Z’ by setting each component ‘a’
and ‘b’:
137
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
It is tempting to skip the temporary variables and write the assignments as:
That would not give the correct results. The value of ‘a’ is correct, but when
calculating the value for ‘b’ we run into trouble. We are mixing old and new
values.
The value of ‘a’ is the new one, but ‘b’ holds the old value. By introducing the
two temporary variables ‘a_new’ and ‘b_new’, we avoid the problem.
138
A Bearing E-Book
A complex number has two components ‘a’ and ‘b’.We can visualize this as a
vector. The size of ‘Z’ is the same as the length of this vector. A vector is simply
a line segment in a given direction.
( ℎ ) = +
We can solve for the length of ‘Z’ by taking the square root on each side:
( ℎ ) = +
On the left hand side, the square and the square root cancels each other out.
We are left with:
ℎ = +
ℎ =√ ⋅ + ⋅
139
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
√ ⋅ + ⋅ > ℎ ℎ
We could implement this directly in code, but we want to save the PC extra work
whenever we can. Both sides of the equation are positive, so squaring each side
does not change it:
√ ⋅ + ⋅ >( ℎ ℎ )
Again, the square and squareroot operations cancel eachother out on the left
hand side:
⋅ + ⋅ >( ℎ ℎ )
The threshold value never changes throughout the program. It is commonly set
to ‘2’:
⋅ + ⋅ > (2)
⋅ + ⋅ > 2⋅2
⋅ + ⋅ > 4
This last result may be used in our code to check if ‘Z’ exploded.
Don’t worry if you feel this is too much math. It is included for context, but you
will be just fine as long as you accept that we can test whether the system
explodes or not by applying the condition:
140
A Bearing E-Book
If the test holds true, we signal that ‘Z’ exploded and exit the loop:
141
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Fantastic! If you were trying to create a Mandelbrot plot all on your own, this
would be the breakthrough. It is quite obviously a fractal, and it sort of looks like
the Mandelbrot fractal, but where's the rest of it?
142
A Bearing E-Book
You may notice that as we repeat calculations, only ‘Z changes. The value of ‘C’
does not change inside the loop.
143
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We feed the system with ‘C’ and the system returns some output that we can
use to calculate a color.
=[ , ]
If we vary ‘ca’ so it is in the range [-2.0 to 0.5] and ‘cb’ is in the range [-1.1 to 1.1],
we get a perfect view of the characteristic Mandelbrot shape, also known as the
Mandelbrot Bulb:
144
A Bearing E-Book
[ , ] = [0,0]
1, 0
= [1,0]
Pixel coordinates
= [ , ] = [0,0]
= [ , ] = [1,0]
145
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The ‘ca’ range of interest is [ -2.0 to 0.5 ]. ‘C1’ is at the end of that range and ‘C2’
is already outside. In fact, every following pixel on the same line, maps to a point
far outside the Mandelbrot set. In other words, the fractal on our screen will be
one pixel wide. That is not going to be a very interesting picture.
Mismatched coordinates
We want to be able to map any chosen section in the Mandelbrot space to the
whole screen as shown in the diagram below:
146
A Bearing E-Book
We have to scale the chosen coordinates in the Mandelbrot space so they map
nicely to our screen coordinates.
How do we go about scaling the values? Let us start by looking at how we can
do this for pixels on a single line.
Imagine we have a screen that is only 30 pixels wide and image data exactly 10
units wide. The chosen space in the Image is in the range [10 to 19]
We choose ‘x’ for position on the screen line and ‘m’ for position on the image
line.
Have you ever heard the phrase: ‘the question is the answer’? It means that the
answer to your question may lie in the details of your question.
We are asking how much one value should change in relation to another. This is
known as a ratio. The ratio of the widths of the two lines therefore tell us how
much ‘m’ must change, as ‘x’ changes.
147
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
ℎ −1
=
ℎ −1
−
=
( − )
9
= = 0.310345
29
Every time we increase ‘x’ by ‘1’ we must increase ‘m’ by ‘0.310345’. I have listed
the first and last four four values of ‘x’ and ‘m’ as we traverse the line:
0 10 … …
1 10.31034 26 18.06897
2 10.62069 27 18.37931
3 10.93103 28 18.68966
… … 29 19
Note that we are subtracting ‘1’ from the widths when finding the ratio. This is
because we actually want the ratio between the dfiferences in coordinates,
which are one less than the actual width.
148
A Bearing E-Book
If you think about it, it rather makes sense. If you take three steps, and someone
else take one, you are walking three times as fast. Turned on its head, the other
person is walking at a third of your pace.
149
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
That sorts the scaling problem. Time to rewrite our code to match:
//PARAMETERS
(int,int,int) result // The color that will be returned
int maxLoopCount = 256 // Prevents staying in a loop forever
double limit = 4.0 // The explode limit
explodedColor = (30,30,255) // Light blue for values that explode
settledColor = (0,0,0) // Black color for values that settle
//INITIALIZATION double
double a = 0.0; // Initializing components of Z
double b = 0.0
//CALCULATE VALUE
double exploded = false;
} // End for-loop
// DEFINE COLOR
if(exploded) { result = explodedColor }
else { result = settledColor }
// RETURN COLOR
return result;
}
150
A Bearing E-Book
We only changed a few things. First, we modified the signature of the function.
That is, the function arguments are different from before:
‘getColør’ arguments
The variables ‘x’ and ‘y’ are screen coordinates. The variables ‘width’ and ‘height’
describe the dimensions of the screen. The points ‘a1’, ‘b1’, ‘a2’ and ‘b2’ define
the section in our Mandelbrot-image that we want to display.
Next, we calculate the scaling factors. We have two ratios, horizontal and
vertical:
//INITIALIZATION
double a = 0.0; double b = 0.0 // Initializing components of Z
double ratio_x = (a2 - a1) / screenWidth
double ratio_y = (b2 - b1) / screenHeight
151
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
We now have a pair of screen coordinates, along with the horizontal and vertical
ratios. We want to use that to find the position in the Mandelbrot space.
double Ca = a1 + x * ratio_x
double Cb = b1 + y * ratio_y
152
A Bearing E-Book
Let us revisit the last diagram. This time I have colorized the coordinates in each
space as shown in the diagram on the previous page.
Let us get rid of all the extra details, and look at the coordinates only. The
diagram below shows coordinate information for the screen to the left, and
Mandelbrot to the right.
We can describe the ratios as the relationships between changes along the
same axis:
Δ
=
Δ
Δ
=
Δ
153
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Δ = −
Δ = −
Δ = −
Δy = −
For the screen coordinates, the first point is ‘0’. We can simplify and :
Δ = − = −0=
Δy = − = −0=
Δ Δ
= =
Δ
Δ Δ
= =
Δ
154
A Bearing E-Book
Let us first look at ‘ratiox’. The equation holds true, if we multiply each side
with the same value. We multiply both sides with ‘x’:
Δ
=
Δ
⋅ = ⋅
Δ
⋅ = ⋅
1
1⋅Δ = ⋅
Δ = ⋅
Δ = −
Δ = ⋅
(C − )= ⋅
− = ⋅
155
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
The expression holds true, if we add the same value to each side. If we add ‘a1’
to both sides of the equation, we will be left with ‘Ca’ on the left:
( − )+ =( ⋅ )+
− + = ⋅ +
+0= ⋅ +
= ⋅ +
The expression does not does not change if we rearrange the way elements
are added together. We can rearrange the expression:
= + ⋅
= + ⋅
That was probably the most math you will see in this book. As always, do not
let the math scare you. After all, this is a course on programming, not math.
If you had difficulties following these last explanations, no harm done. The
important part is that you understand the programming concepts introduced.
156
A Bearing E-Book
The only thing remaining in our code is to update the function call to the
‘getColor’. We need to provide screen dimensions and the coordinates within
the mandelbrot set:
157
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Fantastic! The scaling code works great. We now have much greater control
over which part of the Mandelbrot set we want to paint to the screen.
Notice how easy it is now to select a different section of the set. The following
code will creat the section as as indicated in the diagram below:
158
A Bearing E-Book
A special case
1
= = 0.001
1000
1
= = 0.001
1000
double Ca = a1 + x * ratio_x
double Cb = b1 + y * ratio_y
‘a1’ and ‘b1’ are ‘0’ and the ratios are both ‘0.001’. Let us update the scaling
code with the known values for ‘a1’,’b1’, ‘ratio_x’ and ‘ratio_y’:
double Ca = 0 + 0.001*ratio_x;
double Cb = 0 + 0.001*ratio_y;
We can remove the zero values, since they do not contribute to the equtions:
double Ca = 0.001*ratio_x;
double Cb = 0.001*ratio_y;
159
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Moving to multi-color
I congratulate you for making it this far! We have reached our goal. We
managed to write a program that can fully generate a Mandelbrot fractal. With
some tinkering, we can relatively easy zoom in on it as well.
160
A Bearing E-Book
The calculation code is not of interest right now, so I dotted it out in the code
snippet above. I want to focus on how we exit the loop.
Once ‘Z’ grows past the explode limit, we assume it will go to infinity and the for-
loop will exit. If it took a small number of loops to hit the limit, ‘Z’ must have
grown fast. The larger the number of loops, the slower ‘Z’ grew.
Therefore, we should be able to use the loop count as a measure for how fast
‘Z’ grows.
The algorithm
Let us summarize the process. We navigate through every pixel on screen. For
every pixel, we decide a coordinate within the Mandelbrot space. We take those
coordinates and input them to our system.
The system loops through our equations and eventually output a loop count.
That loop count tells us how fast the system exploded, if at all.
We then use this value as a basis for deciding a color, which we plot to screen.
161
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
int,int ,int) getColor(int x, int y,double X1, double X2, double Y1,
double Y2, double screenwidth,double screenheight)
{
//PARAMETERS
(int,int,int) result // Return value
//INITIALIZATION
double a = 0.0; double b = 0.0 // Initializing components of Z
double ratio_x = (X2 - X1) / screenWidth;
double ratio_y = (Y2 - Y1) / screenHeight;
double Ca = xstart + x * dx;
double Cb = ystart + y * dy;
//CALCULATE VALUE
double exploded = false;
int i;
for(i=0;i<maxLoopCount;i = i+1)
{ double a_new = a*a – b*b + Ca // Mandelbrot formula for a
double b_new = 2*a*b + Cb // Mandelbrot formula for b
a = a_new; b = b_new // Storing results back in a and b
double magnitude = a*a + b*b // Measure for size of Z
if( magnitude > limit ) // If we hit the limit
{ exploded = true; break;} // value exploded, exit loop.
}
// DEFINE COLOR
int R = i % 255;
int G = i % 255;
int B = i % 255;
// RETURN COLOR
return (R,G,B));
162
A Bearing E-Book
So what is different this time around? First off, we declared the looping variable
outside the loop:
int i;
It is usually what we want, but in this instance, we need to know the value of the
looping variable after the for-loop has finished.
There are more than one way to do this, but declaring the variable outside the
for-loop results in least additional code.
We then define the color, based on the value of the looping variable:
// DEFINE COLOR
int R = i % 256
int G = i % 256
int B = i % 256
This may look a bit weird to you. I introduced the modulus operator in the
second chapter.
An integer division will yield a whole number and a remainder. The modulus
operator returns the remainder. The interesting part about it is that it will always
be a value between ‘0’ and its argument value. In other words, we can use it to
ensure the expression stays below a certain value.
163
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
// DEFINE COLOR
int R = i % 256; int G = i % 256; int B = i % 256
The result
164
A Bearing E-Book
We chunk the loopcount so we have one chunk per color in our palette.
In the illustration we have ‘255’ colors and a loop range of ‘765’. Each chunk
spans three values of the loopcount. If our only looped ‘8’ times ( index ‘7’)
before ‘Z’ exploded, we would color the associated pixel with color number ‘3’.
We are going to use a slightly different approach. It will provide less control over
choice of colors, but it is much easier to code. To go forward we need to
165
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
understand why our previous effort generated an image in shades of grey. Have
a look at the diagram below:
These are three different color combinations. All are in shades of grey, because
they all have equal contributions from the base colors ‘red’,’green’ and ‘blue’ The
smaller the component values, the darker the color. At the extremes, the color
turn into ‘black’ or ‘white’.
// DEFINE COLOR
int R = i % 256
int G = i % 256
int B = i % 256
Every time we set a color, each color component gets the same value. When
every component has the same intensity, the result is a grey color.
Great, we found the issue. Now, how do we fix it? If we could make component
expression change at different rates, the resulting color should no longer be
grey.
You may wonder if multiplying the loopcount like this could break things
somehow? It certainly could have, but we take care of that through clipping. The
modulus operator ensures the expression value always stays in the range [0
to 255] regardless of how large the input is.
166
A Bearing E-Book
Anyway, what is the worst that could happen? Let us try and see what
happens:Bingo! A beautifully complex and colorful fractal.
Just to fully appreciate what we have accomplished so far, let us zoom in a bit:
167
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
So me more examples
Fractal images are remarkable in the sense that it takes so little to create so
much. Exploring them can be quite the time thief.
Especially at first, but once the initial sense of awe subsides, curious
programmers may ask themselves what happens if we change things up a bit.
Can we adjust the settings? Or perhaps the formulas themselves?
We made the ‘green’ component change three times as fast as the ‘red’
component. The ‘blue’ component changes six times as fast.
What happens if we adjust the color multiplication factors so they are closer
together? Let us adjust the multiplication factors as follows:
Since we introduce decimal numbers in the equation, we must force the final
value back to integer. We do this by casting to .
168
A Bearing E-Book
The result is a display in red shades mostly. When you think about it, it makes
sense. The ‘red’ component is now about 4 times as frequent as the two other
components.
The relative size will therefore vary in the range [0.0 to 1.0].
We have to multiply it with 255 to get it in to the range [0.0 to 255.0].
169
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
Colorwise it does not look so different from before. However, this factor is
always going to be in the range [0 to 1]:
loopcount/maxLoopCount
170
A Bearing E-Book
Ok, enough with changing the colorization schemes already. Let us see what
happens if we allow the calculations to go on longer. We do this by increasing
the loop-limit.
The picture resolution hardly does it justice, as there are more details than in
our first image. However, calculation time went from about 10 seconds to about
120 seconds!
As we increase the ‘maxLoopLimit’, the image will take longer to render. For
every pixel we may potentially loop through ‘150000’ times instead of ‘10000’.
That is fiften times as much work to do for the computer.
If you render an 800x600 image, 140.000 more loops per pixel amounts to a
worst-case scenario of running about 67 billion additional loops. That is ALOT
of extra computing power needed from flipping a single number.
171
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
I should clarify; as we calculate pixels in the Mandelbrot set, only points inside
the set will require the full amount of loops.
Remember, for a given point, whenever ‘Z’ explodes, we can stop calculating.
For points outside the set, it could happen after ‘5’,’10’,’100’ loops or anywhere
up to the maxloop count.
Still, on a reasonably fast computer calculating fractals does not take too long.
At least not compared to the amount of work the computer must do.
Applications that let you plot fractals are a dime a dozen. They will let you create
some nice looking fractals in no time. We have a great advantage in building it
ourselves though. We can mess about with absolutely everything.
double magnitude = a + b
That would be a rather poor estimate of magnitude. Let us try anyway. As I said
before; what is the worst that could happen? An unpleasing image? No big deal!
172
A Bearing E-Book
double magnitude = a
Figure 5-66 Output of Mandelbrot generator program , with broken magnitude estimate
173
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
I wasn not expecting that. Apparently, the Mandelbrot set is quite resilient.
Presumably the components of ‘Z’ stay small enough near the edge or inside
the Mandelbrot set for the magnitude estimate to be ‘close enough’.
We went through quite a bit of theory to arrive at the proper code for the
Mandelbrot set. The math behind is not of much importance to us.
If math seems scary to you, that is certainly good news. We do not have to
derive anything at all. We are just looking for fun/interesting patterns.
In a sense, it is a bit like throwing stones in a pond to watch the wave patterns
on the surface. We can prod and nudge the equations exactly as we see fit.
174
A Bearing E-Book
Remember ‘C’ seeds the equations. By multiplying the input with sinusoidal
functions we are sort of “shaking” the input to the equations.
175
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS
If you managed to follow along and at least half understood what was going on,
I would consider that a major success!
As mentioned in the beginning of this book, its main purpose was to introduce
and expose you to basic programming concepts. The math, the fractals, the
diagrams etc., it is all fluff. Misunderstand me right. They are important pieces
of fluff, in terms of gaining a thorough understanding of the material, but they
are not topics you were here to learn.
Their main purpose was to provide a proverbial canvas where we could explore
basic concepts of programming while having fun doing so. Something that was
more interesting than coding a text editor or a customer management system.
Therefore, even if you understood nothing of the fractals or the math behind
the examples, no worries! It is not even important that you understood all the
code presented.
I only need you to feel somewhat aquainted with basic programming concepts.
Just enough for you to look at a piece of code, and perhaps recognize parts of
it. A for-loop here, a variable assignment there. There should be a sense of
176
A Bearing E-Book
recognition. A feeling that you have seen it before and can sort of tell what it
does.
I do not expect you to be able to write your own code yet. As I said in the
beginning, a major part of learning happens when you get your hands wet. You
will truly learn programming by writing and compiling code.
This book has been an attempt at prepping you for what comes next.
Onwards to part 2
Writing and compiling code is exactly what we will focus on in the second
volume.
We will repeat all the concepts and many of the examples from this book, but
this time around, you will actually write, compile and run the code. By the end of
part two, you should be able to start creating basic programs on your own.
If you just finished this book, I suggest you get some rest. Sleep on it, eat
something and let your brain process the information for a while.
Once you are ready, I will see you in “Volume 2: Creating code”.
Bjørn
177