Programming for beginners The fundamentals:Basic introduction to programming concepts with fractals [Draft ed.]

Introductory text to programming based around building a fractal generator. It introduces basic concepts such as variabl

223 98 12MB

English Pages [201] Year 2021

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
1. THE BACKGROUND 2
1.1. INTRODUCTION 2
1.1.1. Fast and furious 3
1.1.2. Writing code 3
1.1.3. Programming languages 4
1.1.4. Compiling code 6
1.2. MEMORY 8
1.2.1. SLOW MEMORY 8
1.2.2. FAST MEMORY 9
1.2.3. ACCESSING MEMORY 10
1.2.4. SUMMARY 12
2. BUILDING BLOCKS 14
2.1. COMMENTS 15
2.2. THE DATA TYPE 16
2.2.1. Integers (int) 17
2.2.2. The decimal (double) 17
2.2.3. The Boolean (bool) 18
2.2.4. The object 18
2.2.5. The string (string) 18
2.2.6. The nothing value 19
2.2.7. The symbols 20
2.3. THE VARIABLE 21
2.3.1. Assigning a value 22
2.3.2. The math operators 23
2.3.3. Casting: Forcing a datatype 28
2.4. COLLECTIONS 33
2.4.2. Introducing List 34
2.4.3. Invoking List 35
2.4.4. Sneak peak at functions 38
2.4.5. Accessing collection data 40
2.4.6. Multi-dimensional lists 43
2.4.7. The array datatype 45
2.5. SUMMARY 47
3. BETTER CODE 50
3.1. CODE COMPLEXITY 50
3.2. COMMENTS, PART DEUX 51
3.3. VARIABLE NAMING 54
3.4. INTERMEDIARY VARIABLES 55
3.5. THE FUNCTION 57
3.5.1. Function arguments 58
3.5.2. Returning values 60
3.5.3. Splitting up code 61
3.5.4. The black box 70
3.6. SUMMARY 71
4. WORKING WITH DATA 74
4.1. MAKING CHOICES 74
4.1.1. The condition 74
4.1.2. The if-else construct 75
4.2. REPEATING CODE 78
4.2.1. Introducing the loop 78
4.2.2. The while-loop 79
4.2.3. The for-loop 82
4.2.4. Looping through collections 85
4.2.5. The foreach loop 94
4.3. REUSING CODE 97
4.3.1. Functions 97
4.3.2. Libraries 99
4.3.3. Language Framework 101
4.4. SUMMARY 102
4.4.1. Summarizing the building blocks 102
4.4.2. Things we have not covered 104
5. BUILDING CODE 110
5.1. THE CANVAS 110
5.1.1. The Pixel 110
5.1.2. The Pixel Color 112
5.1.3. The Screen Buffer 114
5.2. CREATING IMAGES 116
5.2.1. Filling the screen 117
5.2.2. Generating pictures 121
5.3. THE MANDELBROT FRACTAL 130
5.3.1. The base formula 130
5.3.2. Partial 2-Color Mandelbrot 135
5.3.3. The full 2-Color Mandelbrot 143
5.3.4. Fractal, V3: monochromatic 160
5.3.5. Fractal, V3: full color 165
5.3.6. Some more examples 168
5.4. CONCLUSION 176
5.4.1. Onwards to part 2 177
Recommend Papers

Programming for beginners The fundamentals:Basic introduction to programming concepts with fractals [Draft ed.]

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

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 ....................................................................................................................................... 35 Figure 2-24 List containers ..................................................................................................................................................................... 36 Figure 2-25 Managing items with List ......................................................................................................................................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 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 and executing code.

, but in the context of writing

 

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. Non-traditional computing devices When writing this book, my focus was on 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



Languages where we tell the computer

it should do things. 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 in fast memory.

Permanent storage fallback

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 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 more than suffice for our purposes.

. It will

 

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 to deal with the details on how to store data.

The variable

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 double Radius double Pi Pi = 3.1415926535 Radius = 3.0 Circumference = 2*Pi*Radius

// // // // // //

Declare decimal number variable Declare decimal number variable Declare decimal number variable Stores the value 3.1415… in Pi Stores the value 3.0 in 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

The modulus 4 % 5

// Returns 0

returns ‘4’: // 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

255%256 = 255

255/256

0

255

256%256 = 0

256/256

1

0

257%256 = 1

257/256 = (1+256)/256

1

1

254

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 int int x = y = sum

sum x y 3 5 = x+y

// // // // //

Declare integer variable Declare integer variable Declare integer variable Stores the integer value 3 in x Stores the integer value 5 in 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 int sum int x string y x = 3 y = “Person” product = x + y

// // // // // //

variable?

Declare integer variable Declare integer variable Declare string variable Store the integer value 3 in x Store the string value “Person” in 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 double x int y x = 3.0 y = 5 product = x * y

// // // // // //

Declare decimal number variable Declare decimal number variable Declare integer number variable Store decimal value 3.0 in x Store integer value 5 in 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 double x int y x = 3.6 y = 5 product = x * y

// // // // // //

Declare integer number variable Declare decimal number variable Declare integer number variable Store decimal value 3.6 in x Store integer value 5 in 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 int Item1 int Item2 int Item3 int Item4 int Item5

integer number variables, and = 10 // Declare variable, and = 100 // Declare variable, = 1000 // Declare variable, = 10000 // Declare variable, = 100000 // Declare variable,

assign values assign 10 and assign 100 and assign 1000 and assign 10000 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 sum sum sum sum

sum = = sum = sum = sum = sum = sum

0 +Item1 +Item2 +Item3 +Item4 +Item5

// // // // // //

Declare sum variable and set to Add value of Item1 variable to sum Add value of Item2 variable to sum Add value of Item3 variable to sum Add value of Item4 variable to sum 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

Collection of integer values

List

Collection of decimal values

List

Collection of text data

List

Collection of Boolean values

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  

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 to manage its content.

List containers

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 manager manager = new List()

// Declare variable that uses List // Create object and store in manager

//ADD SOME DATA manager.Add(10) manager.Add(100) manager.Add(1000) manager.Add(10000) manager.Add(100000)

// // // // //

Add Add Add Add Add

the the the the the

number number number number number

10 to the list 100 to the list 1000 to the list 10000 to the list 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 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 object and store it the ‘manager’ variable: manager = new List()

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

 

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 do it for us.

object to

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 belong to some object.

. Functions can exist individually or they may

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) manager.Add(100)

// Add the number 10 to the list // 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) manager.Add(100) manager.Add(1000) manager.Add(10000) manager.Add(100000)

// // // // //

Add Add Add Add Add

the the the the the

number number number number number

10 to the list 100 to the list 1000 to the list 10000 to the list 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 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 mydata mydata = new List()

// Declare a list variable // 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 int sum = 0 sum = sum + sum = sum + sum = sum + sum = sum + sum = sum +

THE SUM OF ALL NUMBERS IN LIST mydata mydata mydata mydata mydata

[0] [1] [2] [3] [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 we no longer want to keep repeating the code.

The looping construct

We can rewrite the code as follows:

// DECLARE LIST VARIABLE List mydata = new List();

// 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 multidimensional 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 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 line = screen[y] line[x] = 0

// Makes reference to current line // 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” s[1] = “two” s[2] = “three”

// Store the string “one” in the 1st position // Store the string “two” in the 2nd position // 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

new string [3]

keyword, just as we did for

// 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 mydata = new List(); // 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 mydata = new List(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 double py1=2.0

// X coordinate // Y coordinate

// CONTROL POINT P2 double px2=20.0 double py2=3.0

// X coordinate // 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 ) A = a*(x2 - x1)*(x2-x1)/2

// Slope between P1 and P2 // 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; // 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 // On the line P1->P2 double Right_X = 15.8 // … ditto // AREA OF RIGHT ANGLED TRIANGLE // Slope P1 and P2 Slope = (Point2_Y-Point1_Y) / (Point2_X- Point1_X) Area = Slope*(Right_X-Left_)*(Right_Y-Left_Y)/2



a → Slope



A → Area



px1 → Point1_X



py1 → Point1_Y



px2 → Point2_X



py2 → Point2_Y

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 double RateY = Point2_Y- Point1_Y Slope = RateY / RateX

// Intermediary variable // Intermediary variable

// 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. In the example, we said it should return a , so ‘pi must be a

The ‘getPi’ function

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.

Function inputs

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.

 

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 decisions. The computer bases such decisions on the output of tests that return ‘true’ or ‘false’. I have listed the usual suspects in the table to the right. The left column describes the condition, while the right column shows how we express the condition in code. It is relatively straightforward. The condition on the first line tests for equality. The remaining three tests for a variety of inequalities.

Condition

In code

Is X equal to Y?

X == Y

Is X not equal to Y?

X != Y

Is X less than Y?

XY

Common conditions

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. The only condition that returns ‘true’ is the test for equality. This makes sense since ‘X’ and ‘Y’ hold the same value and therefore must be equal. Note how we write the test for equality using two equal signs: X == Y

Condition in code

X=0 Y=0

X == Y

True

X != Y

False

XY

False

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

XY

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:

A



Input is negative : condition is true



Input is positive or zero : condition is false 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 the function when the input is ‘5’.

. I have illustrated the flow of code for

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 ) The curly brackets group code just like for the function. Here we use them to group code that should run in either case of the condition.

{ return "yes" } else { return "no" }

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’ run through the same code multiple times, we refer to it as

. When we .

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 looping condition is true.

-statement keep the loop going while the

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 numbers = new List(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


0 ; q= q-1) { sum = sum + 1}

// q = 5,4,3,2,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 numbers = new List(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 listX = new List(new int[]{10,20,30,40,50} List listY = new List(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 listX = new List(new int[]{10,20,30,40,50} List listY = new List(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 names) { // LOOPING PARAMETERS int maxIndex = names.Count -1 //Index of last list-item

}

// LOOP THROUGH ITEMS for(int idx=0; idx 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 see what happens if we use screen coordinates as input for ‘C’ directly.

The screen space

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:

[ , 1,

] = [0,0] 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 ensure the endpoints match?

Relative traversal in ‘x’

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 int maxLoopCount = 256 double limit = 4.0 explodedColor = (30,30,255) settledColor = (0,0,0) //INITIALIZATION double double a = 0.0; double b = 0.0 double double double double

ratio_x = (b2 ratio_y = (a2 Ca = xstart + Cb = ystart +

x y

// // // // //

The color that will be returned Prevents staying in a loop forever The explode limit Light blue for values that explode Black color for values that settle

// Initializing components of Z b1) / width; a1) / height; * dx; * dy;

//CALCULATE VALUE double exploded = false; for(int i=0;i limit ) { exploded = true; break;}

// Measure for size of Z // Check if we hit the limit // 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

Δ =



=

−0=

Δy =



=

−0=

Replacing the screen deltas in our ratio formulas:

154

Δ Δ

=

Δ Δ

=

Δ Δ

= =

and

:

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

// Don't care about this for now

double magnitude = a*a + b*b if( magnitude > limit ) { exploded = true; break;}

// Magnitude of Z // If we hit the limit // Exploded, no need to continue.

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 forloop 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 double limit = 4.0 explodedColor = (30,30,255) settledColor = (0,0,0) //INITIALIZATION double a = 0.0; double double ratio_x = (X2 double ratio_y = (Y2 double Ca = xstart + x double Cb = ystart + y

// // // //

Prevents staying in a loop forever The explode limit Light blue for values that explode Black color for values that settle

b = 0.0 // Initializing components of Z X1) / screenWidth; Y1) / screenHeight; * dx; * dy;

//CALCULATE VALUE double exploded = false; int i; for(i=0;i limit ) { exploded = true; break;} } // DEFINE COLOR int R = i % 255; int G = i % 255; int B = i % 255; // RETURN COLOR return (R,G,B)); }

162

// // // // // //

Mandelbrot formula for a Mandelbrot formula for b Storing results back in a and b Measure for size of Z If we hit the limit value exploded, exit loop.

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 limit ) {...}

// Hints to how large Z is // 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 double double double

mnew = 0.44 nnew = 0.44 zxnew = a * zynew = 2 *

* * a a

Math.Sin(-1.5 * cb * a) Math.Cos(1.5 * ca * b) - b * b + ca * mnew * 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