Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Beginning Programming All-in-One For Dummies
Beginning Programming All-in-One For Dummies
Beginning Programming All-in-One For Dummies
Ebook1,402 pages11 hours

Beginning Programming All-in-One For Dummies

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Let there be code!

Beginning Programming All-in-One For Dummies offers one guide packed with 7 books to teach you programming across multiple languages. Coding can seem complex and convoluted, but Dummies makes it simple and easy to understand. You’ll learn all about the principles of programming, algorithms, data structures, debugging programs, unique applications of programming and more while learning about some of the most popular programming languages used today. Move confidently forward in your computer science coursework or straight into the workforce. You’ll come away with a rock-solid foundation in the programming basics, using data, coding for the web, and building killer apps.

  • Learn the basics of coding, including writing and compiling code, using algorithms, and data structures
  • Get comfortable with the syntax of several different programming languages
  • Wrap your mind around interesting programming opportunities such as conducting biological experiments within a computer or programming a video game engine
  • Develop cross-platform applications for desktop and mobile devices

This essential guide takes the complexity and convolution out of programming for beginners and arms you with the knowledge you need to follow where the code takes you.

LanguageEnglish
PublisherWiley
Release dateMay 13, 2022
ISBN9781119884422
Beginning Programming All-in-One For Dummies

Read more from Wallace Wang

Related to Beginning Programming All-in-One For Dummies

Related ebooks

Programming For You

View More

Reviews for Beginning Programming All-in-One For Dummies

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Beginning Programming All-in-One For Dummies - Wallace Wang

    Introduction

    If you enjoy using a computer, you may have even more fun learning to control a computer by writing your own programs. To learn how to program a computer, you need to:

    Understand that computer programming is nothing more than problem solving. Before you even think about writing a program, you need to know what problem you want your program to solve and how it will solve it.

    Learn the basic ideas behind computer programming that work with all programming languages on any computer. Although programming a Windows computer is different from programming a Mac, a smartphone, a smart watch, or a super computer, the general principles remain the same. By learning what these common programming principles are and why they exist, you can learn different ways to tell a computer what to do, step-by-step.

    Learn a specific programming language. A programming language represents just one way to express your ideas in a language that the computer can understand. By combining your knowledge of a programming language with programming principles and the type of problem you want the computer to solve, you can create your own computer programs for fun or profit.

    About This Book

    If you have any interest in programming but don’t know where to start, this book can give you a nudge in the right direction. You won’t learn how to write programs in a specific programming language, but you’ll learn the basics of computer programming so you’ll have no trouble learning more on your own.

    If you already know something about programming, this book can still help you learn more by introducing you to the variety of programming languages available and make it easy for you to pick up different programming languages quickly. The more you understand the advantages and disadvantages of different programming languages, the better you’ll be able to choose the language that’s best suited for a particular task.

    Whether you’re a novice or an intermediate programmer, you’ll find this book can work as a tutorial to teach you more and as a reference to help refresh your memory on programming topics you may not normally use every day. This book won’t turn you into an expert overnight, but it will open the doors to more information about programming than you may have ever known even existed.

    This book is a reference — you don’t need to read the chapters in order from front cover to back and you don’t have to commit anything you read here to memory. Also, sidebars (text in gray boxes) and anything marked with the Technical Stuff icon are skippable.

    Finally, within this book, you may note that some web addresses break across two lines of text. If you’re reading this book in print and want to visit one of these web pages, simply key in the web address exactly as it’s noted in the text, pretending as though the line break doesn’t exist. If you’re reading this as an e-book, you’ve got it easy — just click the web address to be taken directly to the web page.

    Foolish Assumptions

    When writing this book, I made two assumptions about you, the reader:

    You may have no experience in computer programming or a limited amount of experience, but you’re eager to learn.

    You have a computer (whether it’s the latest model on the market or simply an older model that still works). Ideally, your computer can connect to the Internet.

    That’s it! As long as you have a computer and the desire to learn, you have everything you need to learn computer programming.

    Icons Used in This Book

    Icons highlight important or useful information that you may want to know about. Here’s a guide to the icons:

    Tip The Tip icon highlights information that can save you time or make it easier for you to do something.

    Remember The Remember icon emphasizes information that’s so important you should commit it to memory.

    Warning Look out! The Warning icon highlights something dangerous that you need to avoid before making an irreversible mistake that could make you curse your computer forever.

    Technicalstuff The Technical Stuff icon highlights interesting technical information that you can safely ignore, but which may provide additional background about programming a computer.

    Beyond the Book

    In addition to what you’re reading right now, this product also comes with a free access-anywhere Cheat Sheet that summarizes different types of programming principles, common ways to store and organize data, and lists of suggested software to use. To get this Cheat Sheet, simply go to www.dummies.com and type Beginning Programming All-in-One For Dummies Cheat Sheet in the Search box.

    Where to Go from Here

    You can use this book as a tutorial or a reference. Although you can just flip through this book to find the information you need, programming novices should start with Book 1 before tackling any other books. After you understand the basics of programming from Book 1, you can freely jump around to read only the information that interests you.

    Programming is more than learning a particular programming language or even knowing how to program a particular type of computer. Basically, programming is about tackling difficult problems and breaking them down into smaller problems until you ultimately solve one much bigger problem. If you like the idea of solving problems, this may be the perfect book to introduce you to the wonderful world of computer programming!

    Book 1

    Getting Started with Programming

    Contents at a Glance

    Chapter 1: Getting Started Programming a Computer

    How Computer Programming Works

    The History of Computer Programming

    Figuring Out Programming

    Chapter 2: Different Methods for Writing Programs

    Spaghetti Programming

    Structured Programming

    Event-Driven Programming

    Object-Oriented Programming

    Using Protocol-Oriented Programming

    Design Patterns

    Chapter 3: Types of Programming Languages

    Your First Language

    Curly-Bracket Languages

    Artificial Intelligence Languages

    Scripting Languages

    Database Programming Languages

    Comparing Programming Languages

    Chapter 4: Programming Tools

    Choosing a Compiler

    Finding an Interpreter

    Compiling to a Virtual Machine

    Writing a Program with an Editor

    Fixing a Program with a Debugger

    Saving Time with Third-Party Components

    Optimizing a Program with a Profiler

    Managing Source Code

    Creating a Help File

    Installing a Program

    Dissecting Programs with a Disassembler

    Chapter 1

    Getting Started Programming a Computer

    IN THIS CHAPTER

    Bullet Understanding how computer programming works

    Bullet Diving into the history of computer programming

    Bullet Discovering programming

    Believe it or not, if you can write a recipe on an index card, you can program a computer! At the simplest level, computer programming is nothing more than writing instructions for a computer to follow, step-by-step. The most important part of programming isn’t knowing how to write a program or how to use a particular programming language, but knowing what to create in the first place.

    Some of the most popular and useful computer programs were created by people who didn’t have any formal training in math or computer science. Dan Bricklin invented the spreadsheet while studying for his MBA at Harvard. Scott Cook, who worked in marketing and product development at Procter & Gamble, created the popular money-management program Quicken after hearing his wife complain about the tedium of paying bills. Nineteen-year-old Shawn Fanning created Napster, the first peer-to-peer file-sharing network, after hearing a friend complain about the difficulty of finding his favorite songs on the Internet. Game developer Dona Bailey wanted to create a video game that would appeal to both men and women; as the only woman working at Atari’s coin-op division, she created the video game Centipede, which became Atari’s second best-selling coin-op game.

    The point is that anyone can figure out how to program a computer. What’s more important than knowing how to program a computer is knowing what to do with your programming skills. As Albert Einstein said, Imagination is more important than knowledge. After you have an idea for a program, you can use programming to turn your idea into reality.

    How Computer Programming Works

    Computer programming is nothing more than problem solving. Every program is designed to solve a specific problem. The more universal the problem (calculating formulas in a spreadsheet, managing your money, searching for music files over the Internet, or keeping people amused playing a game creating virtual buildings), the more useful and popular the program will be.

    Identifying the problem

    Before you even touch a computer, identify the specific problem you want the computer to solve. For example, spreadsheets eliminate the tedium of writing and calculating formulas manually. Word processors make editing and formatting text fast and easy. Even video games solve the problem of challenging people with puzzles, obstacles, and battles.

    Although the most popular programs solve universal problems, literally thousands of programs are designed to solve specific problems in niche markets, such as hotel reservation software, construction billing and invoice management programs, and dental office management programs. If you can identify a problem that a computer can solve or simplify, you have an idea for a computer program.

    Remember You must know exactly what you want your program to do before you start designing and writing it. One of the most common reasons programs fail is because the program doesn’t solve the right problem that people really need.

    THE FBI’S $170 MILLION FLOP

    The Federal Bureau of Investigation (FBI) had a problem. It had so much information, stored on paper, scattered among so many agents around the country that finding and using this information was nearly impossible. One agent might have vital information that could help a second agent crack a case, but unless those two agents knew what each other had, that information might as well never have existed in the first place.

    So, the FBI had a bright idea: Create a computer program that would allow agents to store and share information through the computer. Several years and $170 million later, the FBI had its program, dubbed Virtual Case File, which consisted of more than 700,000 lines of error-prone commands that never even worked. Rather than try to salvage the project, the FBI decided it was easier just to cancel the whole thing and basically flush 170 million taxpayer dollars down the drain.

    What went wrong? Although many factors contributed to the project’s failure, one reason stands out in particular: According to an audit of the program conducted by the U.S. Department of Justice, a prime cause for failure was poorly defined and slowly evolving design requirements. In other words, the FBI never knew exactly what it wanted the program to do.

    How can you aim at a target if you don’t know what it is? You can’t. Or you can try, just as long as you spend $170 million to discover that if you don’t know what you want, you’re probably never going to get it.

    Defining the steps

    After you know what you want your program to do, you need to define all the steps that tell the computer how to solve that particular problem. The exact steps that define how the program should work is called an algorithm. An algorithm simply defines one of many possible ways to solve a problem.

    Remember There’s no single best algorithm for writing a program. The same program can be written in a million different ways, so the best way to write a program is any way that creates a useful, working, and reliable program as quickly as possible. Anything else is irrelevant.

    Knowing what you want the computer to do is the first step. The second step is telling the computer how to do it, which is what makes programming so difficult. The more you want the computer to do, the more instructions you need to give the computer.

    Think of a computer program as a recipe. It’s easy to write a recipe for making spaghetti. Just boil water, throw in the noodles until they’re soft, drain, and serve. Now consider a recipe for making butternut squash and potato pie with tomato, mint, and sheep’s milk cheese from Crete. Not as simple as boiling water to make spaghetti, is it?

    The same principle holds true for computer programming. The simpler the task, the simpler the program. The harder the task, the bigger and more complicated the program. If you just want a program that displays today’s date on the screen, you won’t need to write many instructions. If you want to write a program that simulates flying a space shuttle in orbit around the Earth, you’ll need to write a lot more instructions.

    The more instructions you need to write, the longer it takes and the more likely you’ll make a mistake somewhere along the way.

    Remember Ultimately, programming boils down to two tasks:

    Identifying exactly what you want the computer to do

    Writing step-by-step instructions that tell the computer how to do what you want

    The History of Computer Programming

    Although computer programming may seem like a recent invention, the idea behind writing instructions for a machine to follow has been around for over a century. One of the earliest designs for a programmable machine (in other words, a computer) came from a man named Charles Babbage way back in 1834.

    That was the year Charles Babbage proposed building a mechanical, steam-driven machine dubbed the Analytical Engine. Unlike the simple calculating machines of that time that could perform only a single function, Charles Babbage’s Analytical Engine could perform a variety of tasks, depending on the instructions fed into the machine through a series of punched cards. By changing the number and type of instructions (punch cards) fed into the machine, anyone could reprogram the Analytical Engine to make it solve different problems.

    The idea of a programmable machine caught the attention of Ada Lovelace, a mathematician and daughter of the poet Lord Byron. Sensing the potential of a programmable machine, Ada wrote a program to make the Analytical Engine calculate and print a sequence of numbers known as the Bernoulli numbers.

    Technicalstuff Because of her work with the Analytical Engine, Ada Lovelace is considered to be the world’s first computer programmer. In her honor, the Department of Defense named the Ada programming language after Ada Lovelace. Nvidia named a family of graphics cards after Ada Lovelace as well.

    Although Charles Babbage never finished building his Analytical Engine, his steam-driven mechanical machine bears a striking similarity to today’s computers. To make the Analytical Engine solve a different problem, you just had to feed it different instructions. To make a modern computer solve a different problem, you just have to run a different program.

    Over a century later, the first true computer appeared in 1943 when the U.S. Army funded a computer to calculate artillery trajectories. This computer, dubbed ENIAC (short for Electronic Numerical Integrator and Computer), consisted of vacuum tubes, switches, and cables. To give ENIAC instructions, you had to physically flip its different switches and rearrange its cables.

    Technicalstuff The first ENIAC programmers were all women.

    Physically rearranging cables and switches to reprogram a computer worked, but it was tedious and clumsy. Instead of having to physically rearrange the computer’s wiring, computer scientists decided it would be easier if they could leave the computer physically the same but just rearrange the type of instructions given to it. By giving the computer different instructions, they could make the computer behave in different ways.

    In the old days, computers filled entire rooms and cost millions of dollars. Today, computers have shrunk so far in size that they’re essentially nothing more than a little silicon wafer, about the size of a coin.

    A processor is essentially an entire computer. To tell the processor what to do, you have to give it instructions written in machine language (a language that the processor can understand).

    Technicalstuff To make faster computers, engineers combine multiple processors (called cores) together and make them work as a team. So, instead of having a single processor in your computer, the latest computers have multiple processors or cores working together.

    Talking to a processor in machine language

    To understand how machine language works, you have to understand how processors work. Basically, a processor consists of nothing more than millions of tiny switches that can turn on or off. By turning certain switches on or off, you can make the processor do something useful.

    Instead of physically turning switches on or off, machine language lets you turn a processor’s switches on or off by using two numbers: 1 (one) and 0 (zero), where the number 1 means turn a switch on and the number 0 means turn a switch off. So a typical machine language instruction might look like this:

    1011 0000 0110 0001

    If the preceding instruction doesn’t make any sense, don’t worry. The point is that machine language is just a way to tell a processor what to do.

    Technicalstuff Using 1s and 0s is binary arithmetic. Because binary arithmetic can be so hard to read, programmers also represent binary numbers in hexadecimal. Where binary arithmetic uses only 2 numbers, hexadecimal uses 16 numbers and letters (0–9 and A–F). So, the binary number 1011 0000 0110 0001 could be represented as the hexadecimal number B061.

    Machine language is considered the native language of CPUs, but almost no one writes a program in machine language because it’s so tedious and confusing. Mistype a single 1 or 0, and you can accidentally give the wrong instruction to the CPU. Because writing instructions in machine language can be so difficult and error-prone, computer scientists have created a somewhat simpler language: assembly language.

    Using assembly language as a shortcut to machine language

    The whole purpose of assembly language is to make programming easier than machine language. Basically, one assembly language command can replace a dozen or more machine language commands. So, instead of requiring you to write ten machine language commands (and risk making a mistake in all ten of those commands), assembly language lets you write one command that does the work of ten (or more) machine language commands.

    Not only does this reduce the chance of mistakes, but it also makes writing a program in assembly language much faster and easier. Best of all, assembly language commands represent simple mnemonics such as MOV (move) or JMP (jump). These mnemonic commands make assembly language much easier to understand than a string of binary commands (1s and 0s).

    Remember The goal of every programming language is to make programming simpler and easier. Unfortunately, because no one can define exactly what simpler and easier really mean, computer scientists keep creating new and improved programming languages that promise to make programming simpler and easier, at least until someone else invents another new and improved programming language.

    To understand how assembly language works, you must first understand how processors store and manipulate data. The processor is the brain of the computer that does all the work. By itself, the processor is fairly useless.

    Think of Einstein's brain floating in a jar of formaldehyde. It may be one of the smartest brains in the world, but if it can’t communicate with the outside world, it’s completely useless as anything other than a very unusual paperweight. Like Einstein’s brain in a jar, your computer’s processor is useful only if it can communicate with the outside world. The processor communicates with the other parts of the computer through a series of wires called a bus.

    When a processor needs to work with data, it retrieves it from another part of the computer (such as the hard disk or memory) and temporarily stores that data in a storage area called a register, as shown in Figure 1-1.

    Schematic illustration of a processor uses its registers to temporarily store data.

    FIGURE 1-1: A processor uses its registers to temporarily store data.

    The processor then edits the data in its registers and sends the changed data back to another part of the computer, such as the memory or hard disk.

    So, computer programming progressed from physically rearranging wires and switches (with ENIAC), to flipping switches using 1s and 0s (with machine language), to telling the computer which data to store in which registers and how to manipulate that data (with assembly language).

    A typical assembly language command might look like this:

    mov al, 061h

    This command tells the processor to move (mov) the hexadecimal number 061h into the specific register named al. Other assembly language commands might tell the processor to add (add) or subtract (sub) a value from the number stored in a specific register.

    When you use assembly language, you have to tell the processor what data to store in which registers, how to manipulate the data in the registers, and when to remove data out of the registers.

    Sound tedious? It is. Although assembly language is far easier to understand and write than machine language, it's still too complicated to use for creating really big computer programs, like word processors or video games.

    Technicalstuff In the old days, most programs were written in assembly language, but as programs grew larger and more complicated, assembly language proved too cumbersome to write, edit, and modify.

    The biggest problem with assembly language is that you need to manipulate the processor’s registers just to do the simplest tasks. If you wanted to add two numbers together, you’d have to tell the processor to store a number in a register, add a second number to the number in the register, and then yank the result out of the register.

    Forcing people to know how to manipulate the processor’s registers before they can program a computer is like forcing people to know how their carburetor works before they can drive a car. Ideally, you don’t want to tell the processor how to manipulate data in its registers; you just want the processor to add two numbers without worrying about specific registers. So, to make computer programming even easier, computer scientists have hidden the technical details of manipulating registers by creating high-level languages.

    Technicalstuff Every processor understands only its own particular assembly language. So an Intel processor won’t understand the assembly language of an Advanced RISC Machine (ARM) processor and vice versa. However, some companies make processors that work identically to other processors. For example, a company called Advanced Micro Devices (AMD) makes processors that work just like Intel processors, so an assembly language program written for an Intel processor also works on an AMD processor.

    Hiding the details of a computer with a high-level language

    The whole purpose of high-level languages is to make programming more intuitive. So, rather than tell the computer to store the number 2 in register al, add the number 3 to the number stored in register al, and then yank out the result from register al, high-level languages let you tell the computer what to do and not worry about how the computer does it. So, a typical high-level language command might look like this:

    Total = 2 + 3

    As you can see, high-level languages are much easier to read and understand, even if you know nothing about programming. Where assembly language forces you to tell the processor what to do and how to do it, high-level languages just let you tell the processor what to do.

    Technicalstuff Early popular high-level languages include Fortran (formerly FORTRAN, short for FORmula TRANslator), BASIC (short for Beginner's All-purpose Symbolic Instruction Code), COBOL (short for COmmon Business Oriented Language), and Pascal (named after the French philosopher Blaise Pascal).

    Besides making programming more intuitive, high-level languages also make programming easier because a single high-level language command can do the work of a dozen (or more) assembly language commands.

    A thousand lines of assembly language commands might do nothing more than multiply two numbers together. A thousand lines of high-level language commands might create a video game, a music player, or a stock market analysis program. By using high-level languages, programmers can spend more time being productive and less time worrying about the technical details of the computer.

    Combining the best of both worlds with the C programming language

    High-level languages isolate you from the technical details of programming, but by isolating you from these details, high-level languages also limit what you can do. So, as a compromise between assembly language (which can manipulate the processor) and high-level languages (which isolate you from the details of manipulating the processor), computer scientists created an intermediate language dubbed C.

    The idea behind the C programming language is to give programmers the ability to manipulate the processor directly like assembly language, but also give them the chance to ignore these technical details, if they want, like a high-level language.

    As a result, a C program doesn’t look as cryptic as assembly language, but it also isn’t as easy to read as a high-level language, as the following C program demonstrates:

    #include

    int main(void)

    {

      printf(Hello World!\n);

      exit(0);

    }

    Remember Just by looking at this C program, you can probably figure out that it prints Hello World! on the screen. However, you may see a bunch of cryptic curly brackets, back slashes, and other odd symbols and characters that may make no sense whatsoever. Don’t worry. Just notice how confusing C programs can look while at the same time being somewhat understandable.

    Technicalstuff Because C lets you directly control the processor like assembly language does, but still write programs that look somewhat understandable and easy to read and write, many operating systems — such as Linux, macOS, and Microsoft Windows — are written all or partially in C.

    Weighing the pros and cons of programming languages

    The whole purpose of machine language, assembly language, high-level language, and the C language is to give you different ways to give instructions to the processor (computer). Ultimately, it doesn’t matter which type of programming language you use because it’s possible to write the exact same program in machine language, assembly language, a high-level language (like BASIC or Fortran), and C.

    The only difference is that writing a program in machine language takes a really long time and is very difficult to write, fix, and understand. A similar program written in assembly language is smaller and simpler than an equivalent machine language program.

    Writing the same program in the C language makes the program even smaller and much easier to write and understand. If you use a high-level language, the program would most likely require writing less code and be easiest to understand out of them all.

    So, given these advantages of C or high-level languages, why would anyone ever use machine language or assembly language? The answer is simple: speed and efficiency.

    If you want to write the fastest program possible that uses the least amount of memory, use machine language because machine language is the native language of all computers. Unfortunately, machine language is so hard to understand, write, and modify that writing anything but small programs in machine language is nearly impossible.

    Instead of using machine language, most programmers use assembly language when they need speed and efficiency. Assembly language creates small and fast programs, but they’ll never be as small or fast as machine language programs. That’s because processors understand only machine language, so when you write an assembly language program, you have to translate that assembly language program into machine language.

    Translating assembly language into machine language by hand would be slow and error-prone, so computer scientists have created special programs that can do this automatically. These programs are assemblers.

    An assembler takes an assembly language program and converts it into machine language, but this conversion process isn’t perfect. That’s why assembly language tends to create bigger and slower programs than equivalent handcrafted machine language programs. However, assembly language programs are much easier to write and modify later than machine language programs are, so assembly language is used much more often than machine language.

    High-level languages are much easier to write and understand than machine language or assembly language. The problem is that processors don’t understand high-level languages either, so you have to translate a high-level language program into equivalent machine language commands.

    Doing this by hand is nearly impossible, so computer scientists have created special programs — compilers — to do this for them. A compiler takes a program written in a high-level language and translates it into equivalent commands written in machine language.

    This translation process isn’t perfect, which is why programs written in high-level languages tend to be much bigger and slower than equivalent programs written in machine language or assembly language. So, when programmers want to create large, complicated programs that still run fast and take up as little space as possible, they tend to rely on the C programming language. That’s why so many programs are written in C — C creates programs nearly as small and fast as assembly language programs, while also being nearly as easy to write and understand as high-level languages. (Note the emphasis on the word nearly.)

    As a general rule, if you want to make programming easy where speed and efficiency aren’t that crucial, use a high-level programming language. If you want to make a small and fast program and don’t care how inconvenient it may be to write it, use machine language or assembly language.

    What if you want to write a big and fast program (like an operating system or word processor) and also make it convenient for you to write? You’d use the C programming language.

    Technicalstuff Although C is a fast and powerful language, it’s not the safest. C lets you access all parts of a computer, which means if you’re not careful, your programs can corrupt the computer’s memory (known as memory leaks) and cause all types of unintended havoc. For that reason, computer scientists have used C as a reference to create safer versions of the language. Many of today’s popular programming languages (such as C#, Java, Objective-C, Python, and Swift) have been directly or indirectly inspired by C. Because C uses curly brackets to define the beginning and end of code blocks, C-based languages are often called curly-bracket languages.

    Remember Ultimately, no one cares what language you use as long as your program works. A program that works is far better than a small, fast, and efficient program that doesn’t work. Think of a programming language as a tool. A good programmer can use any tool well, but a bad programmer can screw up using the best tool in the world. The programmer’s skill always determines the quality of any program; the type of programming language used is always secondary. So the goal isn’t to become a C programmer or a Fortran programmer. The goal is to become a good programmer, regardless of the language you ultimately use.

    Figuring Out Programming

    After you understand that programming is nothing more than telling a computer how to solve a problem, you may wonder how you can get started figuring out programming on your own. If you want to figure out how to program a computer, this is what you need:

    Desire

    A computer

    An editor

    An assembler or compiler

    A lot of time on your hands

    Tip Find out more about programming tools, like an editor and a compiler, in Book 1, Chapter 4.

    Desire beats technical training every time

    Desire is probably the biggest factor in studying how to program a computer. Many people think that you need a college degree or a mathematical background to know computer programming. Although a college degree and a mathematical background can definitely help, they aren’t necessary. Saying you need to know math before figuring out computer programming is like saying you need a college degree in biology before you can reproduce.

    Some of the most influential and popular programs in the world were created by people who had no formal training in computer programming or computer science. (Conversely, some of the most intelligent PhD candidates in computer science have done nothing to make this world a better place using their programming skills.)

    So, if you have an idea for a program, you can create it. After you have the desire to understand computer programming, you have (almost) everything you need to program a computer.

    Picking a computer and an operating system

    If you want to know how to program a computer, you need a computer to practice on. You can actually discover programming on any computer, from a top-of-the-line machine to an obsolete relic (that was once a top-of-the-line machine) to a simple handheld computer. As long as you have a computer, you can figure out how to program it.

    Although it’s possible to figure out programming by using an ancient Commodore 64 or an antique Radio Shack TRS-80, it’s probably best to figure out programming on a computer that’s going to be around in the future. That way you can directly apply your programming skills to a computer used in the real world, which boils down to a computer that runs one of the following operating systems: Linux, macOS, or Windows.

    Technicalstuff Some websites let you practice writing and running code completely within a browser. This spares you the trouble of installing a compiler directly on your computer and lets anyone learn to program as long as they have a browser and access to the Internet.

    An operating system is a special program that makes all the hardware of your computer work together. The operating system tells the processor how to work with the hard disk, read keystrokes typed on a keyboard, and display information on the monitor. Without an operating system, your computer is nothing more than separate chunks of hardware that do absolutely nothing.

    Technicalstuff One of the most popular operating systems in the world is Unix, commonly run on big, expensive computers. Linux is based on Unix, so if you understand how to program a Linux computer, you can also program a Unix computer and vice versa.

    It’s still possible to write programs for obsolete computers like the Atari ST, PDP-11, or Commodore Amiga, but most people choose to write programs for one of the following operating systems:

    Linux: Linux is a free operating system for almost every computer (including PCs). Linux is becoming more popular with big companies (as opposed to individual users), so there’s a growing market for talented Linux programmers.

    macOS: macOS is the operating system that runs the Apple Mac computer. Although Macs aren’t as popular as Windows computers, macOS is still a large and lucrative market.

    Windows: Windows is the operating system that runs on most personal computers (PCs). Because so many people use Windows PCs at work and at home, the software market for Windows is huge and lucrative.

    If you want to prepare yourself for the future, it’s probably best to begin programming on any computer that runs Linux, macOS, or Windows.

    Technicalstuff With virtualization software such as VirtualBox (www.virtualbox.org), you can run different operating systems at the same time, such as running both Linux and Windows on a PC or running both Linux and macOS on a Mac. That way you can practice writing programs for different operating systems on a single computer.

    Most programmers use a desktop computer running Linux, macOS, or Windows to write software. With the growing popularity of mobile devices, wearable computers, and browser-based apps, there’s a huge market for writing apps for these devices as well:

    Android: Android is Google’s free operating system that runs on the majority of smartphones and some tablets.

    iOS and iPadOS: iOS and iPadOS are the operating systems that run on the iPhone and iPad, respectively. The iPhone is the most popular smartphone in the world, and the iPad is the dominant tablet in the world.

    watchOS: watchOS is the operating system that runs on the Apple Watch. The Apple Watch is one of the most popular wearable devices in the world.

    Wear OS: Wear OS is Google’s free operating system for smart watches. It’s a version of Android that runs on smart watches to compete against the Apple Watch.

    To write apps for mobile and wearable operating systems, you normally need to use a computer that runs Linux, macOS, or Windows. However, you can use some of the more powerful tablets to write apps for smartphones and tablets, too.

    Writing programs with an editor

    After you have a computer that runs Linux, macOS, or Windows (or a powerful tablet), the next step is to get an editor. An editor acts like a simple word processor that lets you type, change, and save program commands in a file.

    Remember In the world of computer programming, a single program command is a line of code. Most programs consist of thousands of lines of code, although a large program (like Microsoft Windows) consists of millions of lines of code. When you write a program, you don’t tell people, I’m writing a program. You say, I’m writing code. It sounds cooler — at least to other programmers.

    In the old days, you had to buy a programming editor. Today, you can often get a powerful, professional editor for free. Some editors are bundled with an integrated development environment (IDE), which combines the features of an editor with a compiler (to convert your code to assembly language or machine language) and a debugger (to find and fix problems in your code).

    Some popular editors include the following:

    GNU Emacs (www.gnu.org/software/emacs): Editor only for Linux, macOS, and Windows

    Playgrounds (www.apple.com/swift/playgrounds): iPadOS and macOS

    Visual Studio (https://visualstudio.microsoft.com): macOS and Windows, with a limited version available for Linux

    Xcode (https://developer.apple.com/xcode): macOS only

    Unlike a word processor, which offers commands for formatting text to make it look pretty or appear in different colors, text editors are just designed for typing commands in a particular programming language, such as C++, Java, or Swift:

    The simplest editor just lets you type commands in a file.

    More sophisticated editors can help you write a program by

    Color-coding program commands (to help you identify them easily)

    Indenting your code automatically (to make it easier to read)

    Typing in commonly used commands for you

    Figure 1-2 shows a simple editor used to write a Swift program that creates a hypotrochoid art figure.

    Snapshot of an editor lets you write and edit the source code of a program.

    FIGURE 1-2: An editor lets you write and edit the source code of a program.

    Without an editor, you can’t write a program. With an editor, you can write a program. And with a really good editor, you can write a program quickly and easily.

    Remember Professional programmers often get passionate (to the point of fanaticism) about their favorite editors. The quickest way to get into an argument with programmers is to either insult their favorite programming language or insult their favorite editor. If you insult a programmer’s mother, the programmer will probably just shrug and not care one bit.

    Technicalstuff Program commands stored in one or more files are called the program’s source code. Think of a program’s source code as the recipe that makes the program work. If someone can steal or copy your source code, they’ve effectively stolen your program. That’s why companies like Microsoft jealously guard the source code to all their programs, such as Windows or Excel.

    Converting source code with an assembler or compiler

    An editor lets you type and save program commands (or source code) in a file. Unless you’ve written a program completely in machine language, your source code may as well have been written in Swahili because processors don’t understand any language other than machine language.

    So, to convert your source code into machine language commands, you have to use an assembler (if you wrote your program commands in assembly language) or a compiler (if you wrote your program commands in the C language or a high-level language like Java).

    After converting your source code into equivalent machine language commands, an assembler or compiler saves these machine language commands in a separate file, often called an executable file (or just an EXE file). When you buy a program, such as a video game or an antivirus program, you’re really buying an executable file. Without an assembler or a compiler, you can’t create your program.

    Compilers translate source code into machine language, which is the native language of a specific processor. But what if you want your program to run on different processors? To do this, you have to compile your program into machine language for each different processor. You wind up with one executable file for each processor, such as an executable file for an Intel processor and a separate executable file for an ARM processor.

    Technicalstuff Many Mac programs advertise themselves as a universal binary — which means the program actually consists of two executable files smashed into a single file:

    One executable file contains machine language code for the M-series processor (used in newer Mac computers)

    The second executable file contains machine language code for the Intel processor (used in old Mac computers)

    Most compilers work only on one specific operating system and processor. So, a Windows compiler may only create programs that run under the Windows operating system. Likewise, a Linux compiler may only create programs that run under the Linux operating system.

    If you write a program that runs under Windows, you can recompile it to run under Linux. Unfortunately, you may have to modify your program slightly (or a lot) to make it run under Linux.

    Remember Big companies, like Adobe and Microsoft, can afford to pay programmers to write and modify programs to run under different operating systems, such as macOS and Windows. Most smaller companies and individuals don’t have the time to rewrite a program to run under multiple operating systems. That’s why most small companies write programs for Windows — because it’s the largest market. If the program proves popular, they can later justify the time and expense to rewrite that program and compile it to run under macOS.

    Warning Choose your compiler carefully. If you use a compiler that can create only Windows programs, you may never be able to recompile that program to run on a different operating system, such as Linux or macOS. One reason Microsoft gives away its compilers for free is to trap people into writing programs that can run only under Windows. For example, if you write a program in C#, you may not be able to run that program on Linux or macOS without major modifications, which most people will probably never do.

    To make it easy to create programs for multiple operating systems, you can use a cross-platform compiler. This means you can write a program once and then choose to compile it for two or more operating systems such as macOS and Windows or Android and iOS. Cross-platform tools make it easy to write the same program for multiple operating systems, but you may need to write additional code to take advantage of the unique features of each operating system.

    Translating source code with an interpreter

    In the old days, compilers were notoriously slow. You could feed source code to a compiler and literally come back the next morning to see if the compiler was done. If you made a single mistake in your program, you had to correct it and recompile your program all over again — with another overnight wait to see if it even worked.

    Trying to write a program with such slow compilers proved maddening, so computer scientists created something faster called an interpreter. A computer interpreter is just like a foreign language interpreter who listens to each sentence you speak and then translates that sentence into another language. Type a program command into an interpreter, and the interpreter immediately translates that command into its equivalent machine language command. Type in another command, and the interpreter translates that second command right away.

    The problem with interpreters is that they only store the equivalent machine language commands in memory instead of in a separate file like a compiler does. If you want to sell or distribute your program, you have to give people your source code, along with an interpreter that can convert your source code into machine language commands. Because giving away your source code essentially means giving away your program, everyone who wants to sell their programs uses a compiler instead of an interpreter.

    Technicalstuff The original reason why computer scientists developed interpreters was because compilers were so slow. But after computer scientists started creating faster compilers, most people stopped using interpreters and just used compilers. Nowadays, computer scientists use interpreters for running certain types of programming languages known as scripting languages. (Find out more about scripting languages in Book 1, Chapter 3.)

    Combining a compiler with an interpreter to create p-code

    Creating separate executable files for each processor can get clumsy, and giving away your source code with an interpreter may be unreasonable. A third approach is to compile your program into an intermediate format called bytecode or pseudocode (often abbreviated as p-code). Unlike compiling source code directly into machine language, you compile your program into a p-code file instead.

    You can take this p-code file and copy it on any computer. To run a p-code file, you need a special p-code interpreter, or a virtual machine. The virtual machine acts like an interpreter and runs the instructions compiled into the p-code file.

    The advantage of p-code is that you can distribute a single p-code version of your program, which can run on multiple computers. But P-code has a couple disadvantages:

    P-code programs don’t run as fast as programs compiled into machine language.

    If a computer doesn’t have the right virtual machine installed, it can’t run your program.

    The most popular programming language that uses p-code is Java. After you write a Java program, you can compile it into a p-code file, which can run on any computer that has a copy of the Java virtual machine, such as Android, Linux, macOS, and Windows. Microsoft’s .NET framework is similar to p-code that (theoretically) lets you run a program on any computer that can run the complete .NET framework.

    Warning The theory behind p-code is that you write a program once, and you can run it anywhere. The reality is that every operating system has its quirks, so it’s more common to write a program and be forced to test it on multiple operating systems. More often than not, a p-code program runs perfectly fine on one operating system (like Windows) but suffers mysterious problems when running on another operating system (such as Linux). Languages, such as Java, are getting better at letting you run the same program on multiple operating systems without major modifications, but be careful because p-code doesn’t always work as well as you may think.

    Taking the time to understand

    Programming is a skill that anyone can acquire. Like any skill, the best way to understand is to take the time to experiment, make mistakes, and learn from your failures. Some programmers prefer to spend their time mastering a single programming language. Others prefer to master the intricacies of writing programs for a specific operating system, such as Windows. Still others spend their time discovering a variety of programming languages and writing programs for different operating systems.

    There is no right or wrong way to figure out programming. The only right way is the way that works for you. That’s why self-taught programmers can often write programs that are just as good as (or even better than) programs written by PhD computer scientists.

    Like any skill, the more time you spend programming a computer, the better you get. This book is designed to help you get started, but ultimately, it’s up to you to take what you know and start programming your own computer.

    Believe it or not, programming a computer is actually fairly straightforward. The hard part is trying to write a program that actually works.

    KNOWING HOW TO PROGRAM VERSUS KNOWING A PROGRAMMING LANGUAGE

    There’s a big difference between knowing how to program and knowing a specific programming language. This book describes how programming works, which means you’ll understand the principles behind programming no matter what programming language you decide to use.

    When you understand a specific programming language, you’ll figure out how to write a program using that language. Don’t confuse knowing how to program with knowing a programming language!

    When people learn to speak their native language, they often think their particular spoken language is the only way to talk. So, when they learn a foreign language, they try to speak the foreign language just like they speak their native language, but using different words. That’s why literal translations of foreign languages can sound so funny and awkward to a native speaker.

    That’s exactly the same problem with understanding programming. To understand programming, you have to use a specific programming language, but each programming language works a certain way. So, if you know how to write programs in the C programming language, you may mistakenly think that the way the C language works is the way computer programming also works, but that’s not true.

    Like human languages, programming languages differ wildly. Someone who knows how to write programs in the C language thinks differently about programming than someone who knows how to write programs in assembly language.

    To describe how programming works, this book uses a variety of examples from different programming languages. You don’t have to understand how each program example in this book works. Just understand that programming languages can look and solve identical problems in very different ways.

    First, try to understand general programming principles without worrying about the way a particular programming language works. Then try to understand how a particular programming language works. As long as you know how to keep these two topics separate, you can figure out how to program a computer without the distraction of knowing a particular programming language.

    Besides, programming languages rise and fall in popularity all the time, so if you know only one programming language, your skills may become obsolete within a few years.

    At one time, most programmers used assembly language. For programmers who wanted a simpler language, they used BASIC or Pascal. When BASIC and Pascal fell out of favor, programmers gravitated toward C. Because C was so dangerous to use, many people started using C++ and Java. Microsoft created its own version of C++ called C#. Apple initially adopted a language similar to C++ called Objective-C, but then it created its own language called Swift. After running into legal problems using Java, Google adopted Kotlin as the official language for writing Android apps.

    When learning any programming language, the only certainty is that new programming languages will appear all the time, so you should master the popular programming languages and keep learning the newer ones as well.

    Remember: Focus on understanding programming, and then worry about understanding a particular programming language. After you understand how programming works, you can adapt to the next popular programming language of tomorrow, whatever that may be.

    Chapter 2

    Different Methods for Writing Programs

    IN THIS CHAPTER

    Bullet Spaghetti programming without a plan

    Bullet Planning ahead with structured programming

    Bullet Making user interfaces with event-driven programming

    Bullet Organizing a program with object-oriented programming

    Bullet Using protocol-oriented programming

    Bullet Using design patterns

    The goal of computer science is to find the best ways to write a program. The reality of computer science is that nobody really knows what they’re doing, so they’re making up stuff as they go along and pretending there’s a scientific basis for everything they do. The fact that multimillion-dollar programming projects routinely fall behind schedule and sometimes never work at all pretty much shows that computer programming is still less a science than an art.

    Despite these problems, computer scientists are always searching for ways to make programming easier, faster, and more reliable by constantly developing

    Better tools

    Better programming languages

    Better techniques for writing programs

    Just as a carpenter doesn’t build a house with rusty saws and a broken hammer, computer scientists are always developing better tools to help them write, fix, and create programs. One of the first improvements computer scientists made was in developing faster compilers. Instead of waiting overnight to see if a program worked, programmers could use a fast compiler that could show them the results in seconds. Other tool improvements included editors that would show programmers the specific line where an error occurred and special programs (known as debuggers) for making sure that every part of a program worked correctly.

    Another way to improve programmer efficiency involves creating better programming languages. Assembly language was easier to write and modify than machine language, and high-level languages are easier to write and modify than assembly language.

    Computer scientists are constantly inventing new programming languages or improving existing ones. These improvements or new languages typically offer some feature that existing languages don’t offer or solve certain types of problems that existing languages do poorly. For example, the C++ language improves upon the C language, whereas the Java language improves upon the C++ language.

    Perhaps two of the biggest problems with programming involve writing a program from scratch and modifying an existing program. When you write a program from scratch, you want to write a working program quickly with as few problems as possible.

    That’s why programming languages include so many built-in commands. The idea is that the more built-in commands available, the fewer commands you’ll need to use to write a program and the shorter and easier your program will be to write in the first place.

    In addition, many programming languages include built-in error-checking features to keep you from writing a program that doesn’t work. With some languages, it’s possible to write commands that work perfectly but can also crash the computer if you give those commands the wrong type of data.

    Tip In Book 1, Chapter 3, you find out more about the features of different programming languages.

    More than half the battle of programming is writing a program that works. The second half is modifying that program later. When you need to modify an existing program, you must first understand how that existing program works and then you need to modify it without messing up the existing program commands.

    To help you understand how a program works, many programming languages let you divide a large program into separate parts. The theory is that if one part of a program isn’t working or needs to be modified, you can yank out part of the program, rewrite it, and then plug it back into the existing program, much like snapping LEGO building blocks together.

    Finally, the best tools and the latest programming languages won’t help you unless you know how to use them correctly. That’s why computer scientists are constantly developing new programming techniques that work no matter what tools or language you use.

    Tip In Book 1, Chapter 4, you find out more about the different programming tools computer scientists have created to make programming easier, faster, and more reliable.

    This chapter discusses programming techniques based on problems encountered by programmers working in the real world. Basically, computer scientists keep developing and refining programming techniques after they see what really works and what doesn’t.

    Spaghetti Programming

    In the early days of programming, most programs were fairly short and simple. A typical program may just calculate a mathematical equation, which to a computer, is just a little more challenging than adding two numbers together.

    To write such small, single-task programs, programmers would typically start typing commands in their favorite programming language with little planning, just to write a program quickly.

    Unfortunately, many programs aren’t just written once and then used forever. If a program isn’t working exactly right, or if the program needs to do something new that the original programmer didn’t include, you must take an existing program and modify it.

    Modifying an existing program sounds simple, but it’s not. First, you have to understand how the program works so you’ll know exactly how to modify that program. If you try modifying a program without understanding how it works, there’s a good chance you could wreck the program and keep it from working, much like ripping out cables from your car engine without knowing what you’re really doing.

    After you understand how a program works, the second step involves writing new commands into the existing program. Now, here’s where the problem occurs. Take an existing program and modify it once. Now take that same program and modify it again. Now take that same program and modify it 20 more times, and what do you get? Most likely, you’ll have a mishmash collection of code that works but isn’t organized logically, as shown in Figure 2-1.

    Schematic illustration of constantly modifying a program eventually creates an unorganized mess.

    FIGURE 2-1: Constantly modifying a program eventually creates an unorganized mess.

    Modifying a program several times by yourself may not be so bad because you probably remember what you changed and why. But what happens if seven other programmers modify the same program seven different times and then none of them is around to help you understand what changes they made? Yep, you’d wind up with a bigger mess than before.

    With constant modifications, a small, simple program can grow into a convoluted monstrosity that may work, but nobody quite understands how or why. Because the program consists of so many changes scattered throughout the code, trying to figure out how the program even works can get harder with each new modification.

    With a simple program, the computer follows each command from start to finish, so it’s easy to see how the program works. After a program gets modified multiple times, trying to follow the order of commands the computer follows can be like untangling spaghetti (hence, the term spaghetti programming).

    As programs kept getting bigger and more complicated, computer scientists realized that just letting programmers rush out to write or modify a program wasn’t going to work anymore. That’s when computer scientists created the first programming techniques to help programmers write programs that would be easy to understand and modify later.

    SPAGHETTI PROGRAMMING WITH THE GOTO COMMAND

    Although you can write spaghetti programs in any language, the BASIC programming language is most closely associated with spaghetti programming. Early versions of BASIC used a GOTO command, which essentially told the computer to

    Enjoying the preview?
    Page 1 of 1