0% found this document useful (0 votes)
213 views201 pages

Programming For Beginners, THE Fundamentals: Volume 1: Theory

The document is a summary of the contents of a book about programming fundamentals for beginners. It introduces programming concepts like memory, comments, and data types. It explains that the book is divided into two volumes, with the first providing theoretical concepts and the second focusing on creating actual code. The book is intended for complete beginners to learn basic programming principles.

Uploaded by

karla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
213 views201 pages

Programming For Beginners, THE Fundamentals: Volume 1: Theory

The document is a summary of the contents of a book about programming fundamentals for beginners. It introduces programming concepts like memory, comments, and data types. It explains that the book is divided into two volumes, with the first providing theoretical concepts and the second focusing on creating actual code. The book is intended for complete beginners to learn basic programming principles.

Uploaded by

karla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 201

PROGRAMMING

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

PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

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.

Book and Cover design by Bjørn Inge F. Westerheim

Draft version. April 2021, Last updated 10/4/2021.

10 9 8 7 6 5 4 3 2 1

4
A Bearing E-Book

Tell me and I forget.


Teach me and I remember.
Involve me and I learn
- Xun Kuang , Chinese philospoher

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.

Through work, I tend to get involved in utilitary software development, building


tools, installers and various solutions to help my customers.

Programming is one of my absolute favorite activities, whether for work or


leisure. Over the years, I have dabbled in M68k assembly on the Amiga, X86
Assembly on the PC, Mono on Linux, C/C++, Perl, Javascript, PHP, Python,
Matlab, Visual Basic and more. These days,
Visual C# is where I feel at home, but I am always
looking to learn something new.

I have the fortune of residing in the beautiful and


friendly country of Singapore with my fantastic
family and our three cats: Oggi, Bobbi and Bunni.

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

Who is this boo k for?


I have written this book with complete beginners in mind. Previous exposure to
programming is not a requirement at all.

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

1.1. INTRODUCTION ........................................................................................................................................................................... 2


Fast and furious ...................................................................................................................................................................... 3
Writing code.............................................................................................................................................................................. 3
Programming languages .................................................................................................................................................. 4
Compiling code ....................................................................................................................................................................... 6
1.2. MEMORY ............................................................................................................................................................................................ 8
SLOW MEMORY .................................................................................................................................................................... 8
FAST MEMORY ....................................................................................................................................................................... 9
ACCESSING MEMORY ................................................................................................................................................... 10
SUMMARY................................................................................................................................................................................ 12

2.1. COMMENTS ...................................................................................................................................................................................15


2.2. THE DATA TYPE .........................................................................................................................................................................16
Integers (int) ............................................................................................................................................................................ 17
The decimal (double) ......................................................................................................................................................... 17
The Boolean (bool)............................................................................................................................................................. 18
The object ................................................................................................................................................................................ 18
The string (string)................................................................................................................................................................ 18
The nothing value ................................................................................................................................................................19
The symbols ........................................................................................................................................................................... 20
2.3. THE VARIABLE ............................................................................................................................................................................ 21
Assigning a value ................................................................................................................................................................ 22
The math operators .......................................................................................................................................................... 23
Casting: Forcing a datatype ........................................................................................................................................28
2.4. COLLECTIONS ............................................................................................................................................................................ 33
Introducing List<> ..............................................................................................................................................................34
Invoking List<> .....................................................................................................................................................................35
Sneak peak at functions ................................................................................................................................................38
Accessing collection data ........................................................................................................................................... 40
Multi-dimensional lists ....................................................................................................................................................43
The array datatype ............................................................................................................................................................45
2.5. SUMMARY ..................................................................................................................................................................................... 47

3.1. CODE COMPLEXITY .............................................................................................................................................................. 50


3.2. COMMENTS, PART DEUX ....................................................................................................................................................51
3.3. VARIABLE NAMING ................................................................................................................................................................54

9
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

3.4. INTERMEDIARY VARIABLES .......................................................................................................................................... 55


3.5. THE FUNCTION ..........................................................................................................................................................................57
Function arguments ........................................................................................................................................................ 58
Returning values ................................................................................................................................................................ 60
Splitting up code ................................................................................................................................................................. 61
The black box ....................................................................................................................................................................... 70
3.6. SUMMARY ...........................................................................................................................................................................................71

4.1. MAKING CHOICES ...................................................................................................................................................................74


The condition ......................................................................................................................................................................... 74
The if-else construct ........................................................................................................................................................75
4.2. REPEATING CODE .................................................................................................................................................................. 78
Introducing the loop ........................................................................................................................................................ 78
The while-loop ......................................................................................................................................................................79
The for-loop ............................................................................................................................................................................82
Looping through collections ...................................................................................................................................... 85
The foreach loop ................................................................................................................................................................ 94
4.3. REUSING CODE ..........................................................................................................................................................................97
Functions ..................................................................................................................................................................................97
Libraries .................................................................................................................................................................................... 99
Language Framework ................................................................................................................................................... 101
4.4. SUMMARY ....................................................................................................................................................................................... 102
Summarizing the building blocks.......................................................................................................................... 102
Things we have not covered ................................................................................................................................... 104

5.1. THE CANVAS ............................................................................................................................................................................. 110


The Pixel ................................................................................................................................................................................. 110
The Pixel Color ................................................................................................................................................................... 112
The Screen Buffer ............................................................................................................................................................ 114
5.2. CREATING IMAGES ............................................................................................................................................................... 116
Filling the screen ............................................................................................................................................................... 117
Generating pictures ........................................................................................................................................................ 121
5.3. THE MANDELBROT FRACTAL..................................................................................................................................... 130
The base formula ............................................................................................................................................................. 130
Partial 2-Color Mandelbrot ....................................................................................................................................... 135
The full 2-Color Mandelbrot ..................................................................................................................................... 143
Fractal, V3: monochromatic ..................................................................................................................................... 160
Fractal, V3: full color ...................................................................................................................................................... 165
Some more examples .................................................................................................................................................. 168
5.4. CONCLUSION ........................................................................................................................................................................... 176
Onwards to part 2 .............................................................................................................................................................177

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

Figure 3-6 Ordinates of x1 and x2 on P1-P2 ......................................................................................................................................64


Figure 3-7 Calculating area of triangle...............................................................................................................................................65
Figure 3-8 Splitting up code in functions ..........................................................................................................................................66
Figure 3-9 Function inputs ....................................................................................................................................................................... 67
Figure 3-10 Black box ................................................................................................................................................................................. 70
Figure 4-1 Code flow for ‘isNegative’ ................................................................................................................................................... 77
Figure 4-2 The for-loop construct ......................................................................................................................................................... 78
Figure 4-3 List indexing ........................................................................................................................................................................... 80
Figure 4-4 Code flow for while-loop.................................................................................................................................................... 80
Figure 4-5 Elements of the for-loop statement ................................................................................................................................ 83
Figure 4-6 Elementwise multiplication of lists of integers..........................................................................................................86
Figure 4-7 Accessing third element by index...................................................................................................................................88
Figure 4-8 Setting the max index......................................................................................................................................................... 90
Figure 4-9 No match on “simon” ............................................................................................................................................................91
Figure 4-10 Returning from a function ................................................................................................................................................ 92
Figure 4-11 Matching on item “sam”....................................................................................................................................................93
Figure 4-12 Elements of foreach ............................................................................................................................................................94
Figure 4-13 The function ‘findTriangleArea’ ..................................................................................................................................... 97
Figure 4-14 An empty string object ......................................................................................................................................................98
Figure 4-15 Utilizing libraries .................................................................................................................................................................99
Figure 4-16 The function ........................................................................................................................................................................ 106
Figure 4-17 The object ............................................................................................................................................................................ 106
Figure 4-18 Function and property interfac eon object ............................................................................................................ 107
Figure 5-1 Screen parameters ............................................................................................................................................................. 110
Figure 5-2 The screen and the pixel ................................................................................................................................................... 111
Figure 5-3 Addressing pixels horizontally ........................................................................................................................................ 111
Figure 5-4 addressing rows...................................................................................................................................................................112
Figure 5-5 Component value .................................................................................................................................................................112
Figure 5-6 Component contributions for various colors ........................................................................................................... 113
Figure 5-7 The screen buffer................................................................................................................................................................. 114
Figure 5-8 Setting a pixel color in the screen buffer .................................................................................................................. 114
Figure 5-9 Modifying the screen buffer ........................................................................................................................................... 115
Figure 5-10 Function of two variables ............................................................................................................................................... 116
Figure 5-11 Algorithmic view of color-plotting ............................................................................................................................... 116
Figure 5-12 Traversing pixels horizontally .......................................................................................................................................117
Figure 5-13 Traversing lines ..................................................................................................................................................................117
Figure 5-14 Finding the max collection index ................................................................................................................................ 119
Figure 5-15 Traversing all pixels with nested for-loops ........................................................................................................... 120
Figure 5-16 Painting the screen black ............................................................................................................................................. 120
Figure 5-17 Painting screen with smoothing function ................................................................................................................ 122
Figure 5-18 Product as a function of position ................................................................................................................................ 123
Figure 5-19 Smooth as function of product p.................................................................................................................................123
Figure 5-20 Analyzing smooth output ...............................................................................................................................................124
Figure 5-21 Using the Math.Round function ................................................................................................................................... 125
Figure 5-22 Rounding decimals ..........................................................................................................................................................125
Figure 5-23 The sine and cosine functions ....................................................................................................................................126
Figure 5-24 Generated image with trigonometric functions ...................................................................................................128
Figure 5-25 More outputs based on trigonometric functions .................................................................................................128
Figure 5-26 The fractal feedback loop............................................................................................................................................. 130
Figure 5-27 Feedback system .............................................................................................................................................................. 133
Figure 5-28 The Mandelbrot feedback system ............................................................................................................................ 133
Figure 5-29 System explosion ............................................................................................................................................................. 134

12
A Bearing E-Book

Figure 5-30 Selecting colors ................................................................................................................................................................ 134


Figure 5-31 initializing the Mandelbrot system ............................................................................................................................ 137
Figure 5-32 Mixing old and new values ......................................................................................................................................... 138
Figure 5-33 The explode threshold .................................................................................................................................................. 138
Figure 5-34 The magnitude of ‘Z’........................................................................................................................................................ 139
Figure 5-35 Pythagoras .......................................................................................................................................................................... 139
Figure 5-36 Code flows for explode and settle scenarios ....................................................................................................... 141
Figure 5-37 Our first Mandelbrot plot ............................................................................................................................................... 142
Figure 5-38 The Mandelbrot system ................................................................................................................................................. 143
Figure 5-39 Seeded Mandelbrot system......................................................................................................................................... 143
Figure 5-40 Simplified Mandelbrot system diagram................................................................................................................. 144
Figure 5-41 The Mandelbrot space ................................................................................................................................................... 144
Figure 5-42 The screen space ............................................................................................................................................................. 145
Figure 5-43 Pixel coordinates.............................................................................................................................................................. 145
Figure 5-44 Mismatched coordinates ............................................................................................................................................. 146
Figure 5-45 Properly matched coordinates ( Screen space  Mandelbrot space ) .............................................. 146
Figure 5-46 Relative traversal in ‘x’ ................................................................................................................................................... 147
Figure 5-47 Relative traversal in ‘y’.................................................................................................................................................... 149
Figure 5-48 ‘getColør’ arguments ....................................................................................................................................................... 151
Figure 5-49 Moving from screen space to Mandelbrot space .............................................................................................. 152
Figure 5-50 Screen space and Mandelbrot space coordinates ................................................................................ 152
Figure 5-51 Ratios screen space to Mandelbrot space ............................................................................................................ 153
Figure 5-52 Coordinates for full Mandelbrot set .......................................................................................................................... 157
Figure 5-53 Output of Mandelbrot program .................................................................................................................................. 157
Figure 5-54 Selecting section of Mandelbrot set with ‘getColor’ .......................................................................................... 158
Figure 5-55 Converting Mandelbrot system output to color .................................................................................................... 161
Figure 5-56 Output of Mandelbrot generator program ............................................................................................................ 164
Figure 5-57 Defining color palette for colorization of Mandelbrot output ........................................................ 165
Figure 5-58 Color components for grey values ............................................................................................................................ 165
Figure 5-59 Output of Mandelbrot generator program , with individual color rates ................................................... 167
Figure 5-60 Output of Mandelbrot generator program , individual color rates, zoomed in ...................................... 167
Figure 5-61 Output of Mandelbrot generator program , adjusted multiplication factors ........................................... 169
Figure 5-62 ................................................................................................................................................................................................... 169
Figure 5-63 Output of Mandelbrot generator program , with relative size calculation ............................................... 170
Figure 5-64 Mandelbrot with explode limit at 150.000 .............................................................................................................. 171
Figure 5-65 Mandelbrot with bad magnitued estimate ........................................................................................................... 173
Figure 5-66 Output of Mandelbrot generator program , with broken magnitude estimate ....................... 173
Figure 5-67 Mandelbrot with trigonemtric calculations added............................................................................................. 175
Figure 5-68 Example output of our fractal image generator .................................................................................................. 175
Figure 5-69 Example output of our fractal image generator .................................................................................................. 176

13
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

14
A Bearing E-Book

Preface, or World, H el lo!


Having read quite a few programming books over the years, a majority of them
open with an example that write the text "Hello, World" to the screen.

The idea behind this approach is to give a


short and simple example of building
something, at least vaguely useful. It is a piece
of code meant to make the student go "hey,
that wasn't so difficult". It gives you a sense of
having created something early on.

Next, authors would provide examples on


simple text or number manipulation, or
perhaps creating a simple input form. Stuff that would find its way into a basic
application such as a calculator or perhaps a text editor.

Not exactly engaging stuff. I always felt an introduction to programming should


start with something visually exciting. Something that would catch your
attention while being so complex that it would take a computer to do so.

Now, where do we find a topic that covers all of this, while also being simple
enough for complete beginners to grasp?

When I set out to learn a new


programming language, the first thing I
will try on my own, is to make a color
plot of a 2D function.

I do not go by a specific function, but


randomly choose some complicated
function. Not for any other reason, but
to create something interesting and
colorful.

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.

I raised some criteria for what, in my opinion, is a good introductory learning


resource on programming. The undertaking of building a fractal generator
seems to fulfill these:

 I Fractals are complex and colorful.

 It only requires basic math and programming skills

 It gives your computer a run for the money

It sounds a lot more fun than building a calculator app, doesn’t it?

16
A Bearing E-Book

The learning process

Learning can be quite the battle sometimes. Complex


topics explained in books apparently written by mad
scientists. Sometimes there are just too much going on.

Depending on what topic you are trying to learn, it will take


an effort. As well it should, but it would be nice if you could
learn without all the headaches.

A good introductory book should cover everything you


need to know, but no more. It should not be too long. You should have a fighting
chance at completing it over a weekend or two.

The problem with programming is that you need to understand both the big
picture and the small picture all at once.

Without context, programming can seem remarkably alien. With context, it is


quite straightforward. Well, most of the time anyway.

The plan of attack

I firmly believe in learning by It helps you to


understand the theory and to retain what you
have learned.

It may then come as a surprise, that going through


this book; I will not have you write a single line of
code! It may seem contradictory, but bear with
me. There is a method to the madness.

This introdcution to programming spans two volumes or two books:

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

There is a lot of ground to cover. We must choose a programming language and


development environment. We have to learn how to compile and run programs.
Chances are your the program does not work, so you will have to learn about
debugging and testing.

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

Learning should be fun. Making the computer write


‘Hello World’ on the screen is not my idea of fun.
Colors are fun. Graphics are fun.

Therefore, Instead of taking the traditional route, we


shall take a slightly more exciting path. This book is
written around one specific goal; to build a working
“fractal image generator”. Each time we introduce a new concept, it is to
progress towards this goal. Well mostly. I may occasionally broaden the scope
for context, but the aim is to build that generator as quickly as possible.

The examples

Technical books must often convey facts


that belong in some esoteric technical
domain.

Authors may try to make such facts easier to


digest by placing the subject in a familiar
context.

18
A Bearing E-Book

The problem with this approach is that I


would have to make assumptions about
what you find familiar or agreeable.

From the perspective of the reader, nothing


is quite as frustrating as having to wade
through examples on laundromats, train
schedules, sewing machines, or some other
mundane topic the author found interesting.

Some books tend to go light-hearted, humorous and somewhat kooky to punch


the material through. The problem is the same. If the author’s sense of humour
does not match yours, it ends up getting in the way rather than help.

The approach in this book is therefore to avoid generalized mundane examples


and kooky writing as much as possible. There is a red thread throughout the
book, which will guide our choice of examples. The occasional pun may sneak
in, but hopefully not enough to sabotage your learning process.

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.

There will be examples and explanations where I use math,


formulas and diagrams to help clarifying topics. They are
there to help you understand.

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

My goal in this book is simply to expose you to programming concepts. At the


end of the book, you will have seen the most common concepts in use.

Chances are you will not be able to write


working programs yet, but you should be well
prepared for what comes next.

In “Volume 2: Creating code” I will teach you


all you need to know in terms of actually
building the software.

If you find fractals or perhaps graphics as


interesting as I do, chances are you will be well motivated to write code of your
own before you reach the end of the next volume.

What comes next

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

1.1. INTR ODUCTI ON


When talking about basic programming concepts, they apply to most modern
computing devices. Your mind may go towads laptops, desktops, smartphones
etc.

Traditional computing devices

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.

Computing devices such as desktops and


laptops stand apart in one area; their
potential for computing power.

Computing platforms become more and


more powerful every year, but in general, a
fridge will never require as much power as a
dedicated gaming platform. That is just a
fact of life.

When writing this book, my focus was on Non-traditional computing devices


the traditional type of device. However, as
long as we can program a device and it has a screen, it does not matter. The
basic concepts are the same. More or less.

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.

A modern computer is also very fast. It is very easy to overlook because we


have been spoiled with amazing performance over the years.

For example, a modern run-off-the-mill computing device could move around


data contained in every single book, in a medium sized public library in a matter
of seconds. That is quite amazing when you think about it.

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.

We do this by writing down commands. Each command tells the computer to


do a very basic task. It could be asking it to multiply two numbers or to move
data from one place to another.

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.

We refer to the action of producing code as or .

Commands are like the words of a language. The programming language


defines what these words are and how we combine them to build code.

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.

Categori zing languages

Programming can vary in all sorts of manners, but we can roughly divide them
into two categories:

 Languages where we tell the computer it should do things.


 Languages where we tell the computer we want it to do

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.

The programming vehicle

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 compile process

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.

Storing values in memory

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

computer program may have hundreds, if not thousands of such commands


lined up. Imagine the nightmare it would be to read, write or in any way manage
code like this:

Snapshot of in memory commands

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.

We can then write the previous command like this instead:

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:

 Slow, but permanent

 Fast, but volatile

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.

If you own a computer or a smartphone,


you probably interacted with this kind
of memory on multiple occasions.

Some common types of slow memory


device are:

 Hard drives ( SSD or IDE)

 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?

Chances are you have bumped into one of the oddly


looking pictures shown to the right.

This is a QR code. It works pretty much like a


traditional bar code, but it can store slightly more data.
As long as it fits, we can store any type of data in it.
QR Code
Typically, you point your phone at a QR code to take a
picture and your phone extracts the encoded information from the iamge data.

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.

I chose to refer to the memories as


and for a reason. Earlier I stated that
the computer' operates at breackneck
speeds.

Slow memory is faster than the name


implies, but not nearly fast enough to keep
up.

however, is exceptionally
fast. It can easily march in lockstep with
the rest of your computer.

When you think of the computer doing


computations, it does so against data stored Permanent storage fallback
in fast memory.

It is such an integral part of the computer, that when speaking of memory,


usually we are talking about fast memory

ACCESS ING MEMORY


Conceptually, you can divide memory into small blocks that each hold a small
amount of data. One such block, can hold approximately enough data to
describe one single alphabet character.

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:

Storing string data

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.

We refer to the position as a . The action of referencing a


memory block, is known as as ‘addressing memory’.

In this example, we used a memory size of 20.000. Modern computers has


billions of memory blocks. Obviously, we do not want to deal with those
numbers on a daily basis.

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:

 Where is our data located?

 What is the type of data?

 What action do we want to perform on the data?

 How many times do we want it to happen?

 Are there any conditions?

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;

The concerns of a computer program

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:

<this is some code> // this is a comment

We identify the comment by two forward slashes . The compiler traverses


your source code line by line. It disregards all text following the comment
identifier til the end of the line.

Stripping comments during compile process

We use comments in our code to provide an immediate explanation of what the


code does. We can also use them to segment code, by providing headers or
titles to each section of our code.

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:

Integers int 102, 1, 2902, -2, 0

Decimal numbers double 23.345, 1.003, -3.14,


0.0

Boolean Bool true , false

General object object

String string “bjorn”, "this is a


string"

Nothing null Null

Data types

Let us quickly look at each column.

says what sort of data we are working with.

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

If you have two names that only


differs in case, the compiler sees
them as two completely different
names. ‘Double' and 'double' are
considered two completely different
keywords.
String comparison

provides examples of values each datatype is able to handle.

Integers (int)
This data type holds whole numbers. An integer can be negative,
positive or zero, but it cannot contain fractions.

The decim al (double)


To describe fractions, we use a decimal representation. It is hard to
represent fractions in an exact manner. At least it is more
complicated than with integers.

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.

I have selected one particular type represented by the keyword . It will


more than suffice for our purposes.

17
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

The Boolean ( bool)


The Boolean data type sounds stranger than it is. It allows only two
representations: ‘true’ or ‘false’. It is very important in decision
making, as computers tend to see things in black and white, or
rather ‘true’ and ‘false.

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 .

Object holding collection of decimal numbers

The diagram above shows an object that hold a list of decimal numbers and
provide functionality that exposes statistics about its content.

The string (string)


A string holds a piece of text. It could be a single line of text, or a
whole book. We surround text-strings with quotation marks to
distinguish between the text inside the string and commands in our
source code.

18
A Bearing E-Book

A string is actually an example of an object. In addition to the text value, it has


functionality that let you work with its content. For example, we can find out how
long a text string is.

The String object

The nothing va lue


This one may seem a bit weird. Sometimes we need to let the
computer know there is no data. Note that we distinguish between
the concept of empty data and no data.

For example, an empty is still a object. It has properties. Its length


is zero, but you can still work with it as any other string.

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.

Empty String object

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.

Data type symbols

I have listed some common uses in the diagram below:

Symbol usage examples

20
A Bearing E-Book

2 .3 . THE V ARI ABL E


The computer is exceptionally good at moving stuff around.

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.

It would be quite frustrating, having to


remember series of long numbers when
working with data. Additionally, we do not
care where in memory data are stored, as
long as we can easily access them.

So what can we do to fix this? We decide


that we want to reference the address by
name instead of number.

That is, we we want to associate a name with


our data. We then leave it to the computer
The variable
to deal with the details on how to store data.

Storing data in memory through variable assignment

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 .

We call this a variable. Specifically, this is the variable 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 to a variable

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

The math operat ors


Calculations are what computers do best. Most programming languages allow us to
use basic mathematical operations:

Addition

Subtraction

Multiplication

Divison

Common mathematical operators

Simple calculations

Let us use the information we have and try to calculate the circumference of a
circle:

double Circumference // Declare decimal number variable


double Radius // Declare decimal number variable
double Pi // Declare decimal number variable
Pi = 3.1415926535 // Stores the value 3.1415… in Pi
Radius = 3.0 // Stores the value 3.0 in Radius
Circumference = 2*Pi*Radius // Calculate the circumference

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.

We apply the formula for calculating the circumference of a circle:

Circumference = 2*Pi*Radius // Calculate the circumference

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’.

Applying formula for circumference of a circle

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.

Matching data types and variables

24
A Bearing E-Book

The modulus operator

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.

The modulus operator complements the integer division by calculating the


remainder of a division. We denote the operator by the character and use it
the same way we use the division operator .

Let’s say we want to know the remainder of dividing ‘3’ by ‘2’. We can rewrite
this as shown below:

Applying division and modulus operations

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

Let us go through one more example.

Dividing ‘4’ by ‘5’, the result is a fraction. I have


illustrated this in the diagram to the right.

The division returns ‘0’:

4 / 5 // Returns 0

The modulus returns ‘4’:

4 % 5 // Returns 4
Remainder only result

We call the numbers above and below the


divison and . We refer to the
result of the division as the quotient.

A pattern emerges when dividend keeps


increasing, but the divisor does not change.
Every time the dividend is a whole multiple of
the divisor, the remainder resets to zero. Elements of a divison

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.

Have a look at . Pay particular attention to the right-most columns


‘Integer Quotient’ and ‘Remainder’.

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

… … … ..

254%256 = 254 254/256 254

255%256 = 255 255/256 0 255

256%256 = 0 256/256 1 0

257%256 = 1 257/256 = (1+256)/256 1 1

Series of modulus operations

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

Casting: For cing a datatype


What happens if we try to store the wrong data type in a variable? For example,
what happens if we try to store the value ‘3.14’ in an integer variable?

Storing the wrong data type to a variable

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?

In some cases, the computer can make a qualified guess, though.

The diagram below demonstrates a property that can work to our advantage. It
is unproblematic to use a decimal to describe an integer value.

Automatic cast of integer value to decimal

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

Storing an in a will therefore work just fine. We call this ‘casting’. It is


the action of intentionally storing a value of one type into a variable of a different
type. It can happen automatically in some cases, or you can force the compiler
to do it.

Mixing data types

Below is code that adds two numbers:

int sum // Declare integer variable


int x // Declare integer variable
int y // Declare integer variable
x = 3 // Stores the integer value 3 in x
y = 5 // Stores the integer value 5 in y
sum = x+y

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.

Now, what happens if we mix data types by introducing a variable?

int sum // Declare integer variable


int x // Declare integer variable
string y // Declare string variable
x = 3 // Store the integer value 3 in x
y = “Person” // Store the string value “Person” in y
product = x + y // ???

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 :

double product // Declare decimal number variable


double x // Declare decimal number variable
int y // Declare integer number variable
x = 3.0 // Store decimal value 3.0 in x
y = 5 // Store integer value 5 in y
product = x * y // Try to calculate the product

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

Multiplying an integer and decimal with decimal result

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?

Well, not quite. Let me illustrate with another example.

Automatic casting failure

Consider the following code:

int product // Declare integer number variable


double x // Declare decimal number variable
int y // Declare integer number variable
x = 3.6 // Store decimal value 3.6 in x
y = 5 // Store integer value 5 in y
product = x * y // Try to compute product

31
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

We changed the data type of ‘product’ from to . Otherwise the code


is the same as before. Let us focus on the last line where the computation takes
place:

product = x * y // Try to compute product

We are trying to calculate the product of a decimal value and an integer.

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?

Multiplying an integer and decimal value with integer result

We could force the compiler to store a value in an . It would drop the


fraction and store the remaining integer. That could be a valid cast, or it could
break our program. It depends on what we need our program to do.

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.

In general, we avoid relying on automatic conversion by stating explicitly what


we want. That way we will avoid any nasty surprise down the road.

32
A Bearing E-Book

2 .4. COL LE CTIO NS


A collection is a bundle of data where
all data items have the same data
type.

We can have a collection of any of the


data types introduced til now.

The data types we have introduced


so far are lacking when it comes to
working with collections of data.
Collection types
Most languages allow many ways to
manage collections. I have focused on two in particular, which shall be more
than sufficient for our purposes.

First, let us look at how to work with a range of data without a dedicated
collection data type.

Summing variables

Imagine we have five integer variables set up in code:

// Declare integer number variables, and assign values


int Item1 = 10 // Declare variable, and assign 10
int Item2 = 100 // Declare variable, and assign 100
int Item3 = 1000 // Declare variable, and assign 1000
int Item4 = 10000 // Declare variable, and assign 10000
int Item5 = 100000 // Declare variable, and assign 100000

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

The following code will calculate the sum of these variables:

int sum = 0 // Declare sum variable and set to


sum = sum +Item1 // Add value of Item1 variable to sum
sum = sum +Item2 // Add value of Item2 variable to sum
sum = sum +Item3 // Add value of Item3 variable to sum
sum = sum +Item4 // Add value of Item4 variable to sum
sum = sum +Item5 // Add value of Item5 variable to sum

We declare ‘sum’ and add item values to it, one by one.

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:

List<int> Collection of integer values

List<double> Collection of decimal values

List<string> Collection of text data

List<bool> Collection of Boolean values

List<List<…>> Collection of Collection objects

The List<> type

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.

However, when it comes to collections, accessing data by their position makes


things much easier for us in the long run.

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.

In the diagram below, we have a assigned to the variable ‘manager’:

It manages a collection of integers, and currently holds four items.

Managing data with List<int>

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.

The type lets you work with most of the


available data types. It can even work with
itself.

In other words, it can work with a ‘List of a List


of a datatype’. You can keep nesting lists like
this to make multi-dimensional lists. I will
demonstrate this later in the book.

We access the core data types like ,


, etc. directly through the
variable.

The object manages other objects or


types. We store it in a variable, and then use it List containers
to manage its content.

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:

// SET UP COLLECTION OBJECT


List<int> manager // Declare variable that uses List<int>
manager = new List<int>() // Create object and store in manager

//ADD SOME DATA


manager.Add(10) // Add the number 10 to the list
manager.Add(100) // Add the number 100 to the list
manager.Add(1000) // Add the number 1000 to the list
manager.Add(10000) // Add the number 10000 to the list
manager.Add(100000) // Add the number 100000 to the list

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

In the code we declared ‘manager’ as a type:

List<int> manager

It means we wish to work with a list of integers. After declaring ‘manager’, it is


still empty. We must store something in it. We create a List<int> object and
store it the ‘manager’ variable:

manager = new List<int>() // Create object and store in 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.

Managing items with List<int>

37
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

The object lets us interact with the collection content in a number of


ways. Amongst other things, it allows us to:

 Inquire about number of items in list


 Add new items

 Delete existing items

Sn eak peak at func tions


When we want to perform some action on our data, we ask the object to
do it for us.

For example, to add a value of 10 to our list, we write:

manager.Add(10) // Add the number 10 to the list

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.

We refer to ‘Add’ as a . Functions can exist individually or they may


belong to some object.

When using a function that belongs to an object,


the dot separates the object from the function.

Have a look at the diagram to the right. The function


‘Add’ takes a new item value ‘10’ as input.

When called, it adds this value to the collection


managed by ‘manager’. It does not return any data.

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.

The Function definition

We can keep making calls to ‘Add’ to fill in more items in our collection:

manager.Add(10) // Add the number 10 to the list


manager.Add(100) // Add the number 100 to the list

Calling functions on the List<> object

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

Accessing c ollection d ata


In our example program , we fully populate our list:

//ADD SOME DATA


manager.Add(10) // Add the number 10 to the list
manager.Add(100) // Add the number 100 to the list
manager.Add(1000) // Add the number 1000 to the list
manager.Add(10000) // Add the number 10000 to the list
manager.Add(100000) // Add the number 100000 to the list

The ‘manager’ ensures we have the following arrangement in memory:

Memory arrangment in List object

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.

This makes it easy for us to work with items in the list.

For example, if we wish to assign a new value to the third item in the list, we
address the item with index 2.

In code, we provide the index inside a pair of brackets:

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

Storing int in List<int> collection

Summing variables with List<>

Let us try a complete example, where we sum up all the values in our list:

// DECLARE LIST VARIABLE


List<int> mydata // Declare a list<int> variable
mydata = new List() // Create list object and assign to mydata

// ADD CONTENT TO THE LIST


mydata.Add(10); mydata.Add(100); mydata.Add(1000)
mydata.Add(10000); mydata.Add(100000)

// CALCULATE THE SUM OF ALL NUMBERS IN LIST


int sum = 0
sum = sum + mydata [0]
sum = sum + mydata [1]
sum = sum + mydata [2]
sum = sum + mydata [3]
sum = sum + mydata [4]

41
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

We declare and initialize ‘mydata’. It is ready to work with a collection of


integers, but is empty.

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.

mydata.Add(10); mydata.Add(100); mydata.Add(1000)

The new solution seems to be longer


than the old one. It almost seems like a
step backwards.What gives?

To realize the true benefit of working


with collections we need to take a sneak
peak at the concept of looping.

I will cover this in detail later in the book,


but let us have a quick look through a
code example.

A looping construct allows us to repeat a


section of code a number of times or until
The looping construct
we no longer want to keep repeating the
code.

We can rewrite the code as follows:

// DECLARE LIST VARIABLE


List<int> mydata = new List<int>(); // Declare mydata

// ADD CONTENT TO THE LIST


mydata.Add(10); mydata.Add(100); mydata.Add(1000)
mydata.Add(10000); mydata.Add(100000)

// CALCULATE THE SUM OF ALL NUMBERS IN LIST


int sum = 0 // Declare sum and set to 0
foreach(int item in collection) { sum = sum + item}

42
A Bearing E-Book

We use a foreach-construct to loop through items in the collection:

foreach(int item in collection) { sum = sum + item}

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.

If we wanted to add ‘1000’ numbers, the original calculation would be ‘1001’


lines long. Our new code will always be ‘2’ lines long, regardless of the amount
of numbers to add up.

Looping constructs will come in handy when working with screen data. We shall
cover them in full detail in “Chapter 4”.

Multi -dimens io nal list s


In previous examples, our list always had one index. Sometimes we need to
index our data by more than one index. In other words, we have multi-
dimensional data.

2-dimensional lists

In the following, we will look specifically at 2-dimensional lists, as we are going


to need those later on.

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.

Managing 2-dimensional lists

To create a 2-dimensional liste, we create a of ( of ):

List<List<int>> screen

Given two index variables ‘x’ and ‘y’, this is how we index items:

screen[y][x]

Storing and representing 2-dimensional lists

44
A Bearing E-Book

Let us look a bit closer at this, to understand how the indexing works.

We could use the following code to write a value to our list:

List<int> line = screen[y] // Makes reference to current line


line[x] = 0 // Set element @ x,y to 0

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

We remove the parentheses:

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.

The array data typ e


We spent a lot of time talking about the type. Meanwhile, one of the core
data types actually support working with collections: the .

Let us demonstrate it with a code example:

// 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.

We create an object with the keyword, just as we did for

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 .

There is a more concise way to initialize an array:

s = new string[]{“one”,”two”,”three” }

This does exactly the same thing as the previous code.

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:

// DECLARE LIST VARIABLE


List<int> mydata = new List<int>(); // Declare mydata

// ADD CONTENT TO THE LIST


mydata.Add(10); mydata.Add(100); mydata.Add(1000)
mydata.Add(10000); mydata.Add(100000)

Taking advantage of , we can rewrite this code:

// DECLARE LIST VARIABLE AND POPULATE


List<int> mydata = new List<int>(new int[]{10,100,1000,10000,100000})

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.

3 .1 . COD E COM PL EXITY


To understand a piece of code, you must know the rules of the language, but
sometimes even that is not enough.

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?

Coding boils down to honing two overlapping skills:

 The ability to comprehend code


 The ability to write good 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

So what can we do to ensure our code is readable? We can start by informing


the reader about what is going on. We can use comments to accomplish that.
Let us look at that next.

3 .2 . COM M ENTS, PAR T DE UX


Have you ever read a long text, where the author forgot to add any kind of
formatting? No headlines, no titles, no paragraphs, no extra spaces and no
images. Nothing to break up the flow of the text. It becomes very hard to read.

Similarly, if your code is just a long list of commands with no breaks or spacing,
it will be difficult to read.

Have a look at the following code:

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

We separate each variable by a comma and can include assignments to give


variables a starting value as well:

double a,A, px1=10.0,px2=20.0

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

Variable declarations with assignments now appear on different lines. It


improves the first impression, but the meaning is still unclear.

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

// LEFT AND RIGHT CORNER OF TRIANGLE


// X coordinate is in the range [P1X, P2x]
double x1=11.0 // Left corner
double x2=15.8 // Right corner

// AREA OF RIGHT ANGLED TRIANGLE


a = ( py2 - py1 ) / ( px2 - px1 ) // Slope between P1 and P2
A = a*(x2 - x1)*(x2-x1)/2 // Area of triangle

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.

Documenting code with diagrams

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

3 .3 . VAR IABL E N AM ING


In mathematics or physics, we often use single letter variables. When working
with equations, this makes sense. For example, ‘v’ is a lot faster to write down
than 'Total_Velocity_Of_Car_A'. Especially if you have to write that name tens
of times, or maybe hundreds throughout a calculation.

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.

3 .4. INTE RM EDIAR Y VAR IABL ES


The area calculation of the code is still messy. Sometimes it helps to split up a
command. If you can assign a sensible name to a part, it may be worth it to move
that to a separate line.

// AREA OF RIGHT ANGLED TRIANGLE


// FINDING THE SLOPE OF THE LINE
double RateX = Point2_X-Point1_X // Intermediary variable
double RateY = Point2_Y- Point1_Y // Intermediary variable
Slope = RateY / RateX

// DECIDING POINTS ON P1-P2 LINE


double Left_Y = Slope*Left_X
double Right_Y = Slope*Right_X

// FINDING AREA OF TRIANGLE ( ASSUMING RIGHT ANGLE )


double Triangle_Width = Right_X - Left_X // Intermediary variable
double Triangle_Height = Right_Y - Left_Y // Intermediary variable

Area = (TriangleWidth * TriangleHeight) / 2

Let us illustrate by having another go at the calculation code:

Slope = RateY / RateX

We introduced the intermediary calculations for ‘RateX’ and ‘RateY’. The slope
calculation now looks like the formula for the slope of a line:

Similarly, we introduced the intermediary calculations for ‘TriangleWidth’ and


‘TriangleHeight’. The area calculation now looks like the definition straight out
of a mathematics textbook:

Area = (TriangleWidth * TriangleHeight) / 2

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

// TRIANGLE BOTTOM CORNERS


double Left_X = 11.0 , Right_X = 15.8 // On the line P1->P2

// AREA OF RIGHT ANGLED TRIANGLE


// FINDING THE SLOPE OF THE LINE
double RateX = Point2_X-Point1_X
double RateY = Point2_Y-Point1_Y
Slope = RateY / RateX

// DECIDING POINTS ON P1-P2 LINE


double Left_Y = Slope*Left_X
double Right_Y = Slope*Right_X

// FINDING AREA OF TRIANGLE ( ASSUMING RIGHT ANGLE )


double Triangle_Width = Triangle_Right_X - Triangle_Left_X
double Triangle_Height = Triangle_Right_Y - Triangle_Left_Y
Area = (TriangleWidth * TriangleHeight) / 2

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.

Once a program grows too large, it can be difficult to understand it as a whole.


Lines and lines of text can easily drown out the intention behind the code.

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:

Function with input and output

Assume we want to call a function getPi that returns the value of Pi:

double PI = getPI()

The value returned by the function is stored in the variable ‘PI .

Here is the implementation of ‘getPi’:

double getPI()
{
double pi = 3.14
return pi
}

The function returns a value of type We reference it by the name getPI .

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

The body consists of two lines.

First, we declare a variable ‘pi’


and give it the value 3.14.

On the next line, we use the


keyword to set this value
as the output of the function.

We refer to this as returning a


value from the function.

When returning a value, we must


ensure it complies with the
function definition. The ‘getPi’ function

In the example, we said it should


return a , so ‘pi must be a as well.

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:

int sum = add(1,2)

The function add takes the numbers ‘1’ and ‘2’ and returns an integer. This
returned value is then stored in the integer variable ‘sum

We can implement ‘add’ as follows:

// Performs calculation: x+y


int add(int x, int y)
{
int result = x+y
return result
}

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.

The function ‘add’ accepts two arguments, ‘x’ and ‘y’:

int add(int x , int y)

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:

int result = x+y


return 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’,

The ‘add’ function with two inputs

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.

Let us start with how we would call this function:

int a,b
(a,b) = getCoordinates()

The ‘getCoordinates’ function returns two integer values. We assign these


values to ‘a’ and ‘b’. This is just a shorthand notation.

For example, if our function returned (3,4), the previous command is just a
compact way of writing:

a = 3
b = 4

Here is the implementation of ‘getPointCoordinates’:

(int x, int y) getCoordinates()


{
int x = 3, y = 4
return (x,y)
}

What is different from previous examples, is how we return ‘x and ‘y by


grouping them together using parentheses.

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

// TRIANGLE BOTTOM CORNERS


double Left_X = 11.0 , Right_X = 15.8 // On the line P1->P2

// AREA OF RIGHT ANGLED TRIANGLE


// FINDING THE SLOPE OF THE LINE
double RateX = Point2_X-Point1_X
double RateY = Point2_Y-Point1_Y
Slope = RateY / RateX

// DECIDING POINTS ON P1-P2 LINE


double Left_Y = Slope*Left_X
double Right_Y = Slope*Right_X

// FINDING AREA OF TRIANGLE ( ASSUMING RIGHT ANGLE )


double Triangle_Width = Triangle_Right_X - Triangle_Left_X
double Triangle_Height = Triangle_Right_Y - Triangle_Left_Y
Area = (TriangleWidth * TriangleHeight) / 2

We want to use functions to split up this code, making it easier to grasp. We


shall extract code into its own function for:

 Slope calculation
 Ordinate pairs calculation
 Area calculation

61
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

Let us look at the slope calculation first.

The getSlope function

I have extracted the portion of the slope calculation:

// FINDING THE SLOPE OF THE LINE


double RateX = Point2_X-Point1_X
double RateY = Point2_Y-Point1_Y
Slope = RateY / RateX

We want to calculate the slope


based on the two control points ‘P1’
and ‘P2’.

Our function would require the


coordinates of the control points
and return the slope value.

The diagram to the right provides an


overview of the variables we are
working with.
Slope of P1-P2

The implementation of ‘getSlope’:

// CALCULATE THE SLOPE OF LINE DEFINED BY CONTROL POINTS P1 AND P2


double getSlope(double P1_X, double P1_Y, double P2_X, double P2_Y)
{
double RateX = P2_X - P1_X
double RateY = P2_Y - P1_Y
Slope = RateY / RateX
return Slope
}

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.

The getOrdinates function

Next up is the calculation of y-values of points that fall on the line P1-P2.

The code we wish to extract:

// DECIDING POINTS ON P1-P2 LINE


double Left_Y = Slope*Left_X
double Right_Y = Slope*Right_X

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’.

Ordinates of x1 and x2 on P1-P2

All inputs and outputs are of type . We implement ‘getOrdinates’:

// CALCULATES Y-COORDINATES OF POINTS ON P1-P2


(double y1,double y2) =
getOrdinates(double slope, double x1, double x2)
{
double y1 = slope*x1
double y2 = slope*x2
return ( y1, y2 )
}

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

The calculateArea function

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:

// FINDING AREA OF TRIANGLE ( ASSUMING RIGHT ANGLE )


double Triangle_Width = Right_X - Left_X
double Triangle_Height = Right_Y - Left_Y
Area = (TriangleWidth * TriangleHeight) / 2

Our function needs to know the point coordinates that define the triangle. That
is ‘Left_X’, ‘Left_Y’, ‘Right_X’ and Right_Y

All inputs are of type .

In total, it requires four input arguments and returns a value of type .

Calculating area of triangle

65
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

The implementation of ‘calculateArea’:

// CALCULATE THE AREA OF THE TRIANGLE DEFINED BY TWO POINTS Q1 AND Q2


double calculateArea(double x1, double y1, double x2, double y2)
{
double width = x2 – x1
double height = y2 – y1
Area = (width*height)/2
return Area
}

Again, I am using shortened variable names for the arguments, but otherwise
the calculations have not changed.

Replacing code with functions

To summarize; we have extracted three sections of code and moved them to


their own function ‘calculateArea’, ‘getyYCoordinates’ and ‘getSlope’:

Splitting up code in functions

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

// CALCULATION OF AREA OF RIGHT ANGLED TRIANGLE


Slope= getSlope(Point1_X,Point1_Y,Point2_X,Point2_Y)
(Left_Y,Right_Y) = getYCoordinates(Slope,Left_X, Right_X)
Area = calculateArea(Left_X,Left_Y, Right_X,Right_Y )

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.

Creating a master function

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.

There is nothing stopping us from calling


functions from within a function, so let us
define a function that contain all our code so
far.

The diagram to the left shows all the inputs


we need. There are two control points P1 and
P2 along with two x-values of points that fall
on the line P1-P2. These define a triangle.
Function inputs

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:

// DESCRIPTION: Defines area of the right angled triangle,


// defined by two point on the line P1->P2

// 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:

double Area = findTriangleArea(10.0, 2.0, 20.0, 30.0, 11.0 )

We can reuse this code. We call the function more than once for different inputs:

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 )

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 )

// HELPER FUNCTIONS =============================================

// DESCRIPTION: Defines area of the right angled triangle,


// defined by two point on the line P1->P2

// 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

} // ===========================================================

// CALCULATE THE AREA OF THE TRIANGLE DEFINED BY TWO POINTS Q1 AND Q2


double calculateArea(double x1, double y1, double x2, double y2)
{
double width = x2 – x1
double height = y2 – y1
Area = (width*height)/2
return Area
}
// ===========================================================

// CALCULATES Y-COORDINATES OF POINTS ON P1-P2


(double y1,double y2) = getYValues( double slope,
double x1, double x2)
{
double y1 = slope*x1
double y2 = slope*x2
return ( y1, y2 )
} // ===========================================================

69
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

// CALCULATE THE SLOPE OF LINE DEFINED BY CONTROL POINTS P1 AND P2


double getSlope(double P1_X, double P1_Y, double P2_X, double P2_Y)
{
double RateX = P2_X - P1_X
double RateY = P2_Y - P1_Y
Slope = RateY / RateX
return Slope
}

The black box


As long as the function never changes the expected inputs out output, we can
think of it as a black box. What I mean by this, is that when using the function,
we only care that it returns the expected output for a given input. We do not
need to know exactly how it does the job.

Black box

This is a concept also known as encapsulation. The function hide


implementation details from the rest of your program. It encapsulates your
code.

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.

We looked at how we can create and use functions. Through an example


spanning the subchapter, we showed how to use functions to segment code
and improve the readability of your code.

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.

You should have at least a passing understanding of what comments and


functions are.

In short, the main concepts were:

 Thoughtful use of variables and variable naming


 Use of comments to section code

 Using of comments to document code

 Use of functions to segment and organize code

 Use of functions to reuse code

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’.

I have listed the usual suspects in the table Is X not equal to Y? X != Y


to the right. The left column describes the
condition, while the right column shows Is X less than Y? X<Y
how we express the condition in code.
Is X larger than Y? X>Y
It is relatively straightforward. The
condition on the first line tests for equality. Common conditions
The remaining three tests for a variety of
inequalities.
Condition X=0
in code Y=0
Assume ‘X’ and ‘Y’ are two integers, both with the value ‘0’. I
have listed the result for each condition in the table to the right.
X == Y True
The only condition that returns ‘true’ is the test for equality.
This makes sense since ‘X’ and ‘Y’ hold the same value and X != Y False
therefore must be equal.
X<Y False
Note how we write the test for equality using two equal signs:

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’:

X == Y False False True

X != Y True True False

X<Y True False False

X>Y False True False

Examples of condition results

The if-else construc t


We use the ‘ construct to make choices. It allows us to execute code
according to a given condition.

Have a look at the following code:

// DECIDE THE SIGN OF AN INTEGER


string isNegative(int input)
{
bool isNegativeValue = input < 0
if( isNegativeValue ) { return "yes" } else { return "no" }
}

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’

bool isNegativeValue = input < 0

There are two possible outcomes of the condition:

 Input is negative : condition is true

 Input is positive or zero : condition is false

A variable can be ‘true’ or ‘false’, so it fits perfectly to hold the result.

Once we have established the condition, we can act on the result:

if( isNegativeValue ) { return "yes" } else { return "no" }

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

Code flow for ‘isNegative’

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" }

should run in either case of the condition.

We do not have to use a variable to hold the


condition. The -statement can use the condition directly:

if( input < 0 ) {...}

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

4.2. REPE ATIN G CO DE


One of the first things I stated about computers was that they are fast. It is easy
to overlook sometimes, but they are incredibly fast.

Depending on the complexity of an operation, a modern computer can perform


millions or even billions of operations in a mere second.

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?

Introducing the l oop


Untill now, we have worked with data by referencing each data item directly. If
we wanted to store ten values, we had to write ten assignment statements. To
store hundred values, we would have to write hundred assignments. To store
thousand values, thousand assignments etc. As you can imagine, it becomes
unmanageable in a hurry.

Luckily, we have a tool to help us:


the looping-statement. It comes in
different flavors, but ultimately
they all do the same thing.

They keep executing the same


code repeatedly, untill some
condition is reached.

We shall focus on three of them:

 The for-loop
 The while-loop
 The foreach-loop

The for-loop construct

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.

Let us have a look at each one of them.

The while-l oop


As the name alludes to, the -statement keep the loop going while the
looping condition is true.

Summing with the while-loop

Let us illustrate the use of the while-loop with an example.

We want to sum up the values of every integer in a list. The code to do this looks
as follows:

// CREATE COLLECTION CONTAINING ELEMENTS: 10 ,20,30,40,50


List<int> numbers = new List<int>(new int[]{10,20,30,40,50}

// DEFINE LOOPING PARAMETERS


int total = 0 // The running total
int maxIndex = 5 // Index of last element+1
int index = 0

// 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

We first define the variables needed to execute the


loop. We use ‘total’ to keep track of the sum and ‘index’
to point to a position in the list.

‘maxIndex’ defines the upper limit for ‘index’. We start


counting indexes at ‘0’, so the fifth item has index ‘4’.
The upper limit is one larger than the last index.

The while-statement kicks off the loop by checking if


our looping index has reached its max value:

while( index < maxIndex)


List indexing

The body of the loop keeps repeating as long as this is


true. We tally up the total and then increase ‘index’ by one. This happens on
every loop. Finally, the while-loop terminates once ‘index’ exceeds the
‘maxIndex’ limit.

‘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.

Code flow for while-loop

80
A Bearing E-Book

Let us trace the values as they change. The table below shows key values at
every loop:

First time through 0 numbers[ 0 ]  total = 0 + 10 = 10


10

Second time 1 numbers[ 1 ]  20 total = 10 + 20 = 30


through

Third time through 2 numbers[ 2 ]  total = 30 + 30 = 60


30

Fourth time 3 numbers[ 3 ]  total = 60 + 40 = 100


through 40

Fifth time through 4 numbers[ 4 ]  total = 100 + 50 = 150


50

Sixth time through 5

Tracing changes through while-loop

, index is ‘0’. This index corresponds to the first item in the


list. We retrieve the value and add it to the total. At the end of the loop, we
increase ‘index’ by one.

, index is ‘1’. This corresponds to the second item in


the list. We update the total and increase ‘index’ by one.

The loop keeps going, untill we reach the end of the fifth step. After increasing
‘index’ it now has the value ‘5’.

, the index is ‘5’. This breaks the condition that ‘index’


must be less than ‘5’, so the while-loop terminates.

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.

The code below uses a for-statement to recreate the while-loop example:

// CREATE COLLECTION CONTAINING ELEMENTS: 10 ,20,30,40,50


List<int> numbers = new List<int>(new int[]{10,20,30,40,50}

// DEFINE LOOPING PARAMETERS


int total = 0 // The running total
int maxIndex = 5 // Index of last element+1

// 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.

Dissecting the for-header

for (int i=0 ; i< maxIndex ; i=i+1)

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

We have three different sections of code in side the for-statement:

Elements of the for-loop statement

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

Using the for-loop

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:

for (int x=0 ; x < 5 ; x = x +1) // x = 0,1,2,3,4


{ sum = sum + 1} // some loop code

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.

for(int index =0 ; index < 6 ; index = index + 2) // index = 0,2,4


{ sum = sum + 1} // some loop code

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

for(int q =5 ; q > 0 ; q= q-1) // q = 5,4,3,2,1


{ sum = sum + 1} // some loop code

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.

Calculating with for loops

Earlier, we saw an example on how to find the total of the items in a collection:

// CREATE COLLECTION CONTAINING ELEMENTS: 10 ,20,30,40,50


List<int> numbers = new List<int>(new int[]{10,20,30,40,50}

// DEFINE LOOPING PARAMETERS


int total = 0 // The running total
int maxIndex = 4 // Index of last element

// 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.

Elementwise multiplication of lists of integers

We only need a few changes to the previous code:

// CREATE COLLECTION CONTAINING ELEMENTS: 10 ,20,30,40,50


List<int> listX = new List<int>(new int[]{10,20,30,40,50}
List<int> listY = new List<int>(new int[]{2,0,0,-2,0}

// DEFINE LOOPING PARAMETERS


int total = 0 // The running total
int maxIndex = 5 // Index first index out of bounds

// 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:

List<int> listX = new List<int>(new int[]{10,20,30,40,50}


List<int> listY = new List<int>(new int[]{15,0,0,-20,0}

We loop through the indexes for every item in the lists:

for (int i=0;i< maxIndex; i=i+1)

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]

Finally, we calculate the product and add it to the total:

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’.

When you multiply the two values, the result is ‘0’.

87
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

Accessing third element by index

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:

total = total + listX[index] * listY[index]

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

Looking up data with for-loops.

We can use for-loops to identify data. Assume we want to search through a list
of names for a specific match.

bool function hasName(string search, List<string> names)


{
// LOOPING PARAMETERS
int maxIndex = names.Count -1 //Index of last list-item

// LOOP THROUGH ITEMS


for(int idx=0; idx<=3 ; idx = idx +1) // Runs through index 0 to 3
{
string currentitem = names[idx] // Item at current position
if(currentitem == search) { return true } // Exit if match}
}
return false; // No match found
}

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.

To make use of this function we could write the calling code:

// CREATE COLLECTION AND POPULATE


List<string> names = new List<string>(new string[]{
“teodor”, “sam”, “Samantha”, “xavier” })
// IDENTIFY NAME
bool hasSimon = hasName("simon", names)
bool hasSam = hasName("sam", names)

Let us trace the code, starting at the first function call. We call ‘hasName’ with
two arguments:

bool hasSimon = hasName("simon", names)

89
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

If we compare the function call with the function definition

bool function hasName(string search, List<string> names)

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:

int maxIndex = names.Count -1 //Index of last list-item

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.

Setting the max index

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.

for(int idx=0; idx< maxIndex ; idx = idx +1)

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.

string currentitem = names[idx] // Item at current position


if(currentitem == search) { return true } // Exit if match}

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:

return false; // No match found

No match on “simon”

91
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

Note that when we use the keyword within a function, it immediately


exits. No other function code will run. The program continues executing the
code that called the function.

Returning from a function

Let us look again at the code where we called ‘hasName’:

bool hasSimon = hasName("simon", names);

Once ‘hasName’ completes, it returns a Boolean value that indicates whether


there was a match or not.

As we saw earlier, “simon” is not in the list of names so ‘hasName returns .


We store the result in the variable ‘hasSimon’.

92
A Bearing E-Book

There is one more line in the main of our program:

bool hasSam = hasName("sam", names);

Let us quickly trace this code as well.

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:

string currentitem = names[idx] // Item at current position


if(currentitem == search) { return true } // Exit if match}

This time around, the name list contains the string “sam”.

Matching on item “sam”

Eventually the search condition matches and we exit the function with a
value. The calling code stores the result in the variable ‘hasSam’.

At the end of this function call, ‘hasSam’ contains

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.

Luckily, there is a pair of scissors available also; the -loop It provides us


with a more succinct and easy-to-read version of the for-loop.

List<string> names
... // Code to populate collection

foreach(string name in names )


{ ... }

The command goes through every item in ‘names’ and assign it to


‘name’. For each loop, you use ‘name’ to work with the current item. There are
no indexes or counting necessary here.

Dissecting the foreach-header

foreach(string name in names )

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 .

We simply provide the collection that we wish to traverse.

names

Using the foreach-loop

We previously built the ‘hasName’ function, using the for-loop:

bool function hasName(string search, List<string> names)


{

// LOOPING PARAMETERS
int maxIndex = names.Count -1 //Index of last list-item

// LOOP THROUGH ITEMS


for(int idx=0; idx<=3 ; idx = idx +1) // Runs through index 0 to 3
{

string currentitem = names[idx] // Item at current position


if(currentitem == search) { return true } // Exit if match}

return false; // No match found

95
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

We can rewrite this function, using the construct:

bool function hasName(string search, List<string> names)


{
foreach(string name in names){ if(name == search) { return true } }

// 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

4.3. REUS ING C ODE


We have everything we need to build a working program. Well almost. The core
functionality of most programming languages is somewhat limited.

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.

When we first introduced the function, we used it to distribute code to make


code easier to read.

The diagram to the right shows a


birdsview of the ‘findTriangleArea’
function we created earlier.

I mentioned how functions could


open up for code reuse.

The idea is that either of the new


functions could be valuable in other
scenarioes.

It is now relatively easy to pull that


code out and use it elsewhere.
The function ‘findTriangleArea’

97
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

Consider a function that verifies text input. It could look like this:

bool isValidString(string input)


{
if(input == null) { return false} // Is variable set at all?
if( input == "") {return false} // Does variable have content?
return true
}

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.

An empty string object

The function ‘isValidString’ consider either value as invalid, so it must test for
the presence of both of them.

So why did I introduce this function? It is an example of a function that lends


itself towards reuse.

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.

We want to group functionality together according to their use. Mathematical


operations would go into one group, functionality to support file operations
would go into another while string operations go in their own group. And so on.

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.

The larger view

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.

Some examples are:

 Graphics card libraries

 A web-browser component

 Robotics

 Physics calculations

 Mathematical calculations

 Language dictionaries

 AI driven tools

Etc.

The list goes on and on.

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.

You can think of a framework as a collection of libraries (, and other functionality)


that can help you in doing some common programming task.

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.

Summa rizing the building


blo cks
Depending on how fast you went through the first half of this book, you may feel
slightly overwhelmed. I have tried to be brief, but we have covered a lot of
ground.

Let me try to summarize everything we have gone through so far:

Data types Int, double, string, bool, object

Variables and string myVar = “This is my string”


assignments int myNumber = 888

Simple numerical Add


operators

Subtract

102
A Bearing E-Book

Multiply

Divide

Comparisons Less than

Greater
than

Less than
or equal to

Greater
than or
equal to

Not equal
to

Collections string names = new string ()

int values = new int (int[]{1,2,3})

Loops -loop , -loop , -loop

Making decisions ( x > 0 ) { return false } { return true }

Functions int (int ,int ) { return + }

Libraries and
frameworks

Base programming concepts summary

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.

It could take experienced developers years to build a complete framework,


while we could churn out the code for a simple function in less than a minute.

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.

Things not co vered


In order to keep it simple, there are quite a few concepts I have glossed over or
simply skipped. The idea was to provide you with a bare minimum. Just enough
for us to make working programs.

There are four perhaps noticeable omissions. Let us quickly talk about each one
of these.

Validation

Throughout the examples I have given, I generally made quite a bit of


assumptions. One of them is that variables actually contain what we expect
them to.

104
A Bearing E-Book

What happens if they do not? Assume we have the following code:

List<int> data = new List<int>() // Initialized with empty list


int numberOfItems = data.Count // numberOfItems = 0

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.

What happens if we forget to initialize the list?

List<int> data // Not initialized


int numberOfItems = data.Count // data=null. Invalid operation

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

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

To a certain degree, it can hide away implementation details as well.

The OOP object executes code, it can take arguments that affect operation and
it can return data.

The object

Depending on the programming language, that is where the similarities stop. At


least when we are talking about functions and OOP objects conceptually.

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.

A property gives you access to a state or value of the object.

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.

Function and property interfac eon object

Let us have a look at the previous example once more:

List<int> data = new List<int>() // Initialized with empty list


Int numberOfItems = data.Count // numberOfItems = 0

I have generally referred to as a type, but sometimes I used the word


object. It is indeed an OOP object.

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

This topic is arguably as large as that of Object Oriented Programming.

A spelling mistake, missing validation or a lack of understanding of what you are


trying to solve, can give rise to errors. We call these errors ‘bugs’. There are
methodologies and tools availble to make this less of a problem.

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. BUIL DIN G C ODE

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.

A screen image is composed of


picture elements. We abbreviate the
name 'picture element' to . Each
pixel has two properties: position and
color.

Screens have widths and heights. The


width of the screen is simply how
many pixels we can fit horizontally. The
height is how many pixels we can fit Screen parameters
vertically.

We usually refer to the dimensions of the screen as x ( E.g.


1600x900 ).

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.

The concepts of ‘screen’ and ‘image’ are almost interchangeable. The


difference is, that the screen refers to the physical device you look at, while
image is the color data that you want to display on 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:

The screen and the pixel

We represent the position of a pixel by its horizontal position and its vertical
position. We group these two numbers into a coordinate pair.

Let us look at the horizontal position first:

Addressing pixels horizontally

111
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

We start counting from the leftmost pixel. An index value of ‘7’


places us at the eigth pixel.

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

The Pixel Color


We define the colors on a computer by setting three base colors: Red, Green
and Blue. The value of each component is in the range [0 to 255], indicating how
much each component contributes to the final color.

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.

By adjusting each component in the range [0 to 255], we can create


approximately 16 million different colors.

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’.

Component contributions for various colors

113
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

The Screen Buffer


We use something called a screen buffer to put colors to the screen. As far as
we are concerned, it is just an image, or a collection of color data.

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 ).

The screen buffer

If we wanted to set the on-screen color at position (x=7,y=4), we simply assign


a color value to the corresponding position in the screen buffer.

Setting a pixel color in the screen buffer

114
A Bearing E-Book

On a modern high-resolution screen, pixels are so tiny it is hard to see a single


pixel, but as long as we update many pixels at a time, the changes do become
easier to see.

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.

Modifying the screen buffer

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

5 .2 . CRE ATI NG I MAG ES


Assume we have a mathematical function that calculates a value based on two
inputs ‘x and ‘y . We could represent it with a 3D plot:

Function of two variables

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.

Algorithmic view of color-plotting

116
A Bearing E-Book

Filling the scr een


We now know how to define a color and how we can put it on-screen using the
screen-buffer.

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.

Traversing pixels horizontally

After we have completed filling in one line, we move on to the line below.

We keep going til we have processed every line in our image.

Traversing lines

117
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

Let us try some code.

The function 'clear', paints the whole screen in one color:

void clear(List<List<(int,int,int)>> screen, int width, int height)


{

//DEFINE LOOP PARAMETERS


int max_pixel_idx = width - 1 // Index of last pixel on a line
int max_line_idx = height - 1 // Index of last line
(int r,int g,int b) blackcolor = (0,0,0) // The color Black

//TRAVERSE ALL PIXELS


for (int y=0; y<max_line_idx; y =y+1) // Run through y-values
{
for (int x=0; x<max_pixel_idx; x=x+1) // Run through x-values
{
screen[x][y] = blackcolor // Set pixel to black
}
} // End of y-loop
}

It takes the screen-buffer, screen width and screen height as arguments:

void clear(List<List<(int,int,int)>> screen, int width, int height)

We define the max ranges for indexes:

//DEFINE LOOP PARAMETERS


int max_pixel_idx = width - 1 // Index of last pixel on line
int max_line_idx = height - 1 // Index of last line

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

Finding the max collection index

The variable makes code easier to read:

(int r,int g,int b) blackcolor = (0,0,0) // The color Black

This is just a compact way of writing:

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:

for (int y=0; y<max_line_idx; y =y+1) // Run through y-values

Inside the outer loop, we set up a second loop that goes through indexes for
every pixel on a line:

for (int x=0; x<max_pixel_idx; x=x+1) // Run through x-values

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.

Traversing all pixels with nested for-loops

We simply want to fill the screen with the same color, so we set the value of the
current pixel to :

{ screen[y][x] = blackcolor } // Set pixel to black

We chose the variable names ‘x’ and ‘y’ to denote position, simply because they
are short and commonly known for this purpose.

You are ofcourse free to name them as you


please.

In summary, starting at the upper left corner the


function paints the screen black, pixel-by-pixel.

At every line, we go from left to right untill the


end of the line. It then starts over from the first
pixel on the next line and keeps repeating this
process til the whole screen is one color
Painting the screen black

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.

The inner loop used to look like this:

{ screen[y][x] = blackcolor } // Set pixel to black

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

{ screen[y][x] = getColor(x,y) } // Generate color

color based on the position, we can write:

‘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.

Generating color plot #1

We are getting close. All we need to do is to implement the ‘getColor’ function


so that it generates a color based on a given coordinate:

(int,int ,int) getColor(int x, int y, int width, int height)


{
//CASTING VALUES
double a = (double) x, b = (double) y
double w = (double) width, h = (double) height

//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:

Painting screen with smoothing function

Let us dive into the code and explain how it creates this image.

The first thing we do is to cast the input to :

//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’

Next, we take care of the calculations:

//PERFORM CALCULATIONS
double maxval = w*h // Max possible value
double smooth = (a*b)/maxval // Performing calculation

As ‘x’ and ‘y’ increase, so does


the product of ‘x’ and ‘y’.
When ‘x’ and ‘y’ reach their
maximum values, so will the
product. We store the
product in ‘maxval’.

The lowest value of the


product occurs when either

Product as a function of position

‘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’.

Smooth as function of product p

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.

Analyzing smooth output

Back to our code, the next line converts the result into an integer value in the
range [0 to 255]:

int componentvalue = (int) Math.Round(255*smooth)

We know that ‘smooth’ is a decimal value somewhere in the range [0 to 1]. We


multiply it by ‘255’, to get a decimal value in the range [0.0 to 255.0].

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.

Using the Math.Round function

We only have to tell the compiler what library and function we want to use:

(int) Math.Round(decimalvalue)

This rounds the decimal value to its nearest


integer. I have shown a few examples in the
image to the right.

Note that ‘Math.Round’ returns a value of type


. The component value expects an
value, so we must cast the result back to

The only thing remaining is to declare the


actual color. To keep it simple, we assign the
value to ‘red’ and set ‘blue’ and ‘green’ to ‘0’.
Rounding decimals

//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.

Generating color plot #2

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)

double calc3 = (128.0 + 127.0 *((Math.Cos(0.008*a) +


Math.Sin(0.002*a*b))/ 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.

The sine and cosine functions

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.

Let us look at the calculation for one of the components:

double calc1 = 128.0 + 127.0 * (Math.Cos(0.0021 * (a*b)))

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:

-1  128.0 + (127.0 * -1.0) = 128.0 -127.0 = 1.0

+1  128.0 + (127.0 * 1.0) = 128.0 + 127.0 = 255

In other words, the calculation results in values safely within the required range
of [0 to 255].

All three equations have similar behavior.

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

Running our updated code, we end up with the following picture:

Generated image with trigonometric functions

That looks rather interesting, no?

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:

More outputs based on trigonometric functions

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

5 .3 . THE MANDEL BRO T


FRACTA L
We have reached the top of the mountain! We are ready to make our first
attempt at a fractal generator.

The bas e formula


The mandelbrot fractal emerges from throwing numbers into this formula:

= +

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.

The fractal feedback loop

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.

For example the variables ‘Z’ and ‘C’ could be:

= 1.5 + ⋅ 3.0

= 2.0 + ⋅ 8.0

This is a mathematical construct called , but please do not let


that name scare you. Complex numbers are relatively easy to understand. At
least for our purposes.

Let us rewrite the complex numbers to a form that is less confusing:

= [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.

In general, we can write any complex number as:

=[ , ]

, where a and b are the component values of ‘Z’.

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 programmable Mandelbrot equations

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

Fractal systems have one feature


in common. A system generate
some result. We then feed that
result back into the system, and
round and round we go.

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.

I have illustrated this process as a feedback diagram below:

The Mandelbrot feedback system

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?

We need to be a bit clever.

Instead of looking directly at a single


variable in our system, we will use the
state of the system as a base for
selecting color.

Let us give it a try.

Selecting colors

134
A Bearing E-Book

Parti al 2-Co lor Mand elbrot


In the previous chapter, we created a framework for painting colors to the
screen. It would run through every pixel and assign a color. To determine the
color we would call the function ‘getColor’.

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.

This is the Mandelbrot implementation of ‘getColor’:

(int,int ,int) getColor(int x, int y)


{
// COLOR SCHEME
(int, int, int) explodedColor = (30,30,255) // Light blue
(int, int, int) settledColor = (0,0,0) // Black color

//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

// TEST IF MAGNITUDE EXCEEDED EXPLODE THRESHOLD


double magnitude = a*a + b*b
if(magnitude >= explodethreshold)
{ exploded = true; break;} // Value exploded, finished
}

// PICK COLOR AND RETURN


if(exploded) { return explodedColor }
else { return settledColor }
}

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.

Next, we set a couple of parameters that control our calculations:

//PARAMETERS
int maxLoopCount = 256
double explodedThreshold = 4.0

‘maxLoopCount’ limits how many times we repeat the calculations. Ideally, we


should repeat them forever, but then our program would also take forever. We
cannot wait that long, so we set some practical limit. It is worth to note, that the
larger we set this value, the longer it will take to complete.

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

Remember the notation that we used to introduce complex numbers:

= [ , ] = [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.

We are ready to start the loop:

//CALCULATE Z = Z^2+C
double exploded = false
for(int i=0;i<maxLoopCount;i = i+1) {...} // Keep iterating

The for-loop runs as long as possible, limited by the ‘maxLoopCount We use


the variable ‘exploded’ to indicate whether ‘Z’ exploded during the current loop.

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’:

initializing the Mandelbrot system

137
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

//APPLYING MANDELBROT FORMULAS ( Z= Z^2+C )


double a_new = a*a – b*b + Ca // a component of new Z value
double b_new = 2a*b + Cb // b component of new Z value
a = a_new; b = b_new // Set new Z value

It is tempting to skip the temporary variables and write the assignments as:

a = a*a – b*b + Ca // a component of new Z value


b = 2a*b + Cb // b component of new Z value

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.

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.

I introduced the concept of explosion. We want to


set the color according to whether the system
exploded or not, but how exactly do we decide when
that happens?

We make an assumption: if the size of ‘Z’ passes


some threshold, we assume it is going to explode.
Right, but what do we mean by the size of a complex
number? The explode threshold

138
A Bearing E-Book

Size of a complex number

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.

The magnitude of ‘Z’

We can determine the length of ‘Z’ by making use


of some basic trigonometry.

The Pythagoras formula lets us calculate the


length of any side in a right-angled triangle, as
long as we happen to know the length of the two
other sides.
Pythagoras
Comparing the two diagrams in and
we can express:

( ℎ ) = +

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

Finding the explode threshold

We can use this result to test if ‘Z’ exploded:

√ ⋅ + ⋅ > ℎ ℎ

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:

a*a +b*b > explodedThreshold

140
A Bearing E-Book

Testing for explosion

In code, we test against the value of ‘explodeThreshold’. We previously set the


value of the threshold to ‘4.0’.

// TEST IF MAGNITUDE EXCEEDED EXPLODE THRESHOLD


if( (a*a + b*b) >= explodethreshold)

If the test holds true, we signal that ‘Z’ exploded and exit the loop:

{ exploded = true; break;} // Value exploded, finished

At this point, there are two possibilities:

a) ‘Z’ exploded. We exit with ‘exploded’ set to .

b) No explosion. We exhausted the loops and exit with ‘exploded’ set to

Code flows for and scenarios

141
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

We can then easily determine the appropriate color to plot:

// PICK COLOR AND RETURN


if(exploded) { return explodedColor }
else { return settledColor }

That is about it. Running our program, we get this picture:

Our first Mandelbrot plot

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?

Let us proceed with the next example, to figure it out.

142
A Bearing E-Book

The ful l 2 -Colo r Man delbrot


Let us bring up the diagram of the calculation loop again:

The Mandelbrot system

You may notice that as we repeat calculations, only ‘Z changes. The value of ‘C’
does not change inside the loop.

Let me rearrange the diagram slightly to make this clearer:

Seeded Mandelbrot system

143
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

If we block out the internal details we get this diagram:

Simplified Mandelbrot system diagram

We feed the system with ‘C’ and the system returns some output that we can
use to calculate a color.

Our complex number C was defined as :

=[ , ]

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:

The Mandelbrot space

144
A Bearing E-Book

In the remaining explanations,


I will refer to the values chosen
for ‘ca’ and ‘cb’ as the
.

As we traverse the screen we


get a pair of screen
coordinates, but we need
coordinates in the Mandelbrot
space. How do we convert
from one to the other?

Let us experiment a bit and The screen space


see what happens if we use
screen coordinates as input for ‘C’ directly.

That is, we use ‘x’ as value for ‘ca’ and


‘y’ as value for ‘cb’.

When traversing the screen, starting at


the uper left corner, the first two pixels
have coordinates:

[ , ] = [0,0]

1, 0
= [1,0]
Pixel coordinates

If we apply those to ‘C’ we get the values

= [ , ] = [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:

Properly matched coordinates ( Screen space  Mandelbrot space )

146
A Bearing E-Book

We have to scale the chosen coordinates in the Mandelbrot space so they map
nicely to our screen coordinates.

Mandelbrot- to Screen Space

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 a look at the diagram to the right. As


we go through values of ‘x’, we want to
pick values of ‘m’ so the endpoints match.
In other words; when ‘x’ is ‘0’, ‘m’ should
be ‘10’. When ‘x’ reach ‘29’, ‘m’ should be
‘19’.

When traversing the screen, we increase


‘x’ by ‘1’ to go forward one pixel.

The question is: how much should ‘m’


change every time ‘x’ changes so we
Relative traversal in ‘x’
ensure the endpoints match?

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

We can write the ratio:

ℎ −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

Relative increase of ‘x’ and ‘m’

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.

We have found a way to decide a scaling factor as we move horizontally. The


approach is the same when move vertically. The only difference is in variable
names:

Relative traversal in ‘y’

149
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

That sorts the scaling problem. Time to rewrite our code to match:

(int,int ,int) getColor(int x, int y,


double width,double height
double a1, double b1, double a2, double b2)
{

//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

double ratio_x = (b2 - b1) / width;


double ratio_y = (a2 - a1) / height;
double Ca = xstart + x * dx;
double Cb = ystart + y * dy;

//CALCULATE VALUE
double exploded = false;

for(int i=0;i<maxLoopCount;i = i+1) // Main loop


{
double a_new = a*a – b*b + Ca // Mandelbrot formula for Za
double b_new = 2*a*b + Cb // Mandelbrot formula for Zb
a = a_new; b = b_new // Storing results back in Z

double magnitude = a*a + b*b // Measure for size of Z


if( magnitude > limit ) // Check if we hit the limit
{ exploded = true; break;} // value exploded, stop looping

} // 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:

(int,int ,int) getColor(int x, int y,


double width,double height,
double a1, double b1, double a2, double b2,)

The diagram below illustrates what the arguments represent:

‘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.

Moving from screen space to Mandelbrot space

Let us look at the code first:

double Ca = a1 + x * ratio_x
double Cb = b1 + y * ratio_y

Figure 5-50 Screen space and Mandelbrot space coordinates

152
A Bearing E-Book

The formulas convert our screen coordinates [x,y] to coordinates in the


Mandelbrot space [Ca,Cb]. How exactly did we end up with them?

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.

Ratios screen space to Mandelbrot space

We can describe the ratios as the relationships between changes along the
same axis:

Δ
=
Δ

Δ
=
Δ

We read as “delta”. For example reads “delta-x”. We use deltas to


represent the difference between two values.

153
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

There are four such deltas, or differences in our diagram:

Δ = −

Δ = −

Δ = −

Δy = −

For the screen coordinates, the first point is ‘0’. We can simplify and :

Δ = − = −0=

Δy = − = −0=

Replacing the screen deltas in our ratio formulas:

Δ Δ
= =
Δ

Δ Δ
= =
Δ

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⋅Δ = ⋅

Δ = ⋅

Earlier we stated that ‘delta_Ca’ is defined by:

Δ = −

We can insert for Δ (delta-Ca) in the ‘ratiox’ formula:

Δ = ⋅

(C − )= ⋅

− = ⋅

155
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

We want to isolate Ca on the left-hand side.

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:

= + ⋅

Following the same steps for ‘ratioy’, we arrive at:

= + ⋅

We use these equations in our code verbatim.

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.

Still, I wanted to give you an opportunity to see how we arrived at these


formulas, rather than just grabbing them out of nowhere.

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:

color = getColor(x, y,-2.0, -1.1, 0.5, 1.1, width,height)

The coordinates correspond to a view of the whole Mandelbrot set:

Coordinates for full Mandelbrot set

Running the code we get the full mandelbrot set in view:

Output of Mandelbrot program

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:

color = getColor(x, y,-1.8, -0.8, -0.37, 0.37, width,height)

Selecting section of Mandelbrot set with ‘getColor’

While it is fascinating, it certainly lacks color. We shall look into that in a


second, but first I want to look at a special case.

158
A Bearing E-Book

A special case

Assume the starting point in the Mandelbrot space is [a1=0 , b1=0]).


Let us say our screen is ‘1000’ pixels wide and ‘1000’ pixels high. Our source is
‘1’ unit high and ‘1’ unit wide.

The ratios are:

1
= = 0.001
1000

1
= = 0.001
1000

Here is the code that does the scaling:

double Ca = a1 + x * ratio_x
double Cb = b1 + y * ratio_y

Slope = RateY / RateX

‘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

Do you recognize these? We used these equations in our first attempt to


create a Mandelbrot plot. The magic numbers originate from a clever
selection of parameters. They fit the scenario where we want to plot a 1 by 1
unit in the Mandelbrot space, to our whole screen.

The numbers presume a 1000x1000 screen, but even if your screen


dimensions were slightly different, it would still put the fractal in view. Which is
all we cared about at the time.

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.

However, I am not completely satisfied quite yet. There is one remaining


problem. We generated the fractal in two colors. The complexity is quite
interesting, but estethically it is a bit underwhelming.

Let us try to fix that.

Frac tal , V3: mo nochromatic


Have a quick look at the calculation part of our loop:

for(int i=0;i<maxLoopCount;i = i+1) // Loop for as long as possible


{

//CALCULATE VALUES OF a AND b


< ... > // Don't care about this for now

double magnitude = a*a + b*b // Magnitude of Z


if( magnitude > limit ) // If we hit the limit
{ exploded = true; break;} // Exploded, no need to continue.
}

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

Converting Mandelbrot system output to color

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.

This is known as an algorithm. It describes in concrete steps of what the


computer should do. In most cases, you would start by writing the algorithm
before writing code.

161
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

Implementing the algorithm

We already built most of the function in our previous attempt.

We only need to update some parts of it:

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

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 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;

for(int i=0;i<maxLoopCount;i = i+1)


{ ... }

Previously we declared the looping variable inside the -statement. This


would ensure that the looping variable is only accessible inside the -loop. Any
code before or after the for-loop would not be able to access it.

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

This is exactly what we do in the code below:

// DEFINE COLOR
int R = i % 256; int G = i % 256; int B = i % 256

The result

That is it. If we run our code, we get this picture:

Output of Mandelbrot generator program

164
A Bearing E-Book

Frac tal, V3: full color


The previous result was quite an improvement, but colorwise perhaps a bit dull.
Very monochromatic. We shall try to liven it up a bit.

One popular method to color fractals is to use a color palette.

Figure 5-57 Defining color palette for colorization of Mandelbrot output

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

Color components for grey values

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’.

Looking at our color assignment code again:

// 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.

Individual color rates

We can make each component change at a different rate, simply by multiplying


each component with a different value:

int R = (1*loopcount)% 256


int G = (3*loopcount)% 256
int B = (6*loopcount)% 256

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.

Output of Mandelbrot generator program , with individual color rates

Just to fully appreciate what we have accomplished so far, let us zoom in a bit:

Output of Mandelbrot generator program , individual color rates, zoomed in

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?

There is only one way to find out!

Adjusting the component rates

To introduce colors in our plot, we multiplied the color components with


different integers:

int R = (1*loopcount)% 256


int G = (3*loopcount)% 256
int B = (6*loopcount)% 256

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:

int R = ((int)(3.8*loopcount))% 256


int G = ((int)(0.95*loopcount))% 256
int B = ((int)(0.95*loopcount))% 256

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.

Output of Mandelbrot generator program , adjusted multiplication factors

Using loop percentage

It would be a lot easier to control the colors if we could


base the color of a value in the range [0.0 to 1.0].

Instead of binding the color directly to the loop counter,


we can look at the relative size. What I mean by that is the
size of the loop counter in relation to its maximum size.

For example, if the max loop count is set to ‘1000’, a loop


count value of ‘1000’ equals 100% of its max value. A
loop count value of ‘500’ equals 50% and so forth.

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

Finally, we adjust the component rates to make a more colorful plot:

int R = ((int)(2*255.0*loopcount/maxLoopCount)) % 256


int G = ((int)(52*255.0*loopcount/maxLoopCount)) % 256
int B = ((int)(113*255.0*loopcount/maxLoopCount)) % 256

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

This makes it easier to control each color component.

Output of Mandelbrot generator program , with relative size calculation

170
A Bearing E-Book

Modifying the explode limit

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.

If we up it from 10000 to 150000, we get the image shown in .

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.

Mandelbrot with explode limit at 150.000

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.

Messing with limit test

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.

Remember how we checked for explosion:

double magnitude = a*a + b*b // Hints to how large Z is


if( magnitude > limit ) // If we hit the limit
{...}

What happens if we change the magnitude calculation?

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

We run our modified program, and get this:

Mandelbrot with bad magnitued estimate

That is certainly interesting! We wingclipped the magnitude estimate, but the


Mandelbrot set itself seems to remain intact. Let us mess with the size estimate
even further:

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’.

Messing with the equations

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.

Our original fractal calculations looked like this:

double zxnew = a * a – b*b + ca


double zynew = 2 * a * b + cb

There is nothing stopping us from messing with these equations. I figured it


would be interesting to see how they would behave if we added the element of
trigonometric functions. After playing around with them for a while, I came up
with this modification:

double mnew = 0.44 * Math.Sin(-1.5 * cb * a)


double nnew = 0.44 * Math.Cos(1.5 * ca * b)
double zxnew = a * a - b * b + ca * mnew
double zynew = 2 * a * b + cb * nnew

I introduced a couple of temporary variables to take care of the trigonometric


calculations. The original equations were mostly untouched. I simply multiplied
the components of ‘C’ with the new values.

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.

Mandelbrot with trigonemtric calculations added

Do note that there is no math involved in coming up with these equations. I


simply played around with equations and rendered pictures to my heart’s
content. As I said before, this is the fun part. Playing around with knobs and
switches, just to see what happens.

Example output of our fractal image generator

175
PROGRAMMING FOR BEGINNERS, THE FUNDAMENTALS

5 .4. CON CL USIO N


Congratulations on reaching the end of this book!

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.

Example output of our fractal image generator

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”.

Cheers and good luck!

Bjørn

177

You might also like