How to Use Boolean operators?

June 14th, 2008 yudi Posted in Dealing with Branching Statements | No Comments »

Rather than examine a single Boolean expression, your program may need to examine two or more Boolean expressions. For example, the following program checks the Boolean expression (Salary > 500) and (Bribes > 700). Only if both Boolean expressions are true does the program print You don’t need to pay any taxes., as the following Liberty BASIC program shows:


PROMPT “How much money did you make”; Salary
PROMPT “How much money did you donate to political
           candidates”; Bribes
IF (Salary > 500) THEN
 IF (Bribes > 700) THEN
   PRINT “You don’t need to pay any taxes.”
 END IF
END IF
END

Rather than force the computer to evaluate Boolean expressions one at a time, you can get the computer to evaluate multiple Boolean expressions by using Boolean operators. A Boolean operator does nothing more than connect two or more Boolean expressions to represent a True or a False value.

The two most common Boolean operators are

  • Image from book AND

  • Image from book OR

The AND operator

The AND operator links two Boolean expressions. By rewriting the previous program using the AND operator, you can simplify the program as follows:


PROMPT “How much money did you make?”; Salary
PROMPT “How much did you donate to politicians?”; Bribes
IF (Salary > 500) AND (Bribes > 700) THEN
 PRINT “You don’t need to pay any taxes.”
END IF
END

In this case, the program prints the message You don’t need to pay any taxes only if both (Salary > 500) and (Bribes > 700) are true. If either Boolean expression is false, this program doesn’t print anything.

Run the preceding program and use the values in Table 9-2 to see what happens.

Value of Salary

Value of Bribes

What the Program Does

Remember The AND operator can represent a True value only if both Boolean expressions that it connects also are true.

Technical Stuff To show how the AND operator works, programmers like to draw something known as a truth table, which tells you whether two Boolean expressions that the AND operator connects represent a True or a False value. Table 9-3 is a truth table listing the values for the following two Boolean expressions:


(Boolean expression 1) AND (Boolean expression 2)

Value of (Boolean Expression 1)

Value of (Boolean Expression 2)

Value of the Entire (Boolean Expression 1) AND (Boolean Expression 2)

The equivalent Revolution program looks similar to the Liberty BASIC version. The only main differences are the commands used to ask the user to type data. In the following Revolution program, the ask command asks the user to type an answer, which gets stored temporarily in the it variable, which you must then store in a more descriptive variable:


ask “How much money did you make?”
put it into Salary
ask “How much did you donate to politicians?”
put it into Bribes
if (Salary > 500) and (Bribes > 700) then
  put “You don’t need to pay any taxes.” into message
end if

Technical Stuff In C++, the AND operator consists of a double ampersand symbol (&&), as in this example:


(Boolean expression 1) && (Boolean expression 2)

Warning! Notice that C++ uses the double ampersand to represent the Boolean AND operator, but Revolution uses the double ampersand to concatenate strings. When using different programming languages, watch out for ways that different languages use identical symbols or commands that mean entirely different things.

The following code shows the equivalent C++ program:


#include <iostream.h>
#include <stdio.h>
int main()
{
   int Salary;
   int Bribes;
   cout << “How much money did you make? “;
   cin >> Salary;
   cout << “How much did you donate to politicians? “;
   cin >> Bribes;
   if ((Salary > 500) && (Bribes > 700))
   {
   cout << “You don’t need to pay any taxes.”;
   }
   cout << “\nPress ENTER to continue…” << endl;
   getchar();
   return 0;
}

The OR operator

The OR operator links two Boolean expressions but produces a True value if either Boolean expression represents a True value. For an example of how this operator works, run the following program:


PROMPT “How far can you throw a football”; Football
PROMPT “What is your IQ”; IQ
IF (Football > 50) OR (IQ <= 45) THEN
 PRINT “You have what it takes to become a professional!”
END IF
END

In this case, the program prints the message You have what it takes to become a professional! if either (Football > 50) is true or (IQ <= 45) is true. Only if both Boolean expressions are false does the program refuse to print anything.

Run the preceding program and use the values in Table 9-4 to see what happens.

Value of Football

Value of IQ

What the Program Does

Remember The OR operator can represent a False value only if both Boolean expressions that it connects are false.

Table 9-5 is a truth table to show how the OR operator works for Boolean expressions in the following example:


(Boolean expression 1) OR (Boolean expression 2)

Value of (Boolean Expression 1)

Value of (Boolean Expression 2)

Value of the Entire (Boolean Expression 1) OR (Boolean Expression 2)

Technical Stuff In C++, the OR operator consists of a double vertical line symbol (||), as shown here:


(Boolean expression 1) || (Boolean expression 2)

Here’s the equivalent C++ program:


#include <iostream.h>
#include <stdio.h>
int main()
{
   int Football;
   int IQ;
   cout << “How far can you throw a football? “;
   cin >> Football;
   cout << “What is your IQ? “;
   cin >> IQ;
   if ((Football > 50) || (IQ <= 45))
   {
   cout << “You have what it takes to become a
           professional!”;
   }
   cout << “\nPress ENTER to continue…” << endl;
   getchar();
   return 0;
   }
AddThis Social Bookmark Button

How to use variables in Boolean expressions?

June 14th, 2008 yudi Posted in Dealing with Branching Statements | No Comments »

The sample program in the preceding section uses a Boolean expression (4 < 54) that’s fairly useless because it’s always true. Every time that you run the program, it just prints the message Slap him on the wrist and let him go.

For greater flexibility, Boolean expressions usually compare two variables or one variable to a fixed value, as in the following examples:


(MyIQ >= AnotherIQ)
(Taxes < 100000)

The value of the first Boolean expression (MyIQ < AnotherIQ) depends on the value of the two variables MyIQ and AnotherIQ. Run the following Liberty BASIC program to see how it follows a different set of instructions, depending on the value of the MyIQ and AnotherIQ variables:


PROMPT “What is your IQ”; MyIQ
PROMPT “What is the IQ of another person”; AnotherIQ
IF (MyIQ >= AnotherIQ) THEN
 PRINT “I’m smarter than you are.”
END IF
IF (MyIQ < AnotherIQ) THEN
 PRINT “You have a higher IQ to make up for your lack of
           common sense.”
END IF
END

If you run this program and type different values for MyIQ and AnotherIQ, the program behaves in two possible ways: printing on-screen either I’m smarter than you are. or You have a higher IQ to make up for your lack of common sense.

Remember By using variables in Boolean expressions, you give your program the flexibility it needs to handle different data.

AddThis Social Bookmark Button

How to store Boolean expressions in variables?

June 14th, 2008 yudi Posted in Dealing with Branching Statements | No Comments »

Many programming languages let you define a variable as a Boolean data type.

In REALbasic, you can define a variable as a Boolean data type like this:


Dim Guilty As Boolean

In C++, you can define a variable as a Boolean data type like this:


bool Guilty;

Remember You can just stuff a Boolean expression into a variable in Liberty BASIC and Revolution because neither of these languages forces you to declare your variables ahead of time like C++ or REALbasic.

You can then assign a Boolean expression to a variable in the following way:


Guilty = (4 < 54)

This example assigns the value of True to the variable Guilty. The preceding statement tells the computer, “The Boolean expression of (4 < 54) is true. Thus the value of the Guilty variable is True.”

To see how a variable can hold a Boolean value, try the following Liberty BASIC program:


Guilty = (4 < 54)
IF Guilty THEN
 PRINT “Slap him on the wrist and let him go.”
END IF
END

Each time that you run the preceding program, it prints the message Slap him on the wrist and let him go.

Here’s what the equivalent program looks like in Revolution:


put 4 < 54 into Guilty
if Guilty then
  put “Slap him on the wrist and let him go.” into message
end if
AddThis Social Bookmark Button

How to Use Boolean Expressions

June 14th, 2008 yudi Posted in Dealing with Branching Statements | No Comments »

To make any decision, you first need to ask a question such as, “Do I feel like eating a hamburger?” If the answer is yes, you go to a restaurant that serves hamburgers. If the answer is no, you eat something else.

Computers work in a similar way. Although people can ask questions, computers check something called a Boolean expression. A Boolean expression is a computer’s way of asking a Yes or No question.

Technical Stuff Boolean expressions are part of Boolean algebra, which was named after a man by the name of George Boole. (If you study hard and create your own branch of mathematics, someone may name it after you, too.)

Boolean expressions compare two values. An expression can be either true or false, as shown in Table 9-1.

Boolean Expression

What It Means

Boolean Value

Technical Suff Symbols such as <, >, =, <=, >=, and <> are known as relational operators.

Warning! In most programming languages, you can use the equal sign to test a Boolean expression such as (MyIQ = 120). However in C++ (and other C-derivative languages like Perl), you must use the double equal sign symbol (==) to test for equality such as (MyIQ == 120). If you use a single equal sign, your C++ program won’t work right.

A Boolean expression isn’t very useful by itself, so programmers often use it in branching statements to determine which set (or branch) of instructions the computers should follow at any given time.

The simplest type of a branching statement is called an IF-THEN statement, which offers one alternative set of instructions to follow if a certain Boolean expression is true. An IF-THEN statement typically looks like this:


IF (Boolean expression is True) THEN
   One or more instructions
END IF

Technical Stuff In C++, an IF-THEN statement looks slightly different:


if (Boolean expression is True)
   {
           One or more instructions
   }

In C++, the two big differences are that the word THEN is not used and that you must enclose any instructions to follow within curly brackets.

To see how IF-THEN statements work, look at the following Liberty BASIC program:


IF (4 < 54) THEN                                  ?1
 PRINT “This prints on-screen.”                   ?2
END IF                                            ?3
END                                               ?4

This Liberty BASIC program tells the computer to do the following:

  • ?1 Tells the computer to evaluate the Boolean expression (4 < 54). Because this is true (4 is less than 54), the computer can proceed to the second line.

  • ?2 Tells the computer to print the message This prints on-screen.

  • ?3 Identifies the end of the IF-THEN statement.

  • ?4 Tells the computer that the program is at an end.

To see how IF-THEN statements work in C++, look over the following equivalent program:


if (4 < 54)
   {
   cout << “This prints out on-screen.”;
   }
AddThis Social Bookmark Button

How to Convert Strings into Numbers (And Vice Versa)

June 14th, 2008 yudi Posted in Number and Strings | No Comments »

A string can consist of letters, symbols, and numbers. The most common use for storing numbers as a string is when the numbers represent something special, such as a telephone number or address. If you want the computer to print a telephone number, you must store that number as a string, as shown here:


PRINT “555-1212″

This command prints the string 555-1212 on-screen. The quotation marks tell the computer, “Anything inside the quotation marks is a string.” What happens if you try the following command?


PRINT 555-1212

Liberty BASIC interprets this command to mean, “Subtract the number 1,212 from the number 555 and print the result (which is –657) on-screen.”

Although the number 53 and the string “53” may look identical to a human, computers treat numbers as entirely different from strings. To a computer, the number 53 is as completely different from the string “53” as a painting of a cat is different from a real cat.

Converting strings into numbers

The problem with strings is that when users enter numbers, the computer may treat those numbers as strings, but your program may need to use those numbers as data. If a program stores a number as a string but needs to use that number as data, the program needs to convert that number (as a string) into data.

To convert a string into data, most programming languages come with special string-to-data and data-to-string conversion commands. In Liberty BASIC, you can convert a string into a number by using the VAL function, which works like this:


VAL(”String”)

The VAL function tells Liberty BASIC, “Take a string (such as “45”) and turn it into a number.” If you have a string “45” and use the VAL function, Liberty BASIC converts that string “45” into the number 45.

Remember If you use the VAL function on a string that doesn’t represent a number, such as the string “Hello!”, the VAL function returns a zero value.

To see how the VAL function works, run the following Liberty BASIC program:


YearBorn$ = “1964″                                ?1
PRINT “You were born in ” + YearBorn$             ?2
Age = 2007 - VAL(YearBorn$)                       ?3
PRINT “In 2007, you were this old = “; Age        ?4
END ?5

This Liberty BASIC program tells the computer to do the following:

  • ?1 Creates a string variable called YearBorn$ and stuffs it with the string “1964”.

  • ?2 Prints the string “You were born in ” followed by the string stored in the YearBorn$ variable, so the entire line prints You were born in 1964. In this line, the computer treats “1964” as a string.

  • ?3 The VAL function converts the string “1964” to the number 1964. Then it subtracts 1964 from 2007 and stores the calculated result in the Age variable.

  • ?4 Prints the string In 2007, you were this old = and then prints the number stored in the Age variable, which is 20071964 (43).

  • ?5 This line marks the end of the program.

REALbasic uses the same Val function to convert a string into data, as shown here:


Dim YearBorn as string                            ?1
Dim Age as integer                                ?2
YearBorn = “1964″                                 ?3
MsgBox “You were born in ” + YearBorn             ?4
Age = 2007 - Val(YearBorn)                        ?5
MsgBox “In 2007, you were this old = ” + Str(Age) ?6

This REALbasic program tells the computer to do the following:

  • ?1 Creates a string variable called YearBorn.

  • ?2 Creates an integer variable called Age.

  • ?3 Stores the string “1964” into the YearBorn string variable.

  • ?4 Uses the MsgBox command to display a box on-screen that shows the string “You were born in “ followed by the string stored in the YearBorn variable, so the entire line prints You were born in 1964. In this line, the computer treats “1964” as a string.

  • ?5 The Val function converts the string “1964” to the number 1964. Then it subtracts 1964 from 2007 and stores the calculated result (43) in the Age variable.

  • ?6 Uses the MsgBox command to display a box on-screen that shows the string In 2007, you were this old = and then uses the Str function to convert the Age variable (43) to the string “43”. So the entire line prints out In 2007, you were this old = 43.

One problem with type-safe languages like REALbasic is that they restrict what type of data can go into variables (to prevent errors in your program), but they can also make programming more cumbersome when you want to treat a number as both a string and data.

The following Revolution program automatically detects when a number should be treated as a string and when it should be treated as data. Although this has the potential for causing errors, it also gives you the freedom to concentrate on the logic of your program and not worry about trivial details like converting strings into data (and vice versa).


put “1964″ into YearBorn                                 ?1
put “You were born in ” && YearBorn into message         ?2
wait for 5 seconds                                       ?3
put 2007 - YearBorn into Age                             ?4
put “In 2007, you were this old = ” && Age into message  ?5

This Revolution program tells the computer to do the following:

  • ?1 Stores the string “1964” in a variable called YearBorn.

  • ?2 The two ampersand symbols (&&) tack the string “1964” onto the other string “You were born in ”. Then this line display You were born in 1964 in a message box on-screen.

  • ?3 Tells the computer to wait for five seconds. Without this command, Revolution would rush into the rest of the program and the message box displayed in line 2 would appear and disappear in the blink of an eye.

  • ?4 Automatically converts the string “1964” into the number 1964. Then subtracts the number 1964 from 2007 and stores the result (43) in a variable called Age.

  • ?5 Converts the Age variable number (43) into the string “43” and then the two ampersand symbols (&&) tack the “43” string onto the end of the “In 2007, you were this old = ” string. Then this line displays In 2007, you were this old = 43 in a message box that appears on-screen.

The main difference between Revolution and the previous two BASIC examples is that Revolution is smart enough to figure out when to treat a number as data and when to treat a number as a string without having to define any data conversion yourself.

Technical Stuff The C++ language doesn’t recognize strings as valid data types, although you can define a string data type by using the using namespace std; command at the top of your programs. However, C++ doesn’t provide any built-in commands for converting strings into numbers (and vice versa), so many programmers simply write their own conversion programs and store them in library files that they can reuse later.

Converting a number into a string

Rather than convert a string into a number, you might want to go the other way and convert a number into a string.

In Liberty BASIC, you can convert a number into a string by using the STR$ function, which works like this:


STR$ (Number)

The following Liberty BASIC program shows how to use the STR$ function to convert the BossIQ variable into a string:


BossIQ = 34                                      ?1
NewString$ = “This is the IQ of your boss = ” +
           STR$(BossIQ)                          ?2
PRINT NewString$                                 ?3
END                                              ?4

This Liberty BASIC program tells the computer to do the following:

  • ?1 Stores the number 34 in a variable called BossIQ.

  • ?2 Uses the STR$ function to convert the number stored in the BossIQ variable (34) into a string (“34”). Then it pastes the two strings together to store This is the IQ of your boss = 34 in a string variable called NewString$.

  • ?3 Prints the string This is the IQ of your boss = 34 on-screen.

  • ?4 Defines the end of the program.

In this example, Liberty BASIC lets you declare a number variable and convert that number into a string. Here’s the equivalent REALbasic program that converts a number into a string by using the Str function:


Dim BossIQ as Integer
Dim NewString as String
BossIQ = 34
NewString = “This is the IQ of your boss = ” + Str(BossIQ)
MsgBox NewString

In Revolution, you don’t need to give an explicit command to convert a number into a string; the computer does this conversion for you automatically, as the following program demonstrates:


put 34 into BossIQ
put “This is the IQ of your boss = ” && BossIQ into
           message
AddThis Social Bookmark Button

Declaring variables as strings

April 21st, 2008 yudi Posted in Number and Strings | No Comments »

 

As with numbers, you can use strings directly in your program, as follows:


PRINT “Print me.”
PRINT 54
END

Just as with numbers, you may want to store strings in variables so you can reuse that particular string over and over again by typing just the variable rather than the entire string.

Unfortunately, every programming language tends to use different ways to declare a variable to hold a string data type. In Liberty BASIC, you never declare variables until you actually assign data to them. When assigning a string to a variable, the variable name must include the dollar sign ($) at the end of the variable name, as follows:


MyName$ = “Bo the Cat”

In Revolution, you can assign a string to a variable (just like you can assign a number to a variable) by using the into command like so:


put “Bo the Cat” into MyName

In REALbasic, you can declare a variable to hold string data types, as follows:


Dim MyName As String

The C++ language won’t recognize string data types, so you must use a library file called std, which you can include in your program by adding the following:


using namespace std;

This command tells your C++ program to use a library file called std, which defines a string data type. After you include the std library file, you can declare a string variable such as:


string myName;

So an entire C++ program that declares a string variable might look like this:


#include <iostream.h>
#include <stdio.h>
using namespace std;
int main()
{
   string myName;
   myName = “Bo the Cat”;
   cout << myName;
   cout << “\nPress ENTER to continue…” << endl;
   getchar();
   return 0;
}
AddThis Social Bookmark Button

Smashing strings together

April 21st, 2008 yudi Posted in Number and Strings | No Comments »

Unlike with numbers, you can’t subtract, divide, or multiply strings. But you can add strings (which is technically known as concatenating strings). To concatenate two strings, you use the plus sign (+) to essentially smash two strings into a single string, as the following Liberty BASIC example shows:


MyName$ = “Joe Smith”                             ?1
PRINT “Hello, ” + MyName$                         ?2
END                                               ?3

This Liberty BASIC program tells the computer to do the following:

  • ?1 Creates a string variable called MyName$ and stuffs it with the string “Joe Smith”.

  • ?2 Prints the string “Hello, “ followed by the string stored in the MyName$ variable, so the entire line prints out Hello, Joe Smith.

  • ?3 Tells the computer that the program is at an end.

Remember If you concatenate strings, make sure that you leave a space between the two strings so that they don’t appear smashed together (likethis). In the previous example, notice the space in the second line following the word Hello and the comma.

Both REALbasic and C++ also let you use the plus sign (+) to concatenate strings. However, Revolution uses the dual ampersand symbols (&&) to concatenate strings like so:


put “Joe Smith” into MyName
put “Hello, ” && MyName into message
 
AddThis Social Bookmark Button




eXTReMe Tracker