Beginning Programming All-In-One Desk Reference For Dummies®
Published by
Wiley Publishing, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Library of Congress Control Number: 2008927908
ISBN: 978-0-470-10854-3
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
I started off as a writer and wound up becoming a computer programmer. Then I wound up circling around again to become a writer about computers. I’ve spent most of my life writing about and programming a variety of personal computers ranging from an ancient PC running MS-DOS 1.25 to Windows XP PC to the latest Macintosh computer running Mac OS X Leopard. My only preference for any computer is to use one that works.
I first learned about programming from my high school’s ancient teletype terminal that connected to a mainframe computer through a 300 baud acoustic modem that often disconnected me in the middle of my BASIC programming sessions. At the time, I didn’t know much about programming. I just taught myself BASIC from a book and illegally gained access to the teletype terminal by using somebody else’s password. Later in the year, I actually signed up for a computer class and finally gained legitimate access to the teletype terminal to do everything I had been doing illegally long before.
The first time I wrote a BASIC program on my own, it was a game that simulated flying a nuclear-armed bomber through a variety of anti-aircraft defenses including surface-to-air missiles and jet fighters trying to shoot you down. When this program worked for the first time, I felt like Dr. Frankenstein watching his creation twitch and come to life. To this day, I still experience that same feeling of exhilaration in creating something from an idea and turning it into an actual working program. Only other programmers can understand this strange sense of power and elation that comes from a working program, and it’s this same sense of wonder and exploration that I hope you’ll experience as you use this book to explore the world of programming on your own computer.
I may be considered a computer veteran after all these years, but that doesn’t mean that I can’t still experience that same feeling of satisfaction in typing that final command and watching an entire program work exactly as I wanted. Although I’ve written plenty of other books both on computers (Microsoft Office 2007 For Dummies) and far away from computers altogether (Breaking Into Acting For Dummies), I find that programming still fascinates me to this day.
As an author, I hope to help you discover your own path to learning programming, and as a programmer, I hope to provide an overview of computer programming in general. You may not become an expert programmer after reading this book, but if you come away with a greater appreciation for programming, then I’ll know I’ll have fulfilled my duty as both an author and programmer for this.
This book is dedicated to anyone who wants to learn how to program a computer. Computer programming can be one of the most creative ways to express your ideas so if you have your heart set on writing programs for fun or profit, you’ve just joined a select group of fellow renegades, entrepreneurs, and hobbyists who find programming an enjoyable intellectual exercise. When lost in the world of programming, you can often elevate your spirit to lofty heights of pleasure and wind up crashing right back down to Earth again when a single syntax error causes your program to crash an entire computer. Welcome to the wonderful world of programming. You deserve to achieve whatever your mind can envision and your programming skills can create.
This is the part of the book that most people skip over since it usually lists a bunch of names that most people have never heard before, so before you can skip over this page, I’d like to thank you for buying (or at least reading) this book. If you’re interested in learning to program a computer, you’ve already separated yourself from the masses who are ecstatic when they can just get their computer to work in the first place. As a programmer, you have the power to control how people may use computers in the future, and this power can give you the chance to help others or make someone completely helpless in their agony when trying to use a computer, so use your programming skills wisely.
On another note, this book owes part of its existence to Bill Gladstone and Margot Hutchison at Waterside Productions and another part of its existence to Katie Feltman at Wiley Publishing for turning this project into reality. Some other people who helped shape this project include Pat O’Brien and Vince McCune.
I also want to acknowledge all the stand-up comedians I’ve worked with over the years including Darrell Joyce (http://darrelljoyce.com), Leo “the Man, the Myth, the Legend” Fontaine, Chris Clobber, Bob Zany (www.bobzany.com), Russ Rivas (http://russrivas.com), Don Learned, Dante, and Dobie “The Uranus King” Maxwell. Another round of thanks goes to Steve Schirripa (who appeared in HBO’s hit show “The Sopranos”) for giving me my break in performing at the Riviera Hotel and Casino in Las Vegas, one of the few old-time casinos that hasn’t been blown up to make way for yet another luxury hotel and casino targeting rich people who want to lose their money faster.
Additional acknowledgements also go to my fellow radio co-hosts: Rick Gene, Drizz, Justin Davis, and Dane Henderson, who shared the airwaves with me during our year at 103.7 FreeFM in San Diego. Having our own radio show gave us all an excuse to go places and do things that we wouldn’t normally get to do such as visiting a UFO cult that built a landing strip for a flying saucer, exploring a museum that promotes creationism, and visiting Comic-Con where people dress up as their favorite comic book super heroes. (I tried to give ten bucks to anyone who would let me pour gasoline on them and light a match so they could attend Comic-Con dressed up as the Human Torch, but nobody was willing to take me up on that offer.)
I’d also like to acknowledge Cassandra (my wife) and Jordan (my son) for putting up with my long hours and my insistence that everyone dump their Windows XP PCs right away (an easy decision since they never worked right anyway) and migrate completely to the Macintosh. Final thanks go to Bo, Scraps, and Nuit (my cats) along with a final farewell to Tasha, who was a special breed called a Korat. R.I.P.
We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/.
Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and Media Development
Project Editor: Pat O’Brien
Acquisition Editor: Katie Feltman
Copy Editor: Jen Riggs
Technical Editor: Vince McCune
Editorial Manager: Kevin Kirschner
Media Project Supervisor: Laura Moss-Hollister
Media Development Specialist: Angela Denny
Editorial Assistant: Amanda Foxworth
Sr. Editorial Assistant: Cherie Case
Cartoons: Rich Tennant (www.the5thwave.com)
Composition Services
Project Coordinator: Patrick Redmond
Layout and Graphics: Claudia Bell, Reuben W. Davis, Melissa K. Jester
Proofreaders: Laura Albert, John Greenough, Jessica Kramer, Christine Sabooni
Indexer: Ty Koontz
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Joyce Pepple, Acquisitions Director
Composition Services
Gerry Fahey, Vice President of Production Services
Debbie Stailey, Director of Composition Services
Title
Introduction
Who Should Buy This Book
How This Book Is Organized
How to Use This Book
Icons Used in This Book
Getting Started
Book I : Getting Started
Chapter 1: Getting Started Programming a Computer
How Computer Programming Works
The History of Computer Programming
Figuring Out Programming
Getting Started with Programming
Knowing Programming versus Knowing Programming Language
Chapter 2: Different Methods for Writing Programs
Spaghetti Programming without a Plan
Planning Ahead with Structured Programming
Making User Interfaces with Event-Driven Programming
Organizing a Program with Object-Oriented Programming
Designing Programs with Today’s Methodology
Chapter 3: Types of Programming Languages
Choosing Your First Language
Teaching Languages
“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
Creating a Help File
Installing a Program
Dissecting Programs with a Disassembler
Chapter 5: Managing Large Projects with Software Engineering
Software Engineering Methods
Automating Software Engineering with CASE
The Pros and Cons of Software Engineering
Book II : Programming Basics
Chapter 1: How Programs Work
Using Keywords as Building Blocks
Organizing a Program
Dividing a Program into Subprograms
Dividing a Program into Objects
Creating a User Interface
Chapter 2: Variables, Data Types, and Constants
Declaring Variables
Using Different Data Types
Storing Data in a Variable
Retrieving Data from a Variable
Using Constant Values
Defining the Scope of a Variable
Chapter 3: Manipulating Data
Storing Data with the Assignment Operator
Using Math to Manipulate Numbers
Manipulating Strings
Finding Strings with Regular Expressions
Using Comparison Operators
Using Boolean Operators
Converting Data Types
Chapter 4: Making Decisions by Branching
Picking One Choice with the IF-THEN Statement
Picking Two Choices with the IF-THEN-ELSE Statement
Picking Three or More Choices with the IF-THEN-ELSEIF Statement
Playing with Multiple Boolean Operators
Making Multiple Choices with the SELECT CASE statement
Chapter 5: Repeating Commands by Looping
Looping a Fixed Number of Times with the FOR-NEXT Loop
Looping Zero or More Times with the WHILE Loop
Looping at Least Once with the DO Loop
Playing with Nested Loops
Prematurely Exiting from a Loop
Checking Your Loops
Chapter 6: Breaking a Large Program into Subprograms
Creating and Using Subprograms
Passing Parameters
Repeating a Subprogram with Recursion
Chapter 7: Breaking a Large Program into Objects
How Object-Oriented Programming Works
Encapsulation Isolates Data and Subprograms
Sharing Code with Inheritance
Polymorphism: Modifying Code without Changing Its Name
Design Patterns
Object-Oriented Languages
Real-Life Programming Examples
Chapter 8: Reading and Saving Files
Storing Data in Text Files
Storing Fixed Size Data in Random-Access Files
Storing Varying Size Data in Untyped Files
Using Database Files
Chapter 9: Documenting Your Program
Adding Comments to Source Code
Writing Software Documentation
Chapter 10: Principles of User Interface Design
The Evolution of User Interfaces
Elements of a User Interface
Designing a User Interface
Book III : Data Structures
Chapter 1: Structures and Arrays
Using Structures
Using an Array
Working with Resizable Arrays
Working with Multi-Dimensional Arrays
Using Structures with Arrays
Drawbacks of Arrays
Chapter 2: Sets and Linked Lists
Using Sets
Using Linked Lists
Drawbacks of Sets and Linked Lists
Chapter 3: Collections and Dictionaries
Using a Collection
Using Dictionaries
Understanding Hash Tables
Chapter 4: Stacks, Queues, and Deques
Using a Stack
Using Queues
Using Deques
Chapter 5: Graphs and Trees
Understanding Graphs
Creating Trees
Taking Action on Trees
Book IV : Algorithms
Chapter 1: Sorting Algorithms
Using Bubble Sort
Using Selection Sort
Using Insertion Sort
Using Shell Sort
Using Heap Sort
Using Merge Sort
Using Quick Sort
Comparing Sorting Algorithms
Chapter 2: Searching Algorithms
Sequential Search
Using Indexes
Adversarial Search
Chapter 3: String Searching
Sequential Text Search
Searching with Regular Expressions
Searching Phonetically
Chapter 4: Data Compression Algorithms
Lossless Data Compression Algorithms
Lossy Data Compression
Chapter 5: Encryption Algorithms
The Basics of Encryption
Symmetric/Asymmetric Encryption Algorithms
Cracking Encryption
Book V : Web Programming
Chapter 1: HyperText Markup Language
The Structure of an HTML Document
Adding Graphics
Defining the Background
Creating Hyperlinks
Making Tables
Chapter 2: CSS
The Structure of a Stylesheet
Creating Style Classes
Separating Styles in Files
Cascading Stylesheets
Chapter 3: JavaScript
The Structure of a JavaScript Program
Creating Comments
Declaring Variables
Using Operators
Branching Statements
Looping Statements
Creating Functions
Using Arrays
Designing User Interfaces
Chapter 4: PHP
The Structure of a PHP Program
Creating Comments
Declaring Variables
Using Operators
Branching Statements
Looping Statements
Creating Functions
Using Arrays
Creating Objects
Chapter 5: Ruby
The Structure of a Ruby Program
Creating Comments
Declaring Variables
Using Operators
Branching Statements
Looping Statements
Creating Functions
Using Data Structures
Creating Objects
Book VI : Programming Language Syntax
Chapter 1: C and C++
The Structure of a C/C++ Program
Creating Comments
Declaring Variables
Using Operators
Branching Statements
Looping Statements
Creating Functions
Data Structures
Using Objects
Chapter 2: Java and C#
The Structure of a Java/C# Program
Creating Comments
Declaring Variables
Using Operators
Branching Statements
Looping Statements
Creating Functions
Data Structures
Using Objects
Chapter 3: Perl and Python
The Structure of a Perl/Python Program
Creating Comments
Defining Variables
Using Operators
Branching Statements
Looping Statements
Creating Functions
Perl Data Structures
Python Data Structures
Using Objects
Chapter 4: Pascal and Delphi
The Structure of a Pascal Program
Creating Comments
Declaring Variables
Declaring Constants
Using Operators
Branching Statements
Looping Statements
Creating Subprograms and Functions
Data Structures
Creating Objects
Chapter 5: Visual Basic and REALbasic
The Structure of a BASIC Program
Creating Comments
Declaring Variables
Declaring Constants
Using Operators
Branching Statements
Looping Statements
Creating Subprograms and Functions
Data Structures
Creating Objects
Book VII : Applications
Chapter 1: Database Management
The Basics of Databases
Manipulating Data
Database Programming
Chapter 2: Bioinformatics
The Basics of Bioinformatics
Searching Databases
Bioinformatics Programming
Chapter 3: Computer Security
Stopping Malware
Stopping Hackers
Secure Computing
Chapter 4: Artificial Intelligence
Problem Solving
Machine Learning
Applications in Artificial Intelligence
Chapter 5: The Future of Computer Programming
Picking a Programming Language
Picking an Operating System
Cross-Platform Programming
The Programming Language of the Future
: Further Reading