22
Variables and Data Types Higher Computing - Soft Dev - High Level Programming Language Constructs Infosheet 1.1 Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004 A variable is a storage location in the memory of the computer. A variable is usually given a name to make it easy to refer to (meaningful variable names). Data can be stored in a variable at any time during the execution of a program. When variables are created they are normally able to store one particular type of data. A variable cannot normally be used to store data of any type other than the type for which it was created. Data Types To avoid silly mistakes like trying to multiply two letters together, languages tend to classify data into distinct types, and restrict the range of operations which can be performed on any given type. Different data types are used for two reasons. Firstly, each data type is represented differently internally and the compiler or interpreter can tell immediately how much memory to set aside for each one. Secondly, using of data types allows the programmer to validate data and this aids the robustness of the software. There are two main families of data types available to the programmer, simple (or scalar) data types and structured (or complex) data types. Simple Data Types Integer An integer value may be any positive or negative whole number. Examples of integers are: 0, 17, -3, 876 Real The definition of a real value is not so clear cut as the integer. A real value can be any number. In most programming environments, a real value is taken to mean a number with a fractional part. Examples are: 2.0, 3.9, -789.5432 A real number is normally represented internally by the machine as a floating point binary number. Some environments actually name the type 'floating point' to avoid ambiguity. Some environments allow integers to be treated as a subset of real numbers. For example, the number 4, stored as a real number rather than an integer, might be represented by 3.9999999 or 4.0000001 Character A character value is taken to mean any single character, usually from the ASCII character set. Characters are usually differentiated from number values by enclosing them in quotes. Examples of character values might be: a, $,, %, Z Boolean A boolean value is a two-state value. It can either be True or False. This data type is a useful tool for terminating loops and satisfying conditions within a program. Most software development environments provide facilities for storing simple data types such as, integer, real, character and boolean.

Higher High Level Language Constructs

Embed Size (px)

DESCRIPTION

Higher High Level Language Constructs

Citation preview

  • Variables and Data Types

    Higher Computing - Soft Dev - High Level Programming Language Constructs Infosheet 1.1

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    A variable is a storage location in the memory of the computer. A variable is usually given a name to

    make it easy to refer to (meaningful variable names). Data can be stored in a variable at any time during

    the execution of a program.

    When variables are created they are normally able to store one particular type of data. A variable cannot

    normally be used to store data of any type other than the type for which it was created.

    Data Types

    To avoid silly mistakes like trying to multiply two letters together,

    languages tend to classify data into distinct types, and restrict the range of

    operations which can be performed on any given type.

    Different data types are used for two reasons. Firstly, each data type is

    represented differently internally and the compiler or interpreter can tell immediately how much memory

    to set aside for each one. Secondly, using of data types allows the programmer to validate data and this

    aids the robustness of the software.

    There are two main families of data types available to the programmer, simple (or scalar) data types and

    structured (or complex) data types.

    Simple Data Types

    Integer

    An integer value may be any positive or negative whole number. Examples of integers are:

    0, 17, -3, 876

    Real

    The definition of a real value is not so clear cut as the integer. A real value can be any number. In most

    programming environments, a real value is taken to mean a number with a fractional part. Examples are:

    2.0, 3.9, -789.5432

    A real number is normally represented internally by the machine as a floating point

    binary number. Some environments actually name the type 'floating point' to avoid

    ambiguity. Some environments allow integers to be treated as a subset of real numbers.

    For example, the number 4, stored as a real number rather than an integer, might be

    represented by 3.9999999 or 4.0000001

    Character

    A character value is taken to mean any single character, usually from the ASCII character set. Characters

    are usually differentiated from number values by enclosing them in quotes. Examples of character values

    might be:

    a, $,, %, Z

    Boolean

    A boolean value is a two-state value. It can either be True or False. This data type is a useful tool for

    terminating loops and satisfying conditions within a program.

    Most software development environments provide facilities for storing simple data types such as, integer,

    real, character and boolean.

  • Variables and Data Types

    Higher Computing - Soft Dev - High Level Programming Language Constructs Infosheet 1.2

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Structured Data Types

    Structured data types are features of high level programming languages. They are for storing items of data

    that are grouped or structured in a particular way so that you can manage all the data items as one.

    Strings

    A string is a sequence of characters which can include letters, both upper and

    lower case, numbers, punctuation marks etc. The beginning and end of a string

    must be marked with quotation marks e.g. aAb_123. Different languages

    implement strings using single or double quotes.

    Strings can be assigned to variables. Some environments include string as a

    simple type. For example the language BASIC, allows us to group individual characters together and treat

    them as a single item of data.

    Arrays

    Often we use the computer to store and manipulate sets or lists of data. For example we might want to

    search through a list of names for one particular name or sort a group of numbers into an order. An array

    is a data structure which makes it easier to deal with a list of data.

    Using only simple data types we could store a group of five names each in a different variable like this:

    LET name1$ := John

    LET name2$:= Peter

    LET name3$:= Mary

    LET name4$:= "Alex"

    LET name5$: = "Louise"

    In this case, the program is using 5 separate variables name1$, name2$, name3$, name4$ and name5$.

    The program treats 'name1$' as an isolated variable and it does not connect to any other variable even if it

    looks similar.

    The program has no way of knowing that name1 is the 1st item, name2$ is the 2

    nd item, name3$ is the 3

    rd

    and so on. However using an array structure the items can be seen as a list and every item on that list is

    identified in a particular order.

    Arrays can be declared as any data type. In the example above the array would be declared as string. So

    the data could be declared as:

    Array data is usually stored internally in a contiguous set of storage locations.

    An array is a set of data all sharing the same variable name which can be

    accessed by means of a subscript. This subscript identifies the position of the

    element within the array. Subscripted variables allow the programmer to loop

    through the variables in the array by changing the subscript. They cut down the

    number of variable names needed in a program. And hence make the program

    more efficient.

    An array therefore is a list used to 'hold' data values. The data values could be real numbers, integers,

    characters, strings etc.

  • Variables and Data Types

    Higher Computing - Soft Dev - High Level Programming Language Constructs Infosheet 1.3

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Using the example above this diagram represents the array called name, with space for 5 data items or

    elements:

    Subscript 1 2 3 4 5

    name

    Each element of the array can be referred to using the array name with the subscript in brackets after the

    name.

    Example

    name$(1)= John

    This will assign the string John to array element at position 1 of the array called name i.e.

    Subscript 1 2 3 4 5

    name John

    The other elements in the array could also be assigned depending on the data values they had to store.

    Using the example:

    name$(2) = Peter

    name$(3)= Mary

    name$(4) = Alex

    name$(5)= Louise

    This will assign the string Peter to variable number 2 of the array called name, Mary to variable

    number 3 of the array called name etc .

    Subscript 1 2 3 4 5

    name John Peter Mary Alex Louise

    Each variable in an array can be treated in exactly the same manner as a single variable. It can be assigned

    a value, the value can be altered, printed out, and used in a program statement.

    This type of array is called a one dimensional array. Arrays with more than one subscript can be used.

    For example a two dimensional array would have two subscripts etc. Using the example below:

    name$(1,1) = Susan, name$(1,2) = Peter, name$(1,3)= Margaret, name$(2,1)= Sarah, etc.

    Two dimensional array

    1

    2

    3

    1 2 3

    Susan Peter Margaret

    Sarah Careywyn Calum

    Tara James Murdina

  • Subprograms, Variables and Parameters

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 2.1

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Types Of Subprograms

    Subprograms are used by programmers to give modularity to programs. In other words the program is

    broken up into smaller parts using these subprograms. There are generally two kinds of subprograms,

    procedures (or subroutines) and user-defined functions. Procedures and user-defined functions are a

    series of instructions within the program that have been given a name and can be called at any time within

    the program code. The difference between a procedure and a user-defined function is that a procedure

    produces an effect, whereas a user-defined function produces a value. In practice, knowing which to use,

    usually comes down to a mixture of experience and personal preference.

    Calling Subprograms Into Action

    The sequence in which subprograms are carried out is decided by the control structures used in the

    program itself. It is normal to have a top level algorithm which controls the execution of the subprograms.

    This is sometimes called the control module or main program.

    Using Variables Within A Program

    Some languages allow variables to be set up at any point in a program other

    languages need variables to be declared at the start of a program before they

    are used within the program. This allows the translator program to reserve

    suitable areas of memory to hold the data structures which will subsequently be

    used by the program. The declaration of variables also serves as a discipline to

    programmers because they have to create a list which details the name, type, and

    purpose of each variable used in their program. There are two different types of variables one that is

    used throughout the whole program and one that is restricted to a subprogram.

    Local Variables

    Local variables are variables which exist only within a subprogram. They are created

    when the subprogram is called or invoked, and are destroyed when the subprogram

    terminates. They cannot be accessed or assigned a value except within that subprogram.

    Local variables are safer to use because they avoid potential conflict between a

    subprogram and the calling program.

    Global Variables

    Global variables are variables which can be accessed and altered from any part of a

    program including subprograms. They should always be used with care, their values

    should not be changed or they should not be used within subprograms if at all possible.

    So the use of global variables should be avoided where possible, as there is a danger that

    their values may be reassigned accidentally.

    A variable can store many different types of data. When assigned, a variable cannot change its data type.

    Data Flow Through Parameter Passing

    Data flow within a program is handled by parameters. A parameter is a variable or value that is passed

    into, or out from, a subprogram. If a subprogram is defined in such a way that it only uses local variables

    or values passed to it as parameters then this can be of benefit as:

    it is unlikely to change accidentally the value of variables used elsewhere in the program

    the subprogram can also be used elsewhere if it is completely self-contained

    the use of parameters to pass information to and from a subroutine improves the generality of a

    subprogram and is likely help the reliability and robustness of the program as a whole.

  • Subprograms, Variables and Parameters

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 2.2

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    The parameters which are passed into a subprogram when it is called from another part of the program are

    called the actual parameters. The parameters which are used in the subprogram definition are called the

    formal parameters.

    Passing Parameters By Value And By Reference

    There are two methods of passing formal parameters: by reference and by value. Some programming

    languages such as Pascal use different syntax for each of these.

    Parameter passing by reference is used when the value being passed in can be updated and passed back

    out again. This means that the data that entered the subprogram could leave with a different value. The

    program uses the memory address of where the parameter is stored as its reference. So any updating of

    the value within the subprogram would ensure that the changes would be made to the parameter before it

    left the subprogram.

    Parameter passing by value is used when a value is passed in to a subroutine but does not require to be

    passed out. This means that the data that entered the subprogram would leave with the same value that it

    entered with. In order to achieve this, the program makes a second copy of the parameter and uses that

    copy when the subprogram is executed. This ensures that the original is not changed. Passing by value is

    not used for large data structures such as arrays as that would be very inefficient i.e. unnecessary RAM

    could be taken up storing the second copy. So in this case, the need for efficiency is more important than

    the need for good design. So all arrays are passed by reference to subprograms.

    Examples

    Using Pascal, the syntax is different for each:

    procedure calculate(var area :real) the var indicates that the parameter area is passed by

    reference

    procedure calculate(area :real) no var command indicates that the parameter area is

    passed by value

    Using TrueBasic, the syntax is also different for each:

    CALL calculate(length,breadth) the single brackets makes this call passing by reference

    CALL calculate((length),(breadth)) the double brackets makes this call passing by value

    Scope

    The scope of a variable is the parts of the program it can be used in. For example if a variable is declared

    within a subprogram then it can only be used with the code within that routine. This will be the variables

    scope. A variable cannot be used outwith its scope. This enables variables with the same name to be

    used in different parts of a program without causes problems with reassignment.

    This concept is useful when large programs are being constructed with various programmers working on

    separate modules. It prevents conflict between variables happening when the complete system (all

    modules) is run together.

  • Using Algorithms

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 3.1

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Most software development environments provide a fairly standard set of facilities. These facilities are

    for storing data, for exercising control over the execution of a program, and for passing data from one

    program or part of a program to another.

    Before a program is can be written though, an algorithm must be determined. An algorithm is the

    detailed sequence of operations to be performed to solve the problem. Often there may be several

    alternative algorithms for a problem and the program designer must select the most efficient algorithm for

    the circumstances of the problem.

    Pseudocode

    Pseudocode is a cross between a programming language and English. It is sufficiently like English to

    allow the programmer to concentrate initially on the program design without worrying about the

    complexities of the programming language. However pseudocode does contain enough programming

    language features to code the finished design quickly in the chosen program language. The lines in a

    pseudocode algorithm should in theory have a one-to-one mapping with the actual code. Although the

    description can be easily converted into high level language code, pseudocode is not simply a set of

    language statements.

    A top-down design approach should be used when producing an algorithm. This involves splitting the

    overall problem into smaller tasks. This allows the problem to be understood and ensure elements are not

    missed out. Stepwise refinement involves splitting these smaller tasks into even smaller ones until they

    are more manageable and therefore easier to be understood and solved.

    Example

    Typical pseudocode for a program has to be written to find the average of a set of data items.

    Program Inputs: data

    Program Outputs: average

    Algorithm 1 initialise variables (out: total, count)

    2 work out average (in: total, count out: average)

    3 print the average of the data set (in: average)

    Refine step 1 1.1 initialise the total and count of data items to zero

    Refine step 2 2.1 get the first data item

    2.2 while there are more data items do

    2.3 add data item to total

    2.4 increment the count of data items

    2.5 endwhile

    2.6 divide the total by the count of data items

    When writing pseudocode it is important to use indentation and keywords to represent the design

    structure. Every program should be broken down into modules and then each module should be described

    and again broken down fully. This shows the top-down design and stepwise refinement. The data flow

    should also be indicated to show what parameters are being passed in and out of each refinement.

    The algorithm will be a one-to-one mapping with the main program or control module of the code. The

    refinements should indicate the number of subprograms that will be used, what parameters are being used

    and whether they are passed by reference or by value i.e. in would be value parameters and out or in/out

    would be reference parameters.

  • Using Algorithms

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 3.2

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Flowcharts

    A flowchart is often used to illustrate an algorithm (set of instructions) to solve a problem. A flowchart is

    a diagram that uses different shapes and arrows to show the steps in a problem solution. Particular box

    shapes are used to represent different aspects of coding. A flow chart is an example of a graphical design

    notation.

    Using the same example, but with flowcharts this time:

    Example

    A program has to be written to find the average of a set of data items.

    A typical flowchart for this problem could be:

    Add value to total

    Initialise

    variables

    Add 1 to count

    Calculate average

    Start

    Get first value

    Anymore

    values?

    Print out average

    Stop

    Yes

    No

  • Using Algorithms

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 3.3

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Structure Diagram

    A structure diagram shows the different sections of the program. It is a treelike diagram, representing

    component modules and their interrelationships. It also shows the hierarchy of each module. A structure

    diagram is another example of a graphical design notation.

    Using the same example , but with structure diagrams this time:

    Example

    A program has to be written to find the average of a set of data items.

    A typical structure diagram for this problem could be:

    Notes about structure diagrams

    The box at the top describes what the whole program does.

    The boxes below are arranged in logical order from left to right.

    Each box shows a different section of the program.

    The box with a double line at each side shows a subroutine or procedure.

    The flow of data may be indicated by an arrow labeled with the data name.

    Finding the average of aset of data values

    Get first data

    values

    Repeat until no

    more data valuesCalculate average Print average

    Add data item tototal

    Add 1 to count

  • Simple Selection

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 4.1

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    A simple selection (or conditional statement) allows the programmer to let the program select which of

    two different sets of steps to do next. The general form of the IF.THEN.END IF is:

    IF condition is true THEN

    the program performs sequence of instructions

    ELSE the condition is false

    the program follows another sequence of instructions

    END IF

    Example 2.1

    This example is part of an input validation routine - it is checking to see whether the data entered at the

    keyboard is valid. In this example it is validating an age by checking it is not a negative number.

    Algorithm

    1. get age of user

    2. if age less than 0 then

    3. display suitable error message

    4. end if

    Notice that there is no 'ELSE' in this one - if a suitable age is entered, there is no need for any further

    action so the program simply continues with whatever comes next in the sequence. Note also that lower

    case is used for the keywords in the pseudocode.

    Program

    PRINT "How old are you"

    INPUT age

    IF age 100 then

    3. display suitable error message

    4. End If

    Program

    PRINT "How old are you"

    INPUT age

    IF age100 THEN

    PRINT "Too old - please re-enter"

    END IF

  • Simple Selection

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 4.2

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Example 2.3:- This example is part of a payroll program for calculating wages. The employee earns 5.65

    an hour. Any hours worked in excess of 40 are paid at the overtime rate of time and a half. Notice that

    there are two steps being executed between the IF and END IF.

    Algorithm 1. ask user for number of hours

    2. ask user for rate of pay

    3. calculate wages

    4. display wages

    refine step 1 1.1 ask user for number of hours worked

    1.2 store response in hours

    refine step 2 2.1 ask user for rate of pay

    2.2 store response in rate

    refine step 3 3.1 if hours greater than 40

    3.2 calculate overtime using (hours-40)

    3.3 calculate wages using (40 x rate)+(overtime x 1.5 x rate)

    3.4 else

    3.5 calculate wages using (hours x rate)

    3.6 end if

    Program

    CALL get_hours_routine(hours)

    CALL get_rate_routine(rate)

    CALL calculatewages((hours),(rate),wages)

    CALL display_wages(wages)

    END

    SUB get_hours_routine(hours)

    PRINTPlease enter the hours worked this week-;

    INPUT hours

    END SUB

    SUB get_rate_routine(rate)

    PRINTPlease enter the rate of pay-;

    INPUT rate

    END SUB

    SUB calculatewages((hours(,(rate),wages)

    IF hours>40 THEN

    LET overtime=hours-40

    LET wages=40* rate + 1.5*overtime* rate

    ELSE

    LET wages=hours*rate

    END IF

    END SUB

    SUB display_wages(wages)

    PRINTYour wages are - ;wages

    END SUB

  • Multiple Outcome Selection

    Higher Computing - Soft Dev HLL Language Constructs Infosheet 4.3

    Produced by S Lambert, R Simpson and HSDU for Drummond Community High School Computing Department 2004

    Often when producing a solution to a problem there are not just two alternatives as in the previous

    example but many. This is sometimes known as multiway selection and can normally be accomplished in

    one of two ways. One way uses the IF structure from the previous examples and the other uses a CASE

    structure which is specially designed to deal with multiple outcome selection.

    Example 3.1

    This example uses nested IFs to calculate the grade which corresponds to a student mark.

    Algorithm

    1. get mark from user

    2. if mark from 70 to 100

    3. set grade to A

    4. elseif mark from 60 to 69

    5. set grade to B

    6. elseif mark from 50 to 59

    7. set grade to C

    8. elseif mark from 40 to 49

    9. set grade to D

    10. else

    11. set grade to FAIL

    12. end if

    13. end if

    14. end if

    15. end if

    16. endif

    Program

    SUB Getgrade

    INPUT mark

    IF mark>69 THEN

    Pass$="A"

    ELSE

    IF mark>59 THEN

    Pass$="B"

    ELSE

    IF MARK>49 THEN

    PASS$="C"

    ELSE

    IF MARK>40 THEN

    PASS$="D"

    ELSE

    PASS$="FAIL"

    END IF

    END IF

    END IF

    END IF

    END SUB

  • Multiple Outcome Selection

    Higher Computing - Soft Dev HLL Language Constructs Infosheet 4.4

    Produced by S Lambert, R Simpson and HSDU for Drummond Community High School Computing Department 2004

    CASE Structure

    Another variation of the selection algorithm allows the programmer to select one action or a set of

    actions, when one particular condition is true. This is called a CASE structure. You will find that

    different languages implement this structure in significantly different ways.

    Example 3.2

    This example uses CASE to calculate the grade which corresponds to a student mark.

    Algorithm

    1. get mark from user

    2. select case mark

    3. when from 70 to 100 set grade to A

    4. when from 60 to 69 set grade to B

    5. when from 50 to 59 set grade to C

    6. when from 40 to 49 set grade to D

    7. when from 0 to 39 set grade to FAIL

    8. end select

    Refine 1

    1.1 ask user for mark

    1.2 store mark

    Program

    SUB Getgrade

    INPUT mark

    SELECT CASE mark

    CASE 70 TO 100

    Pass$="A"

    CASE 60 TO 69

    Pass$="B"

    CASE 50 TO 59

    Pass$="C"

    CASE 0 TO 49

    Pass$="Fail"

    END SELECT

    END SUB

  • Repetition

    Higher Computing - Soft dev High Level Language Constructs Infosheet 5.1

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    It is often required that a part of a program be repeated several times. A section of program which is

    repeated is called a loop. The loop structure is a sequence of instructions which is repeated zero or more

    times. There are several loop routines for repeating a section of a program.

    Fixed Loop (Unconditional Loop)

    A fixed loop is a structure in which the programmer sets the number of times a loop must be repeated.

    The loop structure usually has a counter variable which is incremented each time a loop is executed. The

    general form is shown below:

    FOR counter = start value to finish value step stepsize

    execute commands

    NEXT counter

    Example 4.1:- This example shows the fixed loop at its simplest. The words Hello World are displayed

    10 times.

    Algorithm 1. loop 10 times (use index)

    2. display the message

    3. end loop

    Program FOR nooftimes= 1 TO 10 STEP 1

    PRINT "Hello World"

    NEXT nooftimes

    Example 4.2:- One of the most useful aspects of a loop, is the ability to make use of the loop counter

    variable. In this example, the square of the numbers from 5 to 10 will be calculated and displayed.

    Algorithm 1. loop from 5 to 10 (use counter)

    2. calculate square using counter * counter

    3. display square

    4. end loop

    Program FOR numbers= 5 TO 10 STEP 1

    LET square = numbers * numbers

    PRINT "The square of the number "; numbers; " is "; square

    NEXT numbers

    Example 4.3:- In this example the odd numbers from 1 to 9 are printed.

    Algorithm 1. loop from 1 to 9 in steps of 2

    2. display number

    3. end loop

    Program FOR oddnumbers= 1 TO 9 STEP 2

    PRINT "The number is "; oddnumbers

    NEXT oddnumbers

    Just as the conditional statement IF can be nested, so loops can be nested, i.e. loops can contain loops.

  • Repetition

    Higher Computing - Soft dev High Level Language Constructs Infosheet 5.2

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Example 4.4

    In this example we are going to compare 3 numbers inputted by the user with 5 numbers generated by the

    computer. This uses a nested loop to compare the user numbers against all the computer numbers.

    Algorithm 1. get user numbers

    2. get computer numbers

    3. Compare user numbers with computer numbers

    4. display number of winners

    refine 3.1 loop 3 times

    3.2 loop 5 times

    3.3 if computeno = userno then

    3.4 increase winners by 1

    3.5 end if

    3.6 end loop

    3.7 end loop

    Program DIM userno(3), computerno(5)

    CALL get_user_nos(userno())

    CALL get_computer_nos(computerno())

    CALL compare_numbers(userno(),computerno(),winners)

    CALL display_winning_numbers(winners)

    END

    SUB get_user_nos(userno())

    FOR counter=1 TO 3 STEP 1

    PRINT "Please type in number ";counter

    INPUT userno(counter)

    NEXT counter

    END SUB

    SUB get_computer_nos(computerno())

    FOR counter = 1 TO 5 STEP 1

    LET Compterno(counter) = INT(RND * 100) + 1

    NEXT counter

    END SUB

    SUB compare_numbers(userno(),computerno(),winners)

    LET winners=0

    FOR usercounter = 1 TO 3 STEP 1

    FOR computer counter= 1 TO 5 STEP 1

    IF userno(Usercounter)=computerno(computercounter) THEN

    LET winners=winners+1

    END IF

    NEXT computercounter

    NEXT usercounter

    END SUB

    SUB display_winning_numbers(winners)

    PRINT"The number of winning numbers is ";winners

    END SUB

  • Repetition

    Higher Computing - Soft dev High Level Language Constructs Infosheet 5.3

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Conditional Loops

    The fixed loop is limited in that the programmer has to know in advance how many times the program has

    to go round the loop. The conditional loop is a more flexible loop structure and is used when the number

    of times a section of program is repeated is not known beforehand, and depends on a certain condition

    being met. There are two kinds of conditional loop, one with the condition at the end of the loop, the

    other with the condition at the start of the loop.

    DO .. LOOP WHILE (In some languages REPEAT .. UNTIL)

    The DO .. LOOP WHILE structure is a conditional loop in which the condition comes at the end of the

    loop. The general structure of a do..until loop is shown below.

    DO

    execute commands

    LOOP WHILE some condition is true

    Notice that in this structure, the condition is at the end of the loop. This means that the steps inside the

    loop must be executed at least once.

    Example 4.5:- This algorithm makes use of a sentinel value. A sentinel value is used to tell the loop

    when to stop. In this example the sentinel value is the string 'banana'. This program will keep asking for

    name until Banana is entered.

    Algorithm

    1. start loop

    2. get password

    3. until the password is Banana

    Program DO

    PRINT"Please enter the correct password"

    INPUT password$

    LOOP WHILE password$"Banana"

    Example4.6

    This example is the same as the one above except it mixes conditional and unconditional repetition by

    only allowing 3 attempts.

    Algorithm 1. set counter to 0

    2. start loop

    3. add 1 to counter

    4. get password

    5. until counter = 3 OR password is banana

    6. display total

    Program LET counter=0

    DO

    LET counter=counter+1

    PRINT"Please enter the correct password"

    INPUT password$

    LOOP WHILE password$"Banana" AND counter3

  • Repetition

    Higher Computing - Soft dev High Level Language Constructs Infosheet 5.4

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Example 4.7

    This is an example of a standard routine which checks that a number entered is within a given range. This

    type of loop is called an input validation loop.

    Algorithm 1 start loop

    2 display suitable message

    3 get number and store in get_number

    4 if number less than 1 or greater than 10

    5 display error message

    6 end if

    7 until number is one from 1 to 10

    Program DO

    PRINT "Please type in a number between 1 and 10"

    INPUT number

    IF number10 THEN

    PRINT "This number is not acceptable"

    END IF

    LOOP WHILE number10

    DO WHILE Loop

    A DO..WHILE loop structure is similar to the DO loop but it depends on the condition being true

    before the loop is executed.

    Whereas the DO loop must be executed at least once, a DO WHILE loop may never be executed as the

    program is able to by-pass it, if the initial condition is false.

    The general structure of a DO WHILE loop is shown below:

    DO WHILE some condition is true

    The program performs sequence of instructions

    LOOP

    Example 4.8

    This algorithm makes use of a sentinel value. The sentinel value is used to tell the loop when to stop. In

    this example the sentinel value is the string 'STOP'. This program will keep asking and storing names

    until STOP is entered.

    Algorithm 1. get password

    2. loop as long as name is not banana

    3. display error message

    4. get password

    5. end loop

    Program INPUT password$

    DO WHILE password$"Banana"

    PRINT"Wrong password try again"

    INPUT password$

    LOOP

  • Manipulating Data Structures

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 6.1

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Arrays allow programs to store lots of data. Loops give programs the power to manipulate this data.

    There are a range of common operations that may be performed on array data types. These include:

    accessing a data item held in an array searching for a particular item in an array finding the maximum or minimum item in an array counting the occurrences of an item in an array sorting an array

    Example 5.1 To find the maximum value in an array

    Algorithm 1. get information of array

    2. find maximum number in array

    3. display maximum number

    Refine 1 2.1 set largest to first value

    2.2 start loop

    2.3 increment array index by 1

    2.4 if value of next array element is greater than largest value then

    2.5 set largest value to value of next array element

    2.6 end if

    2.7 until all array values examined

    Program

    DIM mark(10), name$(10)

    CALL get_info(mark(),name$())

    CALL Find_largest(largest,position,mark())

    CALL print_largest(largest,name$(), position)

    END

    SUB get_info(mark(),name$())

    FOR number= 1 TO 10 STEP 1

    READ name$(number, mark(number)

    NEXT number

    DATA "john",23,"susan",34,"alice",45,"ben",87,"peter",96,"Andrew",45,"Linda",34, DATA"john",24,"susan",34,"alice",45,"ben",87,"peter",96,"andrew",45,"linda",34,

    "louise",61,"Claire",72,"Mike",50

    END SUB

    SUB Find_largest(largest,position,mark())

    LET largest=mark(1)

    FOR numbers= 2 TO 10 STEP 1

    IF mark(numbers) > largest THEN

    LET largest = mark(numbers)

    LET position=numbers

    END IF

    NEXT numbers

    END SUB

    SUB print_largest(largest,name$(), position)

    PRINT" The largest mark is"; largest;" by ";name$(position)

    END SUB

  • Manipulating Data Structures

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 6.2

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Example 5.2 To find the minimum value in an array

    Algorithm

    1. get information of array

    2. find minimum number in array

    3. display minimum number

    Refine 1

    2.1 set smallest to first value

    2.2 start loop

    2.3 increment array index by 1

    2.4 if value of next array element is smaller than smallest value then

    2.5 set smallest value to value of next array element

    2.6 end if

    2.7 until all array values examined

    Program

    DIM mark(10), name$(10)

    CALL get_info(mark(),name$())

    CALL Find_smallest(smallest,position,mark())

    CALL print_ smallest (smallest,name$(), position)

    END

    SUB get_info(mark(),name$())

    FOR number= 1 TO 10 STEP 1

    READ name$(number)

    READ mark(number)

    NEXT number

    DATA "john",23,"susan",34,"alice",45,"ben",87,"peter",96,"Andrew",45,"Linda",34, DATA"john",24,"susan",34,"alice",45,"ben",87,"peter",96,"andrew",45,"linda",34,

    "louise",61,"Claire",72,"Mike",50

    END SUB

    SUB Find_ smallest (smallest,position,mark())

    LET smallest =mark(1)

    FOR numbers= 2 TO 10 STEP 1

    IF mark(numbers) < smallest THEN

    LET smallest = mark(numbers)

    LET position=numbers

    END IF

    NEXT numbers

    END SUB

    SUB print_ smallest (smallest,name$(), position)

    PRINT" The smallest mark is"; smallest;" by ";name$(position)

    END SUB

  • Manipulating Data Structures

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 6.3

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Example 5.3 Counting Occurrences

    Three numbers are used to represent votes for different candidates. This program will count how often they occur.

    Algorithm

    1 get votes out - noofvotes

    2 count occurrences in - noovotes out - vote1, vote2

    3 display number of occurrence found in - vote1, vote2

    Refine 1

    1.1 set counter to 1

    1.2 start loop

    1.3 get and store value

    1.4 increase counter by 1

    1.5 end loop while value =0

    Refine 2

    2.1 loop number of votes

    2.2 if value of array element = 1then

    2.3 add 1 to occurrences of 1

    2.4 else

    2.5 add 1 to occurrences of 2

    2.6 end if

    2.7 end loop

    Program

    DIM vote(100)

    CALL get_info(vote(),counter)

    CALL addvotes(vote(),counter,bush,blair)

    CALL print_totals(bush,blair)

    END

    SUB get_info(vote(),counter)

    LET counter=1

    DO

    READ vote(counter)

    LET counter=counter+1

    LOOP WHILE vote(counter-1)0

    DATA 1,2,1,1,2,1,2,1,2,1,2,2,2,1,2,1,2,1,2,1,2,1,2,2,2,1,1,2,1,1,2,1,2,1,1,1,1,2,1,2,0

    END SUB

    SUB addvotes(vote(),counter,bush,blair)

    FOR totalvotes=1 TO counter-1 STEP 1

    IF vote(totalvotes)=1 THEN

    LET bush=bush + 1

    ELSE

    LET blair=blair + 1

    END IF

    NEXT totalvotes

    END SUB

    SUB print_totals(bush,blair)

    PRINT "Bush has ";bush;" votes"

    PRINT "Blair has ";blair;" votes"

    END SUB

  • Manipulating Data Structures

    Higher Computing - Soft Dev High Level Language Constructs Infosheet 6.4

    Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

    Example 5.4 Linear Search To find out if a number is in an array.

    Algorithm

    1. search array for value

    2. display position in array

    3.

    Refine 1

    1.1 set found to be false

    1.2 set array index to 0

    1.3 ask user for value to be found in list

    1.4 get and store value

    1.5 start loop

    1.6 add 1 to index

    1.7 ask user for next value in list

    1.8 get and store array value

    1.9 if array element = number_to_be_found

    1.10 set found to true

    1.11 end if

    1.12 until found = true or all elements are compared

    Program

    DIM Name$(10), Mark(10)

    CALL get_array-values(name$(),mark())

    CALL get_name(soughtname$)

    CALL search(soughtname$,Name$())

    SUB get_array_values(name$(),mark())

    FOR noofnames=1 TO 10 STEP 1

    READ name$(noofnames), mark(noofnames)

    NEXT noofnames

    DATA "john",23,"susan",34,"alice",45,"ben",87,"peter",96,"Andrew",45,"Linda",34, DATA"john",24,"susan",34,"alice",45,"ben",87,"peter",96,"andrew",45,"linda",34,

    "louise",61,"Claire",72,"Mike",50

    SUB get_name(soughtname$)

    PRINT"What name are you after?"

    INPUT soughtname$

    END SUB

    SUB search(soughtname$,Name$())

    LET found$="NO"

    LET namesearch=1

    DO

    IF Name$(namesearch)=soughtname$ THEN

    Found$="YES"

    Indexmark=namesearch

    END IF

    LET namesearch=namesearch+1

    LOOP WHILE namesearch11 OR found$="NO"

    IF found$="YES" THEN

    PRINT soughtname$; " has been found at position ";indexmark

    ELSE

    PRINT"This name is not in the list"

    END IF

    END SUB

  • String Operations

    Higher Computing - Soft dev High Level Language Constructs Infosheet 7.1

    Produced by S Lambert, R Simpson and HSDU for The City of 2004

    Variables that have been declared as a string data type are seen as a sequence of characters by

    programming languages. Hence the string data type is structured. Strings can be manipulated using

    different techniques within programming languages.

    Programming languages also provide the functions for handling and manipulating strings. In True Basic

    the following can be used:

    CONCATENATION - & Joins two or more strings.

    Let number$ = one, test $= computing, and date$ = 24/12

    number$ & test$ & date$= onecomputing24/12

    Example 6.1 Concatenation Of Two Strings

    This program will ask the user for a name and age and then construct a code using the name and age.

    Algorithm

    1. ask user for first name

    2. ask user for age

    3. make code of first name and age

    4. display code to user

    Program

    PRINT "What is your name"

    INPUT name$

    PRINT "What is your age"

    INPUT age$

    LET password$=name$ & age$

    PRINT "Your password is ";password$

    LENGTH - LEN (String) - returns an integer which represents the number of characters of a string.

    If exam$ = higher then len (exam$) = 6

    Example 6.2 Length of String

    This program will check that a users password has at least 6 characters.

    Algorithm

    1. get and store password

    2. calculate length of password

    3. valid password

    Program

    Print "What is your new password"

    INPUT password$

    LET passlength=LEN(password$)

    IF passlength < 6 THEN

    PRINT "Password must be at least 6 characters"

    ELSE

    PRINT "password accepted"

    END IF

  • String Operations

    Higher Computing - Soft dev High Level Language Constructs Infosheet 7.2

    Produced by S Lambert, R Simpson and HSDU for The City of 2004

    SELECTING CHARACTERS

    It is possible to select a number of characters in a string in the following manner.

    LET x$="abcdefghijk"

    LET y$=x$[2:5]

    PRINT y$ output - "bcde"

    Example 6.3 Input Validation Of Each Character Of A String

    This program will ask the user for a name and validate that each character is either a to z.

    Algorithm 1. get and store name {out : name}

    2. check characters of name are valid {in/out : name, in/out : ch}

    3. display name {in : name}

    Refine 2 3.1 repeat

    3.2 set error to NO

    3.3 ask for name

    3.4 calculate length of name

    3.5 Repeat for each character

    3.6 if name is less than a or greater than z

    3.7 set error to YES

    3.8 end if

    3.9 end loop

    3.10 if error is set to YES

    3.11 print invalid message

    3.12 end if

    3.13 until error is NO

    Program

    DO

    error$="NO"

    PRINT"what is your name"

    INPUT name$

    LET lengthofword=LEN(name$)

    FOR noofcharacter=1 TO lengthofword STEP 1

    IF name$[noofcharacter:noofcharacter]z THEN LET error$="YES"

    END IF

    NEXT noofcharacter

    IF error$="YES" THEN

    PRINT" This name is invalid please type it again !"

    END IF

    LOOP WHILE error$="YES"