Sunteți pe pagina 1din 41

BASIC Programming

Ahmad Abba Datti

PART I
The Concept of an Algorithm
An algorithm is.. a set of steps for carrying out a specific task.

a set of rules that precisely defines a sequence of operations.

a finite, unambiguous set of instructions for solving a particular problem.

any well-defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values, as output.

an effective method expressed as a finite list of well-defined instructions for a computation that, when executed, proceeds through a finite number of successive steps, eventually producing an output and terminating at a final step.

Examples A set of instructions for guiding a person to reach a given destination (Directions) could be regarded as an algorithm. For instance, to get from BUK new site to the ICE-Campus

1. From the BUK new site main gate, take a left onto Gwarzo Road, 2. At Tal'udu Round-about, take another left onto Aminu Kano Way, 2

3. Take the last U-turn on Aminu Kano Way, 4. Take the first Junction by your right (Kwanar Taya), 5. Enter the first gate by your left (and you have reached your destination).

A set of instructions for preparing a dish (A food recipe) could also be regarded as an algorithm.

1. Get the following ingredients: 2-cups of self-raising flour, 1-cup of sugar, 1-cup of butter and 4 eggs, 2. Pour all the ingredients in a bowl and mix throughly, 3. Pour the mixture into a greased baking pan and bake at 180C for about 20 minutes, 4. Serve.

An algorithm for determining the Day of birth of a person by using that

person's date of birth (in the Gregorian Calendar), known as Zeller's algorithm can also be seen below.

Get the Day (1-31), Month (1-12) and Year (1582 9999) of birth If MONTH is 1 or 2 Then A = MONTH + 10 YEAR = YEAR - 1 Else A = MONTH - 2 End If

B = DAY C = Year of the century (00-99) 3

D = Century (15-99) W = (13 * A 1) / 5 X=C/4 Y=D/4 Z=W+X+Y+B+C2*D R = Mod(Z,7): that is, the remainder when Z is divided by 7 If R = 0 Then Day is Sunday If R = 1 Then Day is Monday If R = 2 Then Day is Tuesday If R = 3 Then Day is Wednesday If R = 4 Then Day is Thursday If R = 5 Then Day is Friday If R = 6 Then Day is Saturday

Program
A program is... a sequence of instructions that a computer can interpret and execute. an implementation of an algorithm on a computer. Now referring back to our examples of algorithms, we can notice if we are to write a program for the 1st (Directions) and the 2nd (Recipe), our computer must have legs, mouth and eyes in order to execute the instructions given. But in case of the 3 rd (Zeller's), it only involves computation as such a computer program can be written based on that algorithm.

Examples: The program below is an implementation of Zeller's algorithm BASIC programming language.

1. DIM AS INTEGER day, month, year, A, B, C, D, W, X, Y, Z, R 2. INPUT Enter Day, Month, Year; day, month, year 3. IF month=1 OR month=2 THEN 4. 5. 6. ELSE 7. 8. END IF 9. B = day 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. C = year MOD 100 D = year \ 100 W = (13 * A 1) \ 5 X=C\4 Y=D\4 Z=W+X+Y+B+C2*D R = Z MOD 7 IF R = 0 THEN PRINT Sunday ELSEIF R = 1 THEN PRINT Monday ELSEIF R = 2 THEN A = month - 2 A = month + 10 year = year - 1

22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33.

PRINT Tuesday ELSEIF R = 3 THEN PRINT Wednesday ELSEIF R = 4 THEN PRINT Thursday ELSEIF R = 5 THEN PRINT Friday ELSEIF R = 6 THEN PRINT Saturday ELSE PRINT INVALID DATE END IF

Programming
Programming is ... the process of designing, implementing, debugging and maintenance of a computer program. 'designing' means creating an algorithm 'implementing' means writing a computer program based on the algorithm 'debugging' means removing 'bugs' (errors) during implementation 'maintenance' means supporting usage of the program by modifying and upgrading it as the user requires and sometimes even removing ' bugs' not found at the 'debugging' stage.

Programming Language
A programming language is... an artificial language designed to communicate instructions that can be executed by a computer.

History of Programming
The history of programming languages has been categorised into generations starting from the 1st generation to the 5th generation. The change in the nature of the programming languages is mainly as a result of development in the computer hardware. 1st Generation: During this generation, programming was done basically using the only language the computer CPU understands which is known as the Machine Language. There are only two alphabets in this language '0' and '1'. so all commands and data supplied to the command are written with this two alphabets. For instance,

0001 0001 0010 0110

is an instruction consisting of the command '0001' (add) and the memory address '0001' (r1) storing the first operand and another memory address '0010' (r2) storing the second operand and finally another memory address '0110' (r6) to store the result of the addition. Thus, the instructions is equivalent to the mathematical expression of 'r6 = r1 + r2'. A 4-instructions program written in Machine Language will appear something like:

0001 0011 1010 1100 7

0101 0001 0001 0110 0000 0111 1000 0010 1000 1111 0001 0100 Features: 1. The main advantage of writing programs in Machine Language is that since it is the language of the computer, programs are the most efficient and they get executed the fastest compared to programs written in other languages as we will see. 2. But problems are: Learning, and eventually, writing programs is extremely difficult. As a result of the above difficulty, the tendency to make mistakes when coding programs is very high. A single '0' where '1' is expected will stop the whole program from running. In case there is a 'bug' (error) in a program, it becomes extremely difficult to locate and correct it. It also takes longer to write programs in Machine Language. Programs written in machine language are specific to the computer hardware they are written on and thus cannot be used on machines with a different architecture (Not portable). 2nd Generation: In order to reduce the difficulty faced with writing Machine Language programs, another language (Assembly Language) was employed which now uses Mnemonics (like abbreviated English words) to represent both Commands and Data in a program since people will find it easier to remember English-like words as opposed to '0's and '1's. The example of the machine language instruction for addition given above will now appear in Assembly Language as 2 instructions thus:

ADD R1, R2

STO R6 Features: 1. Writing programs is now easier (than using Machine language), as is debugging them. 2. But as a result of the introduction of a new language in which the program is written which is alien to the computer, there is another need for translating that program (from Assembly Language) into Machine Language before the CPU is now able to understand what it is needed to do. This new piece of software a translator, is known as an Assembler. This leads to: A relatively slower execution time (since the program has to be translated along the way). 3. Programs are still not portable. 3rd Generation: During the 3rd generation, programming languages that are much more easier to understand and program with were used for programming. These languages adopt the use of commands that are very much like those in English and the use of mathematical items like variables (to represent memory locations) and symbols like '+' and '-' to represent addition and subtraction operations respectively. Among the hundreds of programming languages in this category is BASIC, Fortran, C, C++, C#, Java, Visual Basic, SmallTalk, Lisp, Ada, COBOL, Haskell to mention but a few. An instruction to add x to y and store the result in z will appear in BASIC as: z=x+y The program for Zeller's algorithm earlier encountered is a good example of complete BASIC program. Features: 1. Programming is much more easier due to the use familiar words and concepts.

2. The need for a translator (called a Compiler or an Interpreter) still remains thus leading to an increase in the time of required for execution compared to Machine Language (as is the case with Assemblers). 3. The abundance of a programming language's compiler for different machine architectures results in Programs written in that language to be portable (runnable on a machine with different architecture). 4th Generation: A fourth generation (programming) language is a grouping of programming languages that attempt to get closer than 3rd generation languages to human language, form of thinking and conceptualization. They are designed to reduce the overall time, effort and cost of software development. Programs written are translated into 3rd generation languages which are in turn compiled into either machine or assembly code before execution. The main domains and families of 4 th generation languages are: database queries (e.g. SQL), report generators, data manipulation, analysis and reporting, GUI creators, mathematical optimization (e.g. MATLAB), web development (e.g. PHP) etc. An instruction in SQL to search a database record for all entries with 'Smith' as name will appear thus:

find all records where name is Smith Features: 1. Clearly programming has become much more easier (instructions being expressed almost naturally). 2. Not much programming experience is needed to write a program. 3. Their main drawback is that these languages are mostly specific to domains. As such one cannot write a program for handling databases with a language designed for Web site development as opposed to 3rd generation languages which are mostly general purpose.

10

5th Generation: A 5th generation programming language is a programming language based on solving problems using constraints (specifications) given to the program, rather than using an algorithm written by a programmer. Most constraint-based and logic programming languages and some declarative languages are 5th generation languages e.g. Prolog, OPS5, and Mercury. While 4th generation programming languages are designed to build specific programs by the programmer, 5th generation languages are designed to make the computer solve a given problem without the programmer. This way, the programmer only needs to worry about what problems need to be solved and what conditions need to be met, without worrying about how to implement an algorithm to solve them. 5Th generation languages are used mainly in artificial intelligence research.

Types of Programming Languages


Programming languages are categorised into two types (based on their proximity to natural languages of humans): 1. Low-Level Languages (Closer to machine language than human language) 1st Generation Languages (Machine Language) 2nd Generation Languages (Assembly Language)

2. High Level Languages (Closer to human languages than machine language): 3rd Generation Languages 4th Generation Languages 5th Generation Languages

11

PART II
BASIC programming and the BASIC IDE
For the purpose of an introductory course in programming like this one, we are going to be working with a particular 3rd generation high level programming language called FreeBASIC which was based on the original BASIC (an acronym for Beginner's All-purpose Symbolic Instruction Code) created at Dartmouth College. In order to write a program, a programmer needs most importantly the Compiler for that particular language and for his appropriate machine whose purpose is to take the program from the Human readable form (Source Code) and translate it to machine readable form (Object Code). Another necessary tool is an Editor which is where to type in the instructions, in other words, to create the Source Code. Then optionally, one might need a debugger for helping with the debugging aspects of programming. All these tools can be integrated into one large software to be known as an Integrated Development Environment (IDE) which has all the above tools and more. Examples of such IDE's for FreeBASIC are FBIDE (http://fbide.freebasic.net/) FBEdit (http://radasm.cherrytree.at/fbedit/)

Overview of the FBIde

12

Recently opened FBIde (without Design Window) To start writing a program, select 'New' from the 'File' menu and then 'Save' from the same 'File' menu. Proceed to give a name to your program and then save. In the design area that appears with a blinking cursor, type in the statements of your program thus:

Program Source Code in Design Window of FBIde

When you are ready to test-run your program, select 'Compile and Run' from the 'Run' menu,

13

Compile and Run When successful, you will now see the Output Window like this:

Program in Execution in Output Window

to close the output window and return to the design window you just press any key from the keyboard.

Literals, Variables and Data-types


A program is a collection of instructions, ranging from one to thousands. And each of this instruction is in turn made up of a Command and (where applicable,) the Data that the command is to work with. Consider:

PRINT Hello World The above instruction can be seen to be made up of the Command PRINT and the Data Hello World that is supposed to be displayed to the user on the Console Screen. Upon execution of this command, the user will see on the output window Hello World. We are going to start with the Data aspect of programming. 14

Literals: Raw data of any kind, be it a number, text or combination of both, is known as a literal. Hello World is a literal, so also is 150, 22.87, Room005 etc. they are all actual values by themselves. Variables: Now in order for the program to be able to handle several of these literals without mixing them up and forgetting some, there is a need for some of temporary storage on the computer memory (RAM). This is where the concept of a variable comes into play. Variables are like little containers capable of holding a literal (in RAM) until the program finishes execution. In addition to this, the value being held by this variable could be changed as many times as desired in the program (that is why they are called variables).

x=2 Name = Bayero Pi = 3.1428571429 Allowance = 50000 In the above statements, x is a variable holding the value 2. Name is another variable holing Bayero. 3.1428571429 is also being held by the variable Pi, and finally Allowance is another variable storing 50000. If you know your program will need to temporarily store data that it gets from the user, you must first create enough variables to hold that data. If you dont create enough variables to hold all the data that your program needs, your program will simply lose any data you give it, which effectively makes your program utterly useless. So as far as variables are concerned, before you write a program, you need to identify the following: 15

What names should I give each variable? What type of data does each variable need to hold (numbers, text)?

Naming Variables: Each variable must have a distinct name to keep your computer from getting confused. The names can be anything as far as they abide by the following rules:

The first character of a variable name must be a letter (a-z, A-Z):

password (legal) sum1 x 2go 9ja 7up (legal) (legal) (illegal) (illegal) (illegal)

Variable name cannot contain a special character (+, &, #, @ ), /, - space). Although different programming languages allow a particular special character. For some it is '_' (underscore), for others it is '.' (period), and yet for others it is '@'. but it is always safer for one to avoid them all together:

Mony First Name FirstName Reg. Num C++

(illegal) (illegal) (legal) (illegal) (illegal)

16

(radius)

(illegal)

The name of a variable cant be the same as a (FreeBASIC) keyword: end print if case exit (illegal) (illegal) (illegal) (illegal) (illegal)

Data-types: For the sake of efficiency and safety, whenever a variable is created in a program, the type of data you are expecting to be held by that variable throughout it's lifetime must also be specified. There are seven data types in FreeBasic, six of which are dealing with numbers (numeric) and one dealing with text (non-numeric). Numeric Data-types:

S.No Datatype 1 2 3 4 5 6 Byte Short Integer LongInt Single Double -128 to 127

Range range -32,768 to 32767 -2,147,483,648 2,147,483,647 9,223,372,036,854,775,807 1.1 x 1038 to 3.43 x 1038 -2.2 x 10-308 to 1.7 x 10308

Description Holds whole numbers in the given Holds whole numbers in the given range to Holds whole numbers in the given range range Holds fractional numbers in the given range Holds fractional numbers in the given range

-9,223,372,036,854,775,808 to Holds whole numbers in the given

17

Non-numeric data types: S.No Datatype Range (no. of characters) Description 1 String 0 to 2,147,483,647 Holds zero (0) or more characters. They could be letters (A-Z, a-z), numbers (0 9) or special characters (!, @, #, +, -, space, =, /, etc) or any combination of letters, characters. NB: String literals must be enclosed in double quotes (). For instance : Hello World is a string. Age is a string but Age is a variable. 21 is a string but 21 is a numeric literal (byte, short etc). Print is a string but Print is a command. 2go is a string but 2go is an illegal entry (neither a variable nor a numeric literal nor a command). numbers and special

Declaring a Variable: When you intend to use a variable in your program you have to first of all notify the compiler of the name and datatype of that variable by declaring it before you start using it. In FreeBasic, a variable is declared in this form:

18

DIM variableName AS DATATYPE where,

DIM: is the FreeBASIC command for variable declaration.

VariableName: should be replaced by the name you choose to give your


variable AS: the keyword signifying what follows to be a particular data type. DATATYPE: any of the recognized FreeBasic Data types. For example,

DIM x AS INTEGER DIM FirstName AS STRING DIM pi AS DOUBLE

In case you want to declare multiple variables all of the same datatype, you could write individual instructions such as:

DIM FirstName AS STRING DIM MiddleName AS STRING DIM Surname AS STRING

Or more succinctly, you could just declare everything on a single line with one instruction using:

DIM AS STRING FirstName, MiddleName, Surname Furthermore, if you want to declare multiple variables but each with a different 19

datatype and with a single instruction, you could use:

DIM acceleration AS DOUBLE, age AS SHORT, password AS STRING

BASIC Commands
Just as a program is going to be almost useless without variables, it is also going to be nearly useless without a means of communicating with it's user. This is because there is no way the program could get input data and there is no way it could present the result of it's computation to the user. So basically, all programming languages have OUTPUT and INPUT commands for communicating with it's potential users. Output occurs whenever a program displays information (data) on any of several computer output devices. Some common examples of output include the following: Data that appears on-screen (such as text, pictures, or videos) Data that prints on paper through a printer Sound that plays through a computers speakers (such as music files)

Input occurs whenever a program accepts data from an outside source using any of a computer input devices. Some examples of where a program can get input include the following: Anything the user types from the keyboard The movement and clicks from the computer mouse Data that someone previously stores in a file (such as a word processor document) Data that feeds into the computer from an outside source (such as a Web page sent through a modem or an image captured through a scanner). For a start, we are going to concentrate on commands that only display output on 20

the console screen and get input from the standard keyboard. The PRINT and the INPUT command respectively.

PRINT: The simplest way to use a PRINT command is write the command followed by a string literal, a variable or an expression. For instance:

S.No 1 2

FreeBASIC PROGRAM PRINT What are you looking at? text = What are you looking at? pi = 3.1428571429 PRINT text PRINT pi

OUTPUT What are you looking at? What are you looking at? 3.1428571429

basicSalary = 10 allowance = 3 PRINT basicSalary + allowance

13

The PRINT commands above are all having only one value to be displayed on the screen. A string literal in the 1st, a string variable and then a single variable in the 2nd and an integer expression in the third. But the power of the PRINT command doesn't end there. A single PRINT command (just like the DIM) could be given multiple values to display with the condition that they be separated by a comma (,) or a semicolon (;). For instance, PROGRAM: x=1 y=2 z=3 PRINT x ; y ; z 21

OUTPUT: 123

PROGRAM: bSalary = 10 allw = 3 ded = 0 PRINT Basic Salary = ; bSalary ; Allowance = ; allw ; Deductions = ; ded PRINT Net pay = ; bSalary + allw ded OUTPUT: Basic Salary = 10 Allowance = 3 Deductions = 0 Net Pay = 13 INPUT As the PRINT command gives your program the capability to output data, the INPUT command gives your program the capability to accept data from the keyboard. The simplest way to use the INPUT command is to type the word INPUT and follow it with a variable that is to hold whatever literal is inputted by the user from the standard keyboard. For instance, PROGRAM PRINT What is your name? INPUT urName PRINT What?! ; urName ; ? What kind of name is that! OUTPUT What is your name?

22

McFish What?! McFish? What kind of name is that? Here, the 1st instruction will display What is your name? on the screen. The 2nd instruction will just display a blinking cursor (_) signifying to you that the program is expecting something from the keyboard. After typing something ( McFish for example) and pressing Enter, the program takes that and stores it in the variable urName where it is later going to be used by the 3rd instruction. In order to be able to accept multiple values and store them in different variables using a single INPUT command, you just write the command and follow it with the list of variables separated by commas (,) and when the program runs, the user is then expected to write the corresponding values also separated by commas (,) or just spaces ( ). For instance, PROGRAM DIM AS INTEGER a, b, c, d, e, f PRINT Enter 6 integers to get there sum: INPUT a, b, c, d, e, f PRINT Sum = ; a + b + c + d + e + f OUTPUT Enter 6 integers to get there sum: 2,4,6,8,10,12 Sum = 42 Using an INPUT command without having previously telling your user what you expect from him (with a PRINT command) is like meeting someone and just telling him to give you. That person is obviously going to get confused as to what you expect him to give you. Meaning when you use an INPUT command without using a PRINT command before it to signify what you intend to collect, your user might at

23

best give you the wrong input or at worst never give you anything. To facilitate things, you could merge the PRINT and INPUT command by writing the descriptive-message (followed by a semicolon ' ;') between the INPUT command and the variable(s). That is, Instead of: PRINT Enter your Username: INPUT username You just use: INPUT Enter your Username: ; username

Operators and Expressions


One of the most important parts of a computer program is its capability to manipulate any data that it receives and to return a useful answer. The two types of data that your program must manipulate are numbers and text (strings).

Mathematical Computations Mathematical computations are generally carried out by applying operators on numbers (variables or literals). The table below gives a list of some of the fundamental operators available in FreeBasic with there corresponding symbols:

S.N o 1 2 3 4

Operation Addition Subtraction Multiplication Division

Symbol + * /

Example (=Result) 12 + 6 (=18) 9 17 (=-8) 7 * 5 (=35) 7 / 5 (=1.4) 24

Remark Sum of 12 and 6 Difference between 9 and 17 Product of 7 and 5 Quotient of 7 and 5

5 6 7 8 9

Exponentiation Integer Division Modulo Division Parenthesis Assignment

^ \ Mod () =

3 ^ 4 (=81) 7 / 5 (=1) 7 mod 5 (=2) (4^2)+(2^4) Pi = 3.142 newPi = pi pi = 22 / 7 x=x+2

3 raised to the power of 4 Integer part of the quotient of 7 and 5 Remainder of the division 7 / 5 Grouping sub-expressions Used in putting a literal, value of a variable or the result of an expression in the right hand side into another variable in the left hand side.

NB: The exponentiation symbol (^) appears on the 6 key. You can also use the subtraction symbol () to indicate negative numbers, such as 34.5 or 90. x = x + 2: Here, the old value of x is increased by 2 and the result stored in the same variable 'x'. Examples: S.No . 1 2 3 4 5 6 7 8 avg = (a + b + c) / 3 y=m*x+c z=p*r^n+w/x-y a*x^2+b*x+c P * (1 + I / 4) ^ (4 * n) (x + y) ^ 2 (( s ^ 4) * (( x + y ^ n) ^ q) ^ 0.5) / (j * (f t * z)) (a / b) + (c / d) Mathematical Expression FreeBasic Expression

When several operations occur in a single expression, each operation is evaluated and resolved in a predetermined order. For example, does 5 + 6 * 3 equal 33 or does it equal 23? FreeBasic evaluates expressions based on Precedence Rules, that is, rules that describe what gets evaluated when.

25

As a rule, if an operator in an expression has a higher precedence, it is evaluated before an operator of lower precedence. If operators have equal precedence, they then are evaluated in the order in of their associativity. The associativity may be Left to Right or Right to Left order. Binary operators those that need two values (such as + , ^) are evaluated Left to Right. The assignment operator is always the last to be evaluated. Parentheses can be used to override, force and change operator precedence. Operations within parentheses are performed before other operations. Within the parentheses normal operator precedence is used. You can also embed parenthesis within parenthesis in which case innermost ones are evaluated first before outer ones.

The following table lists operator precedence from highest (1) to lowest (5).

Precedence (Priority) 1 2 3 4 5 6 7 (Last) Consider:

Operator Parentheses '( )' Exponentiation '^' Multiplication '*' and Division '/' Integer Division '\' Modulo Division 'mod' Addition '+' and Subtraction '' Assignment '='

TaxYouOwe = PastTaxes + NetIncome * TaxRate If the value of NetIncome is 50,000, the value of TaxRate is 1.01, and the value of PastTaxes is 2,500, the expression now becomes:

26

TaxYouOwe = 2500 + 50000 * 1.01 So now the question is whether FreeBASIC adds 2,500 to 50,000 and THEN multiplies the whole thing by 1.01 (in which case the answer is 53,025) or multiplies 50,000 by 1.01 first and THEN adds 2,500 (in which case the answer is 53,000). Example: myMoney = 3 + 4 ^ 5 - 8 / 5 * 7

FreeBASIC calculates the value of 4 ^ 5, which is 1,024. The formula now looks as follows: 3 + 1024 - 8 / 5 * 7

Next, the program calculates all multiplication and division (/). Because multiplication and division have equal precedence, the computer starts calculating with the first multiplication or division (/) operator that it finds, moving from left to right. The program calculates the value of 8 / 5 first (1.6) and then multiplies it by 7. So the formula now looks as follows: 3 + 1024 - 11.2

Now, the program calculates all addition and subtraction, moving from left to right. First it calculates the value of 3 + 1,024 (which is 1,027); it then subtracts 11.2 from it. Thus the final answer looks as follows: 1015.8

Finally, due to no more operators apart from Assignment '=', the program assigns the value 1015.8 to the variable myMoney. myMoney = 1015.8

Example: Consider: x=x+2 (assuming x = 12) This expression has only two operators Addition '+' and Assignment '='. 27

Addition has higher precedence over Assignment hence, x = 12 + 2 x = 24

Finally 24 is assigned to x. x = 24

Exercise: 1. Evaluate: sigma = ((3 + 4) ^ 5 / 3 - 8) / 5 * 7

is the result the same with that of the previous example? Why? Or why not?

Selection Constructs
The whole purpose of a program is to make the computer behave in a certain way. The most primitive programs act exactly the same way each time that you run them, such as displaying, Hello, world! or the result of an arithmetic expression. Such primitive programs may work fine for learning to program, but theyre relatively useless otherwise, because most programs need to accept data and modify their behavior based on any data that they receive. Consider the program in an ATM machine, you are only able to withdraw money from it IF you enter the correct PIN for that ATM card AND the amount in your account is greater than or equal to the amount you are requesting AND you have not exceeded your daily withdrawal limit. If the program is written in a manner we have been seeing just executing all instructions sequentially, it means the moment you insert your ATM card into the machine it will just ask you the amount you want and give it out to you.

28

From the programmers perspective, the program first requests the PIN and depending on the value given either proceeds or quits. It then requests for amount and depending on whether there is enough money in the account also proceeds or quits. The Programming Constructs/Structures that enable a programmer to execute instructions based on the satisfaction or otherwise of a condition are what are known as Selection Structures. We are going to study FreeBasic's two types of Selection Constructs: the IF...THEN construct and the SELECT...CASE construct.

The IF...THEN construct: The format for using a simple IF...THEN construct is:

IF condition THEN statement(s) END IF where,

condition: is an expression whose answer is either TRUE or FALSE statement(s): one or more FreeBasic instructions to execute ONLY when condition is TRUE. The compiler will skip to the next instruction AFTER END IF when condition is FALSE. The Condition: So far we have seen one type of expression - the arithmetic expression, which is made up of variables or numeric literals with arithmetic operators acting upon them to produce a result which is finally a numeric literal. 2*pi*r^2 for instance to

29

produce 25.136 when r = 2. another kind of expression is called a boolean expression which is made up of variables, literals or expressions being acted upon by relational operators whose answer is either TRUE or FALSE. Relational operators are operators that compare two operands (variables, literals or expressions) and return whether a given relationship between them is TRUE or FALSE. For instance,

3>4 The above is a boolean expression whose answer is FALSE because the relationship being tested (is greater than '>) does not hold for 3 and 4. simply put, it is NOT TRUE that 3 is greater than 4. Now consider

4 -1 < 4 here, the result of this boolean expression is TRUE because the relationship (is less than '<') holds for 4 1 ( = 3) and 4. Simply, it is TRUE that (4 - 1) is less than 4. Here is a list of the FreeBasic's relational operators:

Relation Less than

Symbol Usage Remark < than value of 'y'. FALSE otherwise.

Example

x < y TRUE if value of 'x' is less 13 < 31 (TRUE)

Greater than

>

x > y TRUE if value of 'x' is 13 > 31 (FALSE) greater than value of 'y'. FALSE otherwise

Equals

x = y TRUE (if value of 'x' is equal 13 = 31 (FALSE) to value of 'y'). FALSE otherwise.

30

Less than or equals

<=

x<= y TRUE if value of 'x' is either 13 < = 31 (TRUE) less than value of 'y' or OR equal to value of 'y'. FALSE otherwise.

Greater or equals

than

>=

x >= y TRUE if value of 'x' is either 13 > = 31 (FALSE) greater than value of 'y' or OR equal to value of 'y'. FALSE otherwise.

Not equals

<>

x <> y TRUE if value of 'x' is not 13 <> 31 (TRUE) equal to value of 'y'. FALSE otherwise.

Now looking at the following FreeBasic Program,

1 2 3 4 5 6 7 8

DIM AS SINGLE radius, area, pi INPUT Enter Radius: ; radius pi = 22/7 area = 0 IF radius >= 0 THEN area = 2*pi*r^2 END IF PRINT Area = ; area

You will notice that line 6 is only going to get executed if the condition 'radius >= 0' is TRUE. Which depends on the value of 'radius' inputted by the user at line 2. So any user who enters a negative value for radius is going to get Area = 0 as answer because the condition 'radius >= 0' will result in FALSE and that will not let the compiler execute the statement inside the IF...THEN...END IF construct.

31

Compound Boolean Expressions Multiple boolean expressions could be joined together to form one compound boolean expression with the aid Boolean Operators: Boolean Operators S.No Operator 1 AND Usage expression1 expression2 2 OR expression1 expression2 3 NOT NOT expression Remark AND TRUE if both are both are expression1 TRUE. expression1 FALSE. and FALSE and TRUE expression2 otherwise OR FALSE if expression2 otherwise. TRUE if expression is FALSE; FALSE if expression is TRUE. NB: The expressions above are simple boolean expressions evaluating to either TRUE or FALSE. Such as x+y <> 0 AND x*y <= 1.

IF financialStatus = Rich AND maritalStatus = Single THEN PRINT Grade 1 Candidate END IF

IF beauty > = average OR character > good THEN PRINT Potential Candidate END IF

IF...THEN....ELSE The IF THEN statement tells your compiler to follow a(some) statement(s) only if a 32

certain condition is true. If that condition is not true, the computer ignores all the instructions trapped between the IF...THEN statement and the corresponding END IF and moves to the instruction immediately after that END IF. A variation of this exists - the IF THEN ELSE statement. It is similar to the simple IF in the sense that it executes a set of instructions when the condition is true but instead of moving out of the IF construct when the condition is FALSE it now executes another set of instructions before exiting the IF construct. The IF THEN ELSE statement looks as follows:

IF condition THEN

statement(s) when condition is TRUE


ELSE

statement(s) when condition is FALSE


END IF Consider the following program that determines whether a number is positive or negative:

1 2 3 4 5 6 7

DIM number AS INTEGER INPUT Enter Number: ; number IF number > 0 THEN PRINT Positive. ELSE PRINT Negative. END IF

Upon being given any number as input, the boolean expression 'number > 0' gets evaluated and when it is TRUE, the statement between THEN and ELSE is executed 33

and the one between the ELSE and END IF gets skipped and when the condition evaluates to FALSE, the statement between the THEN and the ELSE gets skipped and the one between the ELSE and the END IF gets executed. IF...THEN...ELSEIF....THEN...ELSE...END This variation of the IF construct is used in a situation where we have multiple independent statements to execute, each one depending on it's own condition. Recall that the previous IF...THEN...ELSE...END IF construct has multiple statements but they all depend on one condition. The format is thus:

IF condition1 THEN statement(s)1 ELSEIF condition2 THEN statement(s)2 ELSEIF condition3 THEN statement(s)3 .... ELSE statementDefault END IF where, statementDefault: is to be executed if none of the previous conditions is TRUE. For Example,

34

1 2 3 4 5 6 7 8 9 10 11 12 13 14

DIM AS STRING financialStatus, maritalStatus INPUT Is he Rich or Poor?; financialStatus INPUT Is he Single or Married?; maritalStatus IF financialStatus = Rich AND maritalStatus = Single THEN PRINT Grade 1 Candidate ELSEIF financialStatus = Rich AND maritalStatus= Married THEN PRINT Grade 2 Candidate ELSEIF financialStatus = Poor AND maritalStatus = Single THEN PRINT Grade 3 Candidate ELSEIF financialStatus = Poor AND maritalStatus = Married THEN PRINT Grade 4 Candidate ELSE PRINT Invalid Candidate END IF

Another example:

1 2 3 4 5 6 7 8 9

DIM score AS SINGLE DIM grade AS STRING INPUT Score = ; score IF score <=100 AND score >=70 THEN grade = A ELSEIF score <70 AND score >=60 THEN grade = B ELSEIF score <60 AND score >=50 THEN grade = C 35

10 11 12 13 14 15 16 18 19 20

ELSEIF score <50 AND score >=45 THEN grade = D ELSEIF score <45 AND score >=40 THEN grade = E ELSEIF score <40 THEN grade = F ELSE PRINT Score is out of range. END IF PRINT Grade = ; grade

SELECT CASE construct This construct is the same (but optimised version) in terms of functionality with the IF...THEN...ELSEIF construct. It is also used in executing one instruction out of many depending on multiple conditions. Its format is as follows:

SELECT CASE variable | expression CASE value 1 statement(s)1 CASE value 2 statement(s)2 CASE value 3 statement(s)3 CASE value n 36

statement(s)n CASE ELSE statementDefault END SELECT where, variable | expression: means a variable of any valid data type or an expression whose result is of any valid data type e.g.

SELECT CASE circumference SELECT CASE 2*pi*r

value: is any literal or variable whose value is compared to the variable or expression in the SELECT CASE part. If a match is found then the corresponding statement will be executed otherwise program moves to the next CASE value 2 (and so on until either a match is found or program reaches CASE ELSE which handles all no-match cases).

DIM AS BYTE day INPUT Enter day of the week: ; day SELECT CASE day CASE 1 PRINT Monday CASE 2 PRINT Tuesday CASE 3 37

PRINT Wednesday CASE 4 PRINT Thursday CASE 5 PRINT Friday CASE 6 PRINT Saturday CASE 7 PRINT Sunday CASE ELSE PRINT Invalid Entry END SELECT The CASE part can handle much more than single values. You could check a list of values (separated by commas ',') in one CASE statement thus:

CASE value1, value2, value3,....valueN

{e.g. CASE 2,4,6,8,10}

You could also check a range of values with a minimum and a maximum value thus:

CASE min TO max

{e.g. CASE 0 TO 39} where min is the start of the range and max is the stop.

You could also use it together with any of the Relational Operators thus:

CASE IS operator value

{e.g. CASE IS < 40} where operator is any of Relational Operators.

38

DIM AS BYTE month INPUT Enter month of the year: ; month SELECT CASE month CASE 1,2,3 PRINT First Quarter of the Year CASE 4,5,6 PRINT Second Quarter of the Year CASE 7,8,9 PRINT Third Quarter of the Year CASE 10,11,12 PRINT Fourth Quarter of the Year CASE ELSE PRINT Which planet are you from? Jupiter?! END SELECT The Program for determining Grade based on Score above using SELECT CASE construct will appear thus:

DIM score AS BYTE DIM grade AS STRING INPUT Enter Student Score: ; score SELECT CASE score CASE 0 TO 39 grade = F CASE 40 TO 44

39

grade = E CASE 45 TO 49 grade = D CASE 50 TO 59 grade = C CASE 60 TO 69 grade = B CASE 70 TO 100 grade = A CASE ELSE grade=Invalid END SELECT Another Version:

DIM score AS BYTE DIM grade AS STRING INPUT Enter Student Score: ; score SELECT CASE score CASE IS < 40 grade = F CASE IS < 45 grade = E CASE IS < 50 grade = D CASE IS < 60 40

grade = C CASE IS < 70 grade = B CASE IS < 100 grade = A CASE ELSE grade=Invalid END SELECT

41

S-ar putea să vă placă și