File Under: Programming

Get Started With Programming

Ah, the joys of computer science. The late nights in the lab, the screaming, the crashes, the frustration, the endless days filled with angst as you try to remember why you got into this in the first place. All the grim stories you’ve heard are probably true, but so is this:Programming can be fun. Honest. Although computer science takes a lot of work and isn’t always a picnic, you can do some pretty extraordinary things with patience, the right frame of mind, and the necessary skills.

In order to acquire these skills, you must first learn some fundamental principles of computer science. Even though I will refer to JavaScript in the following examples, these principles can be applied to almost any language.


Contents

  1. Plan Ahead
  2. Variables:The Tupperware of Programming
  3. Scope of variables
  4. Learn About Conditionals or Else
  5. Getting Loopy
  6. What’s Your Function?
  7. Hints, Tips, and Tricks

Plan Ahead

When programming, it’s always a good idea to think of the program you want to create in terms of its solution. In order to do this, you must have a pretty solid understanding of the programming language that you’ll be working in and what you can do with it. Then you should sort out what exactly you’re trying to accomplish. What do you want your program to do? What problem is it solving? Next, divide the program into its various components. Then decide how those components will fit together to execute the program. Once you have all this sorted out, you can write each part of the program and put them together. Some of you eager beavers might want to start coding right away, but this can result in a messy program and lot of frustration for you down the road. If you don’t plan ahead, you won’t have a clear idea of what exactly you need to do to complete the program, and this can lead to a lot of mistakes. Establishing this type of process from the get-go is important because it makes it easier when you need to tackle more complex problems.

In addition to your overall approach, there are also a number of common concepts and commands that are used in every programming language, and mastering them is your first step. Let’s start with variables.

Variables:The Tupperware of Programming

No matter what language you’re working with, you’ll always use variables. Variables are like saved documents on your computer, each one storing information. When you name a variable you are actually declaring or defining it. The values stored in them can then be applied to functions (I’ll get to them later on).

In JavaScript, for example, variables can hold letters, numbers, and Boolean (true or false) values. If you want to access the information that a variable has stored in it, all you have to do is call the variable’s name. The process of naming a variable is unique to the programming language, but a few universal rules hold true. First, never give a variable the same name as a function; this can cause confusion. You can easily lose track of which is doing what. Second, make sure the names are descriptive. Stay away from abstract names so that when you or someone else goes back over the code, the purpose of the variable isn’t misunderstood.

You may have to define variables before defining the function that you call them in, depending on the language you’re using. In JavaScript, it’s always good practice to go ahead and define them beforehand to prevent having to root through a bunch of code to see what isn’t defined. They can be defined between the head tags or in the body.

Scope of variables

The scope of a variable refers to when and where a variable can be used, and they fall into two groups:local and global. Local variables are used most often in user-defined functions. If you try to call a local variable outside of its specific function, you will either get an error or the computer will evaluate the global variable instead (if the local variable has the same name as a global variable). The scope of a global variable is anywhere at any time. They exist outside of any functions regardless of whether they are called in one. A great example of these two types of variables is the
var
command used in JavaScript. You can create new variables with
var
. If you had a function named “Squiggly” and you used
var
to define the variable “Gobbledygook” within it, Gobbledygook would be a local variable, and would only be relevant inside Squiggly. Now, if you used
var
to define a variable called “Gibberish,”, just by itself with no association to a function, it would be a global variable. It’s not specific to one function but rather can be applied to any function at any time. An important thing to note is that global variables take precedence over local variables. So, if you call Gobbledygook within Squiggly, but there is also a global variable with the same name being applied to the function, the value of the global variable will be evaluated instead. Take a look here for details about this.

Learn About Conditionals or Else

If and if-then statements are commonly used conditionals in most programming languages. They check a condition and then take the appropriate action based on whether the condition is true or false. The basic structure of an if-then statement is:


 if (condition)



 {

 (action);

 }



 else



 {

 (else-action);

 }

Conditionals always start with the word if. If the condition is true, then the action within the body is applied and the appropriate results are produced. It’s possible for more than one action to be applied. If the condition is false, then else-action, also in the body, is applied and produces the appropriate return value. If you’re thirsty for more about the if and if-then structure in JavaScript, take a peek here.

The if statement only evaluates whether a function is true, and then proceeds to the next condition or line of code. The nice thing about using an if-else instead is that you have more control over the flow of the program. In addition, the else allows you to create command blocks (grouped commands) when the condition is false. This eliminates the work of writing several if statements to create a command block since they can all be combined and listed inside the else statement.

Predicates, or conditional operators as they’re called in JavaScript, are functions that return true or false values. They are frequently used in conditionals and can evaluate to one or two different values depending on the condition. Sometimes it’s easier to use a conditional operator than an if-then statement. Other times, they are used in conjunction with the if-then statements to produce the desired results. It all depends on the situation. You can usually identify them by the question mark that they end with. The structure for conditional operators is as follows:

 (condition) ? val1 :val2

Let’s say you wanted to create a function called printName that checked to see if the variable name is equal to “Deeter” and then returned something accordingly. If name is not equal to “Deeter” then the function would return something else. Here’s what it would look like:

 function printName(name) {



   alert((name == "Deeter")?"The monkey likes Deeter":"Who invited you to this party?");



 }



Now let’s take this all a step further with loops.

Getting Loopy

Looping is often used for actions like counting through a list and applying a certain function to each element in that list, or testing for a condition and repeating the process until the condition is false. It essentially allows a program to repeat pieces of the code. For example, a loop could be used to repeat a sequence of actions on each number between 1 and 8, or it could continue to collect information from a user until it’s indicated that the user is done.

The two main kinds of loops are conditionals (like the while loop in JavaScript) and iterated (the for and for in loops in JavaScript). You’ll usually encounter iterated loops, so I’ll focus on them. As I stated earlier, they are mainly used for counting purposes. For in is for more specific applications. It sifts through the properties of an object, which is useful when you don’t know the number of properties. Here’s the basic structure for a loop:

 for (initial value; test; increment)



 {



 do this stuff;



 }

Here’s a loop as it might be used in a function:




 for (i=0; i < thePasswords.length; i=i+1) {



   if (enteredPassword == thePasswords[i]) passwordMatches = true;



 }



 return passwordMatches;

Let’s break down the loop into three parts so it’s easier to understand. The first part of the for loop (i=0) sets its initial value. In this case, the initial value is 0. The second part, i < thepasswords.length, is evaluated until the return value is false. The third part says what to do to i each time the loop runs. When part two is not true, the looping will stop. The function will return false if enteredPassword doesn’t match any of thePasswords[i]. The if statement just says if your password matches i, then change the value of passwordMatches to true, which in turn makes the getPassword function true.

Here are some additional examples of loops. Now let’s put it all together with functions.


What’s Your Function?

Any JavaScript, C++, or Perl program is built with functions. Functions are expressions that execute an operation, allowing a programmer to create several pieces of code and bunch them together to perform a particular task. Functions accept information in the form of arguments (the values that are passed through the function) and evaluate the arguments to provide results. It’s important to prevent mix-ups by differentiating between arguments and parameters. These terms are often used interchangeably, which has always been especially confusing for me.

So, to make things clearer, when I say arguments I’ll be referring to functions. Likewise, when I say parameters, I’ll be referring to programs. Arguments are created whenever a function is defined. They are basically placeholders for the values that will be passed through the function. When an argument is passed through the function, it is evaluated and then applied to the function, which gives you a return value (the results). Arguments exist only during the life a function and change every time it’s called again because the values passed through them also change. The parts of a function are the function name, the argument(s), and the body. It looks something like this:

 function printName(argument)



 {



 body (all the cool code)



 }

The function name is printName and it takes in one argument. The stuff between the two curly brackets is the body and that’s where all the code goes.

There are two types of functions, built-in and user-defined. Built-in functions are the functions that already exist within the language. An example of this in JavaScript would be alert () or document.write(). User-defined functions are functions that the programmer creates. They are defined by assigning a name to the function and executed by calling that name again. The exact process of defining them varies from language to language. In JavaScript, you begin with function. Let’s look at a function that combines everything we have learned so far. Basically, when you enter the page, you type in a password and get a response according to whether or not the password is correct. The code would look like this:


 function getPassword () {



   thePasswords = new Array('foo','bar','bobo');



   var passwordMatches = false;



   var enteredPassword = prompt ("Enter your password:");



   for (i=0; i < thePasswords.length; i=i+1) {



     if (enteredPassword == thePasswords[i]) passwordMatches = true;



   }



   return passwordMatches;



 }



 var theVerdict = getPassword();



 if(theVerdict == true) {



   alert("Right-O!")



 } else {



   alert("How much schooling did you say you had?");



 }

As soon as you type in a password it becomes the value of the variable enteredPassword. If you type in a password – “bobo” for example – the function sifts through the array ( thePasswords) and compares each of the elements to the password you typed in. If it finds a match, the value of the variable passwordMatches changes to true, which also makes the function getPassword true, so you would then get a pleasant little message. If you type in a password like “spivey,” the function would be false because it doesn’t match an element in the array, so the value of passwordMatches (which is initially false) would not change.

In the loop in this function, the initial value of the variable i is 0. Each time the loop moves to a different element in the array, it adds one to the value of i. This is due to the i=i+1 piece of the loop. The position of each new element is one more than the last. If i=2 or thePasswords[2], then it would compare your password to “bobo” in the array list because that is the second position in the list (the third counting from 0).

Basically, thePasswords[2] is equal to “bobo.” If there was another element in the list after “bobo,” it would be referred to as thePasswords[3], since it would be the fourth position in the array. So, if i=0 and the corresponding element in the array does not match your password, it will continue to sift through the rest of the list and compare. As long as i < thePasswords.length is true, the loop will continue to add one to i and compare until the expression returns false (when i is greater than or equal to thepassword.length). If i < thePasswords.length is false, the function will return whatever value passwordMatches is set to – which could be either true or false. If passwordMatches is false then you’ll receive a not-so-pleasant message.

Hints, Tips, and Tricks

There are a few final things to consider when writing programs.

  • You may have noticed that the example codes here have a fair amount of spacing between the commands. This spacing isn’t essential, but in my opinion, it makes the code much easier to read and understand.
  • If you’re having trouble working through the code, and you’re not sure what you need to complete the program, try writing pseudo code, which is a mixture of English and the programming language. It’s very helpful to write out the steps you need to create a program, and sometimes it’s easier to articulate them in English rather than in some abstract programming language.
  • It’s also important to debug your program as you work on it. Don’t wait until the whole program is finished and then check to see if it works. Check each part as you go and make sure each one works properly before moving on to the next piece. This will save you a lot of time and unnecessary stress. Check out Advanced JavaScript Tutorial to learn about the process of debugging. And remember, you are going to make mistakes, and that’s OK. Professional programmers spend half of their time debugging; it’s part of the learning process.
  • Last but not least, have fun! Experiment, get frustrated, and then experiment some more. No pain, no gain.