Creating Variables

February 1st, 2008 yudi Posted in Variables and Constants No Comments »

A variable simply acts like a box that can hold data. Each variable can have a descriptive name so you can identify which variable to use when storing and retrieving data. Variables have the following two uses:

  •  Storing inputted data

  •  Storing calculations that use inputted data or previous calculations

When you store data in a variable, the computer handles the specific memory address to store your data; all you have to worry about is the name of the variable where you stored your data. When you want to retrieve the data again, you just refer to the data by its variable name, and the computer knows the exact memory address it needs to find your data.

In general, you create a variable in three steps:

  1. Give each variable a unique, descriptive name.

  2. Define what type of data each variable can hold.

  3. Assign data (numbers or letters) to each variable.

Variables can hold any type of data, such as numbers or text. However, a variable can store only one chunk of data at a time. The moment you stuff another chunk of data in a variable, the variable dumps the old data and cheerfully stores the new data. The contents of a variable may vary at any given time, hence the name variable.

AddThis Social Bookmark Button

Naming variables

February 1st, 2008 yudi Posted in Variables and Constants 1 Comment »

You can give variables any name you want, such as the name of your dog or variations of four-letter words. However, it’s a good idea to use descriptive names that help identify the type of data that the variable holds, such as FirstName or CustomerIDNumber.

Remember Each variable must have a unique name to keep your computer from getting confused. In some languages, the variable names LastName, lastname, and Lastname are considered identical. Other languages, such as C++, are case-sensitive. A case-sensitive language considers a variable called LastName to be completely different from another variable called lastName. Unless every letter in a variable name is identical (including upper- and lowercase letters), a case-sensitive language considers variables to be two completely different items.

Warning! When naming variables in a case-sensitive language like C++, a common error is to name a variable something like CustomerAge but try to store data in that variable as customerAge. (Note that the first letter is lowercase rather than uppercase.) When naming variables, be consistent. Some programmers always capitalize the first letter of a variable name (Customer), but others always type the first letter as lowercase (customer). Some programmers always capitalize the first letter of each word (MyStudentNumber), but others don’t (Mystudentnumber). Whatever you do, do it consistently to save yourself a lot of headaches trying to identify your variables later on.

In some programming languages, you can name your variables and stuff data in them at the same time, as in the following Liberty BASIC program that creates variables. One variable (Salary) stores data that represents a user’s salary, and the second variable (TaxOwed) stores a calculation.


Salary = 25000                                    ?1
TaxOwed = Salary * 0.95                           ?2
PRINT “This is how much tax you owe = $”; TaxOwed ?3
END                                               ?4

This is how the Liberty BASIC program works:

  • ?1 Tells the computer, “Create a variable named Salary and store the number 25000 in that variable.”

  • ?2 Tells the computer, “Create a variable called TaxOwed. Then multiply the number stored in the Salary variable by the number 0.95 and store the result of this calculation in TaxOwed variable.”

  • ?3 Prints This is how much tax you owe = $ followed by the number that the variable TaxOwed represents.

  • ?4 Tells the computer that the program has ended.

In most programming languages, you use the equal sign (=) to assign a value to a variable. However, in Revolution, you use the magic into command instead, as follows:


put 25000 into Salary                             ?1
put Salary * 0.95 into TaxOwed                    ?2
put “This is how much tax you owe = $” && TaxOwed
           into message                           ?3

This is how the Revolution program works:

  • ?1 Tells the computer, “Put the number 25000 into a variable named Salary.”

  • ?2 Tells the computer, “Multiply the number stored in the Salary variable by the number 0.95 and put the result of this calculation in a variable named TaxOwed.”

  • ?3 Tells the computer, “Take the text, This is how much tax you owe = $ and include the number stored inside the TaxOwed variable and put all of this text in the message box that appears on-screen.” (The && symbol tells the computer to “add” the number stored in the TaxOwed variable to the end of the This is how much tax you owe = $ line.)

AddThis Social Bookmark Button

Defining the data type of a variable

February 1st, 2008 yudi Posted in Variables and Constants No Comments »

Programming languages like Liberty BASIC and Revolution let you create a variable and stuff it with data right away. This makes programming easy because you can create variables whenever you need them. Unfortunately, it also encourages sloppy programming for two reasons:

  • You have to search your code, line by line, to find all the different variables your program creates and what type of data it stores in them.

  • You can easily store the wrong type of data in a variable by mistake.

Consider the following Liberty BASIC code. The code works but doesn’t make any logical sense because nobody can have 1.48 numbers of children.


Children = 1.48
MonthlyPayment = 350
PRINT “You owe = “; Children * MonthlyPayment
END

In this example, the Children variable should hold only whole numbers and not decimal numbers.

To avoid storing inappropriate data in a variable, many programming languages do something called type-checking. Type-checking forces you to define the type of data a variable can hold, and then it checks to make sure you don’t try to store the wrong type of data in that variable. In this way, type-checking acts like a filter that allows only valid data into the variable.

Technical Stuff Programming languages that force you to define the type of data a variable can hold are also known as type-safe languages.

Warning! If you don’t define what type of data a variable can hold, it’s possible to store the wrong type of data in a variable. If your program tries to work with the wrong type of data, it could crash or just mess up very badly.

In type-safe languages such as REALbasic and C++, you must define both the name of a variable and the type of data it can hold. Only after you have defined (or declared) both the variable name and its data type can you stuff data in that variable.

The three most common types of data that variables can hold are

  •  Whole numbers (such as 3, 45, or 102): Often referred to as integers.

  •  Decimal numbers (such as 34.04679, 3.1415, or 26.943): Often referred to as single or double to represent single-precision or double-precision numbers. Single- or double-precision refers to how many decimal places the computer uses to store a number. Double-precision numbers can store more decimal places than single-precision numbers.

  •  Text (such as “a”, “my cat”, “fat”, or “I like frogs”): Often referred to as strings.

Image from book

Technical StuffUnderstanding data types

The three most common data types are integers, decimal numbers, and strings. However, some programming languages offer other data types such as Boolean (which can only hold a True or False value), byte (which is a subset of an integer but can hold only values ranging from 0 to 255), and long (which can hold extremely large or small integer values).

The main reason for these other data types is to give programmers the freedom to choose the data type that most closely fits the acceptable range of values a program needs to store in a variable. For example, an integer variable type can hold both positive and negative numbers, but a byte data type can hold only values ranging from 0 to 255. So if you need to create a variable to hold someone’s age, you should declare your variable as a byte because a person’s age can never be negative nor higher than 255. Additional data types simply help you further restrict what types of values a variable can hold.

Image from book
 

The following REALbasic code example shows how to declare a variable named Children and define it to hold only whole numbers (also called integers).


Dim Children As Integer

Dissecting this REALbasic code reveals the following:

  1. The Dim command is short for dimension, which is just a fancy way of saying “I declare a variable

  2. Immediately following the Dim command is the name of the variable, which is Children. So the first two words in the REALbasic code tell the computer, “I declare a variable named Children.”

  3. The last two words, As Integer, define the data type as an integer. So the entire REALbasic code tells the computer, “I declare a variable named Children as an Integer data type.” At this point, the Children variable can hold only integers.

Declaring a variable named Children and defining it to hold only integer data in C++ might look like this:


int Children;

Dissecting the preceding C++ code reveals the following:

  1. The int command is short for integer and tells the computer, “I want to create a variable that can hold only integer values.”

  2. Children is the actual variable name, so the first two lines tell the computer, “I want to create a variable that can hold only integer values, and the name of the variable is Children.”

  3. The semicolon tells the computer, “That’s the end of my variable declaration.”

Remember C++ commands tend to be much shorter (and harder to read) than equivalent BASIC commands. C++ resembles shorthand whereas BASIC resembles actual words.

If you declare a variable to hold only integers, you can never accidentally store decimal numbers (3.1415) or text (twenty-five thousand) in the variable by mistake.

AddThis Social Bookmark Button

Assigning a value to a variable

February 1st, 2008 yudi Posted in Variables and Constants No Comments »

Variables are useless until you store data in them. When you store data in a variable, it’s called assigning a value to a variable.

Warning! As soon as you create a variable, it’s a good idea to assign an initial value to that variable, such as 0 or an empty string like “”. In some programming languages, declaring a variable automatically fills that variable with random data. If you forget to clear out a variable by storing an initial value and you then try to use that variable in a calculation, the random data automatically stored in a variable could crash your program.

The simplest way to assign a value to a variable is to use the equal sign. This method enables you to assign a number or string to a variable, as in the following Liberty BASIC example:

 


CEOSalary = 9000000
Message2Workers$ = “So I make more than I’m worth.”

In the first line, you assign the number 9000000 to a variable by the name of CEOSalary. In the second line, you assign the string So I make more than I’m worth. to the variable Message2Workers$.

Technical Stuff If you assign a string to a variable in Liberty BASIC, the variable name must include the dollar sign ($) at the end. If you assign a number to a variable, don’t include a dollar sign in the variable name. In other dialects of BASIC, such as REALbasic, you don’t have to use the dollar sign at the end of a variable that contains strings. Like spoken languages, programming languages consist of minor variations (dialects) that force you to do something that another version of that same language may ignore completely.

To use the preceding Liberty BASIC code in REALbasic, you first have to declare your two variables before assigning a value to them, as shown here:

 


Dim CEOSalary As Integer
Dim Message2Workers As String
CEOSalary = 9000000
Message2Workers = “So I make more than I’m worth.”

Similarly, you must declare your variables first in C++, as in this example:

 


#include <iostream.h>
#include <stdio.h>
using namespace std;
int main()
{
   int CEOSalary;
   string Message2Workers;
   CEOSalary = 9000000;
   Message2Workers = “So I make more than I’m worth.”;
   cout << “nPress ENTER to continue…” << endl;
   getchar();
   return 0;
}

Technical Stuff The C++ language doesn’t include a string data type, so you have to add the using namespace std; command near the top of your program. This provides commands that define a string data type that you can use in your C++ program.

Tip Using variables in C++ is usually a two-step process. First, you must declare a variable name and its data type. Second, you have to assign a value to the variable. To save time, C++ lets you declare a variable and assign a value to it all in a single line such as

 


int CEOSalary = 9000000;

This C++ code tells the computer, “Create a variable that can only hold integer values (int), name the variable CEOSalary, and store the number 9000000 in it.”

Remember In most programming languages, you assign a value to a variable by using the equal sign (=). However, in Revolution, you assign a value to a variable by using the into command, as shown here:

 


put 9000000 into CEOSalary
put “So I make more than I’m worth.” into Message2Workers
AddThis Social Bookmark Button

Using Constants

February 1st, 2008 yudi Posted in Variables and Constants No Comments »

Variables can change values while the program’s running; that’s why they’re called variables (because their values can vary). Sometimes, you may want to use a fixed value throughout your program. Look at the following program. Can you figure out what the number 0.1975 stands for?

 


Balance = 43090
OurProfit = Balance * 0.1975
Balance = Balance + OurProfit
PRINT “Pay this amount, or we’ll get you = “; Balance
PRINT “Today’s current loan sharking interest rate = “;
           .1975
END

A quick glance at the preceding program shows that the meaning of the number 0.1975 isn’t obvious. Because the meaning of numbers isn’t always clear without additional explanation, programmers use constants. A constant is nothing more than a descriptive name that represents a fixed value.

Remember Older versions of the BASIC programming language, such as Liberty BASIC, don’t support constants. Newer versions of BASIC (such as REALbasic) do support constants.

To see how constants can be helpful, look over the following REALbasic program:

 


Dim Balance, OurProfit As Single
Const InterestRate = 0.1975
Balance = 43090
OurProfit = Balance * InterestRate
Balance = Balance + OurProfit
MsgBox “Pay this amount = $” + str(Balance)

By reading this program, you can clearly see that the number 0.1975 represents an interest rate, which then makes the fourth line much easier to understand:

 


OurProfit = Balance * InterestRate

In this line, the value of the OurProfit variable is calculated by multiplying the variable Balance by the constant value of InterestRate.

By replacing a descriptive name (constant) to represent a fixed value, you can make the meaning of numbers easier to understand. Although the preceding REALbasic program is fairly small, imagine a program that consists of a million lines of code and uses the value of 0.1975 (as the interest rate) 20 times. What happens if you want to change the interest rate from 0.1975 to 0.2455? You have to change it all 20 times where it appears, which means you have to take the time to find it and change it all 20 times (while hoping that the value of 0.1975 isn’t also used somewhere else that you don’t know about).

Rather than go through this hassle, constants let you assign a fixed value to a descriptive name and then use that descriptive name throughout your program. If you need to change the value of that constant, you just need to change it once and its value automatically changes throughout the rest of your program.

  • Constants offer two key advantages:

  • Descriptive constant names make fixed values easier to understand.

  • Storing a value as a constant lets you update that value just once no matter how large your program is.

Technical Stuff To define a constant in the C++ programming language, you need to use the const keyword followed by the data type, the constant name, and the value to define the constant, as shown here:

 


const double interestrate = 0.1975;

This C++ code tells the computer, “Create a constant that can represent a double-precision number (decimal number), name the constant interestrate, and set the value of the constant to 0.1975.”

To define a constant in Revolution, you just have to use the constant keyword followed by the constant name and its value:

 


constant InterestRate = 0.1975
AddThis Social Bookmark Button

Commenting Your Code

February 1st, 2008 yudi Posted in Variables and Constants No Comments »

If you write a small program, anyone can readily understand how it works by following it line by line. But if you write a large program, understanding what the program does can prove difficult for others (and even for you) without spending a long time studying each line.

To make understanding (and ultimately maintaining) a program easier (because programmers are notoriously lazy), every programming language allows you to insert comments into your source code. Comments are often used to explain the following:

  • Image from book Who wrote the program (so you know who to blame)

  • Image from book The creation and last modification dates of the program

  • Image from book What the program does

  • Image from book How the program works

  • Image from book Where the program gets, saves, and outputs data

  • Image from book Any known problems with the program

Remember Every programming language provides different ways to create comments.

In Liberty BASIC, you can add comments in one of the following two ways:

  • Image from book By using the REM (short for remark) statement

  • Image from book By using an apostrophe ()

The following program shows how to use both the REM statement and the apostrophe to insert comments into a program. Although you can use both types of comments in a single program, you might want to use only one or the other for consistency’s sake.


 ‘ Created on March 29, 2007
‘ Written by John Doe
‘ This program displays a not-so-subtle
‘ message to potential copycats to
‘ come up with their own ideas rather
‘ than steal mine.
REM This program does nothing more than
REM print a message on-screen to
REM insult any potential authors browsing
REM through this book in hopes of stealing
REM ideas to use in a competing book.
NOTICE “Don’t steal ideas from this book!”
END ‘ This last line ends the program

Because comments are for the benefit of humans only, the computer looks at the preceding Liberty BASIC program and sees only this:


NOTICE “Don’t steal ideas from this book!”
END

Remember Comments exist solely for your benefit. The computer completely ignores any comments that you insert in a program. So make your comments useful but not too wordy; other wise, they become more of a nuisance than an aid.

In C++, you can use two slash characters to create comments such as


// This is a C++ comment

In REALbasic, you can use the REM keyword, an apostrophe (), or double slashes (//) to create a comment.

In Revolution, you can use the hash symbol (#) or two dashes () to create a comment such as


– This is a comment in Revolution
# This is a comment in Revolution too

Comments typically take up a single line, but if you want to create a comment that appears on several lines, you can type the comment character in front of every line. However, many programming languages such as C++ and Revolution (but not Liberty BASIC or REALbasic) offer the /* and */ symbols to identify the beginning and ending of your comments, as in this example:


/* Created on March 29, 2007
Written by John Doe
This program displays a not-so-subtle
message to potential copycats to
come up with their own ideas rather
than steal mine.
This program does nothing more than
print a message on-screen to
insult any potential authors browsing
through this book in hopes of stealing
ideas to use in a competing book. */

Tip Besides adding explanations to the source code of a program, programmers often use comments to temporarily ignore one or more lines of code to test certain parts of the code. Rather than delete an entire line, test to see whether the program works, and retype the deleted line, you can just comment out the line, as follows:


NOMAINWIN
‘ A = SQR((B * B) + (C + C))
END

If you run this program, Liberty BASIC sees only the following:


NOMAINWIN
END

To restore the commented line, just remove the apostrophe so that Liberty BASIC sees the program like this:


NOMAINWIN
A = SQR((B * B) + (C + C))
END
AddThis Social Bookmark Button




eXTReMe Tracker