Home

Chapter 3 THE REPRESENTATION OF PROCESSING

image

Contents

1. End If Each condition s Then true branch If one of operations includes a sentences keyword is followed by one or more VB sequence then this sequence will be included statements that are processed if the ina sentence block condition evaluates to True Each condition s Else false branch operation keyword is followed by one or more statements that are processed if the condition evaluates to False PASCAL If condition Then If one of operations includes a sentences operation sequence then this sequence will be included Else in a sentence block operation2 Begin operation End Example We design the logical flowcharts figure 3 10 and the corresponding procedures to determine the min value Min x y and max value Max x y from two values passed in arguments return Max Figure 3 10 A description of min and max algorithms for any kind of data type values 108 THE REPRESENTATION OF PROCESSING ALGORITHMS An implementation of Min and Max Function Min x As Variant y As Variant Function Max x As Variant y As Variant As Variant Ifx gt y Then Min y Else Min x As Variant Ifx lt y Then Max y Else Max x End If End If End Function End Function It is possible do not have a specific operation on the two branches that mean situations as depicted in figure 3 11 If the condition is true then the set of sentences placed between If and End If are executed Th
2. The user defined data type is formed by placing the needed declarative sentences Type block For example if we want represent the structure of a row from the Balance_Sheet the Romanian one this can be declared by the user as follows Type Balance_Sheet_Row Dim Account_ID As String 22 Dim Account_Description As String 60 Dim Db_Jan As Double Dim Cr_Jan As Double Dim Db_Prev As Double Dim Cr_Prev As Double Dim Db_Month As Double Dim Cr_ Month As Double End Type After declaration a user defined data type can be used in the same way VB data type used For our example we can define a memory variable that we call Current_Row thus Dim Current_Row As Balance_Sheet_Row The declaration of references must contain instantiation such as Dim aReferenceToAnObject As Object New Object For strings you don t have to use new if a literal assigned 102 THE REPRESENTATION OF PROCESSING ALGORITHMS Dim aNullString as String A string instance that is initialized with a character repeated a number of times suppose 20 stars Dim starValue As String New String c 20 Such declarations can be split in two parts declaration and assignment as in the example Dim starValue As String starValue New String c 20 Constants can appear as such anywhere as literals intrinsic constants available in the Visual Basic programming environment or in other Windows applications or as declarations in the declarative part of the program
3. Fori 1 Ton pow pow x Next i Power pow End Function b The function Power exponentiation a number x to a power n compact Function Power x As Variant n As Integer As Double Power 1 Fori 1Ton Power Power x Next i End Function HI We want to solve now a more complex problem we want to list a Fahrenheit to Celsius correspondence table based on the computation formula CELSIUS 5 9 FAHRENHEIT 32 The correspondence table will be displayed figure 3 22 starting with the minimal value min 0 zero and ending with the maximal value max of 300 degrees and the computation and display will be done from 20 to 20 degrees pas We use to solve this problem assignments instructions the function MsgBox to display the result and an instruction For that allow us to repeat the execution of a group of sentences until a specified condition satisfied INFORMATICS Computer Hardware and Programming in Visual Basic 127 The program looks as Sub Coresp_Temp Dim min max pas fahrenheit celsius tabel Computation of the correspondence C F min 0 Starting Value max 300 Ending Value pas 20 From to degrees tabel Fahrenheit Celsius amp Chr 13 amp Chr 10 amp _ String 36 amp Chr 13 amp Chr 10 For fahrenheit min To max Step pas celsius 5 9 fahrenheit 32 tabel tabel amp Right Space 12 amp Format fahrenheit 000 12 amp _ amp Righ
4. allows you to make certain that formulas and calculations are included in the instructions to the programmer Pseudocode The statements in the flowchart can be extracted from it and listed in order They form in this way the basis for pseudocode Pseudocode is a set of succinct instructions to the programmer using some of the syntax of the language in which the application will be programmed INFORMATICS Computer Hardware and Programming in Visual Basic 91 The Basic Symbols Used in Drawing Program Flowcharts The symbols used for building logical diagrams program flowcharts are shown in the table 3 1 Table 3 1 Symbols used in Drawing Program Flowcharts Terminal Interrupt Start Stop It marks the START and the STOP of the logical diagram and or the beginning and ending of a procedure function subroutine Inside is written case usage dependent either the word START STOP for main programs or the call model for the procedure function or subroutine Process Calculation Block It is used for representing calculus formula changes of the index values assigning of values Inside are written the expressions of that operations Procedure A call to another process or procedure Inside is written the name of the procedure followed by the list of parameters in the order as specified in the call model Decision Block It is used for the passing in different points of the diagram depending on the true state or false state of a logic
5. gt O10 The sum of all marks from the table is computed by adding the value Mark to the sum obtained by adding the previous values by following the way after each adding operation we obtain a subtotal to which the next value is added The computation program can be Sub Average_Marks Dim Mark 5 11 i As Integer j As Integer Rem the definition of the table in i eee Aa aie i Exemple Dim Average As Double Name As Variant CH entiiEmilGRnsreninesce Read_Marks Name Mark are media generala 5 75 Average 0 Fori 1To5 For j 1To 10 Average Average Average i j Next j An output sample Next i Average Average 10 5 MsgBox Studentul amp Name amp Chr 13 amp Chr 10 amp are media generala amp Average End Sub In the table Mark we must fill in each cell called element the obtained Mark We fill the marks by reading them from a file where previously stored or from the keyboard The table defined by the sentence Dim Mark 5 10 is called usually matrix bidimensional array or bidimensional massive In this example the procedure Read_ Marks is defined as follows Sub Read_Marks Name As Variant Mark As Variant Name InputBox First Name amp Last Name Example of using VB Fori 1To5 For j 1To 10 Mark i j InputBox Name amp Name amp Chr 13 amp Chr 10 amp _ Mark amp i amp amp j amp Example of using VB Marks Input Next j Next i End Sub In this example w
6. with the content of the variable named y The variables x and y from the name of the procedure Exchange x y are called arguments and the real actual values for these are passed to the procedure at call time The call is realized in almost algorithmic programming languages as C Visual Basic Pascal etc by writing the name of the procedure followed by the list of the arguments The call Exchange x y means applying the operations included in the procedure body to the content of variables x and y In the computation block from the figure 3 3 the numbered line means 1 the content of variable x is stored in a temporary Exchange x y working variable called temp 2 the content of variable x is overwritten by the content of variable y first is deleted and after deletion the content of y is copied 3 the content of y is overwritten by those of the variable temp it contains the value of x as passed at the call time The new values of x and y are returned to the caller Return x y For example the call Exchange 3 2 j realizes the operations Figure 3 3 The representation temp 3 of Exchange operation x 2 y 3 the temp content And returns 2 3 Some programming languages describes in the syntax of the call model the return parameters and the usage sense IN OUT IN OUT together with the accepted data type Integer Single Double String etc 3 2 1 Assignments The assignments are represented in t
7. Basic 95 The precedence of evaluation of logical operators is Not And AndAlso Or OrElse The logical functions works as explained in chapter two Each one has an associated truth table that take carry of the two states True or False and in some programming environments a state called Empty or Null to distinguish between False an non value If you want to see how this really works you must consult the VB programming environment 3 An arithmetic expression uses the syntax lt operand gt lt arithmetic_operator gt lt operand gt where lt operand gt lt operand gt can be numeric variables literals constants or arithmetic expressions or calls to functions that returns numeric values arithmetic_operator binary operators is one of the following Example Evaluation Priority in for x 3 descending order a ec y po Subtract as S S a po o Mutiyadi po Divide ois o S 2 ordiv Integral division xx2 gt 1 ooo 2 mod Modulus x mod 2 gt 1 remainder4 2 Exponentiation x 2 gt 9 a 3 OO and can be used as sign designator and are referenced as unary operators Or a shift operator VS 05 Operator Significance Explanation Evaluation Priority i descending lt lt Shift Left Shifts the individual bits in an integer operand to the left by the number of bits specified in the second operand acts as multiplying the left operand by two at the power specified by the second operand Example
8. EtAltTVA Visible False AItTVA Visible False ElseIf PT va2 Value True Then PrTVA PrTVA2 PTval Value False Ptvax Value False EtAltTVA Visible False AItTVA Visible False Elself Ptvax Value True Then PrTVA PrIVAx PTval Value False PTva2 Value False EtAltTVA Visible True AItTVA Visible True FrmTva Refresh Else MsgBox Att Computation Error vbCritical End If End Sub 112 THE REPRESENTATION OF PROCESSING ALGORITHMS Case of Executes one of several groups of statements depending on the value of an expression called selector The case structure and statement can is especially used when selection is based on the value of a single variable or a simple expression called the case selector it compares a single value against a set of test cases values A proposed graphical representation is shown in figure 3 13 test_expression Selector fest_expresson mh f 5t_EXpressDONE gt test_expressione expression_list expression_list expression_list expresion ist expresion_sist gt expresion lisi l lt Semences Figure 3 13 The Case Of structure Each expression _list is described as one or more values separated by comma First syntax Basic Access VBA Select Case test _ expression switch expression_int Case expression list case constant_expressiony sentences operations Case expression list 2 case constant_expressionz sentences 21 _ Ope
9. Int Ni b If b gt 16 Then newNi oldNi Ni b amp IIf newNi lt gt amp newNi Else newNi isTheDigit oldNi Ni b amp newNi End If Loop IntegerToBinary newNi End Function 136 THE REPRESENTATION OF PROCESSING ALGORITHMS This function is very simple it defines a vector of 16 characters and initialize each one with the corresponding hexadecimal digits represented as characters The function receives a value computed by following the conversion algorithm steps and returns a character string containing the digit in the new base for example for 10 returns a An optimized a little strange method can be defined by using the bitwise operators you can see an implementation in VB in example VI and in the site http www avrams ro conversions htm Function isTheDigit ByVal i As String Dim dg 0 To 15 As String dg 0 o dg 1 1 dg 2 2 dg 3 3 dg 4 4 dg 5 5 dg 6 6 dg 7 7 dg 8 8 dg 9 9 dg 10 a dg 11 b dg 12 c dg 13 q dg 14 e dg 15 f isTheDigit dg i End Function End Class
10. Min x Max x Ifx gt y Then Min y Ifx lt y Then Max y End Function End Function A special case of the If sentence is the sentence if then elseif available in VB a similar structure is available for example in the procedural component PL SQL of Oracle DBMS The nested If can be coded as a multiple alternative decision The syntax for that nested If is If condition Then sequence ElseIf condition Then sequence Else End If For the first time condition is tested If the result is False condition is tested and so on until a True evaluated condition reached for each the associated sentence block executed After executing the reached block the control of processing is passed to the next sentence after End if If no condition evaluates to True then the sentence block associated to the Else branch executes if Else defined if not nothing executes 110 THE REPRESENTATION OF PROCESSING ALGORITHMS Examples a using nested If Sub Factorial Call n InputBox Type the value for n VB Samples n P If IsNumeric n True Then If Int n n Then Call to the iterative implementation of factorial function valReala Factorial _Iterativ n Raspuns MsgBox The Factorial is amp valReala vbInformation voOKOnly Call to the recursive implementation of factorial function valReala Factorial n Raspuns MsgBox The Factorial is amp valReala vbInformation voOKOnly End If End If End S
11. Second Syntax Choose index choice_I choice_2 choice_n The return is Null if n lt index lt 1 114 THE REPRESENTATION OF PROCESSING ALGORITHMS 4 Calculator de Birou oxi Calculator Ajutor Example Procent TVA j K 19 C0 C Altprocent Suppose we want to build a simple calculator figure 3 14 that deals with formulas of the type result operator op or result op operator op2 where the variables op and opz are numeric data types ag ea ee ee i E operator buttons The choosing of the right computation is 7 i realized depending on the property Caption of the button Each button is included into an object E B Fa Bj collection called Operator and to each button is associated an index Figure 3 14 An example of a VAT calculator The selection of the Case the operation desired the button pressed is realized depending on a flag indicator OpFlag in which is stored the value of the Caption property The following code sequence represents the operator analyzer of a desk computer allowing the direct VAT elements computation Romanian rules The sequence calls user defined functions as AfiseazaBazaTva for example to which you must don t think You can see how the CASE OF pseudocode can be used in practice INFORMATICS Computer Hardware and Programming in Visual Basic 115 Select Case OpFlag OpFlag contains the pressed Operator ke
12. as a Double The hexadecimal literals start with the amp H character sequence followed by the hex digits Integral values of type Integer are followed by a capital or the character Integral values of type Long are followed by a capital L or the character amp You can include octal literals in your code by starting the value with the amp O character sequence followed by the octal digits Integral values of type Short are followed by a capital S Floating point values of type Single are followed by a capital F or the character String literals appear within a set of double quotes with no special character following the closing quote A quote character within the string literal will be typed twice as in the second example which will produce the string A B C 3 2 3 Variables and Constants Declarations The variable that appears in an assignment statement and not only in the left side or the variables and the constants used in expressions must be declared explicitly A variable declaration is not an executable sentence These kinds of sentences are addressed to the 100 THE REPRESENTATION OF PROCESSING ALGORITHMS program language compiler and or interpreter that eat them in the order they appear as a sequence The result of eating is a memory reservation with a naming maybe The naming of constants and variables in VB uses the rules 1 An identifier must begin with a letter 2 Can
13. distance of the left edge of the dialog box from the left edge of the screen If xpos is omitted the dialog box is horizontally centered ypos Optional Numeric expression that specifies in twips the vertical distance of the upper edge of the dialog box from the top of the screen If ypos is omitted the dialog box is vertically positioned approximately one third of the way down the screen helpfile Optional String expression that identifies the Help file to use to provide context sensitive Help for the dialog box If helpfile is provided context must also be provided context Optional Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author If context is provided helpfile must also be provided 103 104 THE REPRESENTATION OF PROCESSING ALGORITHMS ypos Example xpos Prompt acceptare corect anulare renuntare The call InputBox Prompt Valoare_implicita Titlu will produces the dialog box from figure 3 7 Cancel Valoare_implicita Figure 3 7 Example of using InputBox MsgBox Displays a message in a dialog box waits for the user to click a button and returns an Integer indicating which button the user clicked Syntax MsgBox prompt buttons title helpfile context where Argument Description prompt Required Is a string expression that is displayed as the message in the di
14. e Finality the algorithm must find a solution in a finite number of steps e Clarity the algorithm must specify all steps that must be realized to obtain a correct solution of the problem The problem solving process starts with the problem specification and ends with a concrete and correct program The steps to do in the problem solving process may be problem definition problem analysis algorithm development coding program testing and debugging and documentation 3 1 1 The Stages of Solving a Problem by Means of Computer The stages of analysis design programming implementation and operation of an information system forms the life cycle of the system as described in 1 8 Here we briefly describe the steps in problem solving process by using a programming environment it can allow the around application programming by the possibility of generating programs from general templates for example and by considering only a specific process from the whole system In this context the stages can be 1 Defining Specifying the problem Theme by answering to questions as What the computer program do What tasks will it perform What kind of data will it use and where will get its data from What will be the output of the program How will the program interact with the computer user Specifying the problem requirements forces you to state the problem clearly and unambiguously and to gain a clear understanding of what is requi
15. is zero signals that to the user and stops processing Extracts the digit in the new base from the string myDigits from the position determined by anding the number with the base 1 Starts a loop as long as the number not yet less than the most significant digit in the new base Divides the number by the new base reprezented as 2 at the power determined previously here Extracts the digit in the new base from the string myDigits from the position determined by anding the number with the base 1 Restarts the loop Returns the value to the caller Function dec2base ByVal d ByVal b As String Dim newD As String bb As Integer b1 As Integer bb whichPowerOf2 b b1 b 1 If bb lt 0 Or b1 0 Then dec2base Err Exit Function End If newD Mid myDigits d And b1 1 1 Do While d gt b1 d gt gt bb newD Mid myDigits d And b1 1 1 amp newD Loop dec2base newD End Function This function determines if a number is a power of two or not If the number is a power of two determines that power and returns to caller that value Function whichPowerOf2 ByVal d As Integer Dim nr As Integer 0 dd As Integer dd d If d lt 2 Then Return 0 End If If d 2 d gt gt 1 lt gt 0 Then MsgBox The base is not a power of two vbCritical voOKOnly whichPowerOf2 0 Exit Function End If Do While d gt 1 d gt gt 1 nr 1 Loop If dd lt gt 2 nr Then MsgBox The bas
16. k Next j Next i Each For i associated with the line containing the Next sentence followed by the variable designated as counter 124 THE REPRESENTATION OF PROCESSING ALGORITHMS If the instruction line Next don t contains the counter variable name then that associates to the first appearing sentence For If the line sentence Next contains the counter variable then the association is realized in the reverse order of For s instructions In our case the first cycle that must be enclosed is that defined in the lineNo containing the sentence For k the second instruction Next closes the line containing the instruction For j and the last closes the line containing For i In the case in which between the sentences Next enclosing For sentences no other sentences needed then is enough to place a single Next sentence referencing by intermediate of a list the counter variables of that For s Order x y relop Estomac return x y Figure 3 20 An algorithm for ordering two values Example For i For j sentences Next j i 3 5 Commented Samples I We realize a generalization of the Asc algorithm so that the values x and y are passed together with the comparison operator velop that can be gt lt and Depending on the value chosen for the comparison relop we are the case greater than less than and otherwise is the equality The algorithm call the defined algorithm Exchange x y to reali
17. program line containing the Figure 3 22 The display of Fahrenheit sentence to repeat Next fahrenheit line 10 The C sius correspondence table execution ends when the value of fahrenheit is greater than max To each executed cycle the value of s is added to the variable fahrenheit Line 8 transforms the Fahrenheit degrees in Celsius degrees Line 9 transform the computed values in a character string by using string functions and complete a table line IV We want to keep the marks obtained by a student over 5 years of studies in tables of the form Student First name amp Last name Studies Year Obtained Marks Discipline 1 Discipline 2 re Discipline 10 I a HI IV IV In the table below on the rows numbered from I to V the studies years are enumerated and on columns we have ten disciplines representing the disciplines from each year By the notation Mark 1 5 we define the mark obtained in the first year to the discipline 5 This table can be represented in computer as a bi dimensional array or matrix If we denote by i and j two variables by which we designate a line i and respectively a column j from the table then by Mark i j we designate the mark obtained in the year i to the discipline j The computation formula or the algorithm used to determine the average is INFORMATICS Computer Hardware and Programming in Visual Basic 129 S 10 Average Mark 5 10 g gt
18. to express the algorithms The representation by flowchart for the reverse string solution can be 86 THE REPRESENTATION OF PROCESSING ALGORITHMS Start Read text iid i oi Y empty IsEmpty string y Stop stop ba finalText finalText finalText amp Right originalT ext 1 originalText Left originalT ext Len originalT ext 1 a Display Not a N rs ran and Empty g E string reversed After you write the algorithm you must realize step by step simulation of the computer execution of the algorithm in a so called desk check process verifying the algorithm 4 Coding or programming is the process of translating the algorithm into the syntax of a given programming language Programming You must convert each algorithm step into one or more statements in a programming language The implementation of the reverse string algorithm in Visual Basic NET only the subroutine corresponding can be Private Sub ReverseStringToolStripMenultem_Click ByVal sender As System Object ByVal e As System EventArgs Handles ReverseStringToolStripMenultem Click 0 Dim originalText As String finalText As String oneCharacter As String preservedText As String 1 originalText InputBox Type text to reverse 2 If Len originalText 0 Then MsgBox Empty string supplied No Action voOKOnly vbInformation End 3 finalText preservedText ori
19. 1024 lt lt 2 will produces 4096 multiplied by 4 2 gt gt Shift Right Shifts the individual bits in an integer operand to the right by the number of bits specified in the second operand acts as dividing the left operand by two at the power specified by the second operand Example 1024 gt gt 2 will produces 256 divided by 4 2 96 THE REPRESENTATION OF PROCESSING ALGORITHMS The Visual Basic assignment can be combined with the basic arithmetic with except for amp string concatenation operators similarly to C C language as described in the following table Operator Based On Examples The Expression Is Equivalent With Standard assignment operator Addition a 1 a a 1 Subtraction a 1 a a 1 Multiplication a a a 2 I Division al 2 a al2 Integer Division a 2 a a 2 A Exponentiation a 2 a a 2 lt lt lt lt Shift Left a lt lt 2 a a lt lt 2 gt gt gt gt Shift Right a gt gt 2 a a gt gt 2 amp amp Concatenation strings a amp this string aza amp this string If the desired order of evaluation differs from the operator evaluation order 3 2 1 we can use parenthesis to form sub expressions as so called embedded or nested expressions In that case first evaluated is the most nested parenthesis For example the computation of the real root of the polynomial in 2 can be written as b sqr b 2 4 a c 2 a If an opera
20. 2 Cancel vbAbort 3 Abort i vbRetry 4 Retry vblgnore 5 Ignore vbYes 6 Yes Figure 3 8 Example of an MsgBox vbNo 7 No dialog In the following example is illustrated how to write the message on many lines and what means a string expression MsgBox The Student amp Name amp Chr 13 amp Chr 10 amp has the average mark amp media What is between means literal strings that will be placed as such in the message Name and media are named variables whose content will be concatenated by the string concatenation operator amp with the literals and the function calls Chr 13 amp Chr 10 means display what follows on a separate line 106 THE REPRESENTATION OF PROCESSING ALGORITHMS 3 3 Alternative Structure Decision The decision structure figure 3 9 is used for choosing an alternative an operation or block of pow ee os oe True Yes False Not operations from two possible alternatives rid condition Algorithm steps that select from a choice of actions are called decision steps The decision block can be expressed in a natural language as evaluate the expression that defines the logical condition lt condition gt If the result of evaluation is True Then execute operation Else execute operationz continue the execution with the next step in the flow The logical condition lt condition gt is a logical expression that will be evaluated either to True or either to Fa
21. 45 for negative g 4 bytes numbers 1 401298E 45 to 3 402823E38 for positive floating point p ek 1 79769313486232E308 to Double 8 bytes 4 94065645841247 E 324 for negative numbers floating point y 4 94065645841247 E 324 to 1 79769313486232E308 for positive numbers Currency 8 bytes 922 337 203 685 477 5808 to scaled integer y 922 337 203 685 477 5807 INFORMATICS Computer Hardware and Programming in Visual Basic 101 79 228 162 514 264 337 593 543 950 335 without decimal mark 7 9228162514264337593543950335 with 28 14 bytes positions for the fraction and the less number lt gt 0 equal to 0 0000000000000000000000000001 8 bytes 1 January 100 to 31 December 9999 y Jan 1 1 AD to Dec 31 9999 AD oa 4 bytes Any reference to an Object String 10 bytes variable length E sting lengi Orions Uses UNICODE String 7 fixed length g string length 1 to 65 400 variant N 16 bytes Any number value from the double domain with numbers Variant with N 22 bytes 0 to 2 billions characters string length o e UInt32 hal 4 bytes 0 to 4 294 967 295 unsigned integers on 32 bits ULon 8 bytes 0 to ICL 446 744 073 709 551 615 ULong y UShort gt 2bytes 0to 655385 s sCs d User defined using eat oie of The size of each element is the same with that for Type Baca the associated data type Available only in Visual Studio 2005 N Not available in Visual Studio 2005
22. FORMATICS Computer Hardware and Programming in Visual Basic 105 vbYesNoCancel 3 Display Yes No and Cancel buttons vbYesNo 4 Display Yes and No buttons vbRetryCancel 5 Display Retry and Cancel buttons vbCritical 16 Display Critical Message icon vbQuestion 32 Display Warning Query icon vbExclamation 48 Display Warning Message icon vbInformation 64 Display Information Message icon vbDefaultButton1 0 First button is default vbDefaultButton2 256 Second button is default vbDefaultButton3 512 Third button is default vbDefaultButton4 768 Fourth button is default vbApplicationModal 0 Application modal the user must respond to the message box before continuing work in the current application vbSystemModal 4096 System modal all applications are suspended until the user responds to the message box vbMsgBoxHelpButton 16384 Adds Help button to the message box VbMsgBoxSetForeground 65536 Specifies the message box window as the foreground window vbMsgBoxRight 524288 Text is right aligned vbMsgBoxRtlReading 1048576 Specifies text should appear as right to left reading on Hebrew and Arabic systems For example the call MsgBox Prompt vbInformation vbOkCancel Titlu will produces the dialog shown in figure 3 8 The returned values correspond to the pressed aa Constant Value Description 7 vbOK 1 OK Ono vbCancel
23. ICS Computer Hardware and Programming in Visual Basic 83 Chapter 3 THE REPRESENTATION OF PROCESSING ALGORITHMS 3 1 Concepts Algorithm is a fundamental concept of computer programming An algorithm is represented as a set of rules Rij which can be applied to the same class of problems CPj in order to obtain the solution S by means of some sequential unique operations OS started eventually with some initial conditions Ci S Ri OSi CPi CIi An algorithm is a prescribed set of well defined instructions for solving a problem in a finite number of steps In computing algorithms are essential because they serve as systematic procedures that computers require LK 99 Thus we can say that an algorithm is a solution of certain kind of problems that are referenced by the term computational or algorithmic problem There are many reasons for using algorithms from which at least the following three are very important Efficiency for certain types of problems resources have found over the time efficient ways for solving and implementing them They exist also as procedures or functions in libraries usable in many programming languages Abstraction an algorithm provides a level of abstraction in solving problems Generally every complex problem can be decomposed into simpler ones for which known algorithms exists Reusability algorithms are generally reusable for many different situations A program is a set of instruc
24. INFORMATICS Computer Hardware and Programming in Visual Basic 81 Chapter 3 THE REPRESENTATION OF PROCESSING ALGORITHMG ccccceeseeteees 83 A MAIGRET siccssaiasccundeancicandassacnadaadocieansecticeasapecanbanvadansasmsaraxanccnnss E 83 3 1 1 The Stages of Solving a Problem by Means of Computer cccccsccceseceeeeeeeeseees 84 The General Steps for Preparing a Prostrate ccsicnsdscesscencemanneian eaten macanenade 87 EXGCUUME PIOOTAIN snenia a a E E E EE TE EEAO AEE EE RA RAS 89 3 1 2 The Description of Algorithms by Means of Logical Diagrams Flowcharts 90 Process Program and Document Flow Charts sissaccsssvesacesssceaxauencdanespsneassagendanacsbecexeebeanieass 90 The Basic Symbols Used in Drawing Program Flowcharts c ccccecsseceteceeeeeeeeeeees 91 Fundamental Structures Used in Algorithm Representation ccccesseceteeeeeeeeeeeeees 92 E EE TNS S E E E E ee 92 EPE a A E E EEE 93 eE T EAA E 98 3 2 3 Variables and Constants Declarations is ccasiissccsssssccsannssiseiasssacraessiceargsaacaavstaecaanisaneees 99 3 2 4 Input Output Operations by Using InputBox and MsgBox Functions eee 103 3 3 Alternative Structure Decision sy ssccstccssecsiesensseeanieeaieden ee natsiaavle taneous 106 34 Repeating I eaii EE EREE sie EE AE ER accents 115 J3 Commented Sap ESen naie ssncusnesabdenandunapeelscsasinedesncunusnbdessndyasirese 124 82 THE REPRESENTATION OF PROCESSING ALGORITHMS INFORMAT
25. Literals can be used only once in the code if you want use many times you must declare them each time The constants are like a cross between literals and variables they have a single never changeable value just as literals but must be declared and assigned with the value just as variables Examples Constant Type Welcome to the information century string 25 000 00 currency 3 14 positive real number 123 negative integer number 0 123e 3 number written in the scientific notation 11 12 2009 date Constants can be defined as a declaration statement by using the syntax Const constantName As data_type expression where data type can be one of Byte Boolean Integer Long Single Double Currency Decimal String Date user_defined Object etc as described in table 3 1 constantName is an user identifier defined by following the naming rules expression an expression evaluated to an agreed data type whose evaluation is considered the default value for the constant Examples Const Pi As Single 3 14159 Const Vat As Single 0 19 Star As String x A declared constant is a named storage location that contains data that cannot be modified during the program execution The most used constants are number constants and string constants A string constant is sequences from 0 to 1024 characters enclosed in quotes INFORMATICS Computer Hardware and Programming in Visual Basic 3 2 4 Input Out
26. a during processed instructions for T displaying or printing values in F Proran OPY memory can be executed to Computed results output Results display the program result The lines displayed by a program Step 3 are called the program output Figure 3 2 Executing a program 3 1 2 The flow of information during program execution can be summarized as in figure 3 2 The Description of Algorithms by Means of Logical Diagrams Flowcharts Process Program and Document Flowcharts In the general analysis of information system the designer can use three kinds of flowcharts document process and program flowchart and or narrative descriptions in pseudocode Document Flowchart A document flowchart is a diagram illustrating where documents originate and where copies of them are sent The most useful kind of document flowchart shows what happens to the copies of a single document from the time they are created until each of them is in a file or in the hands of an outside party A consolidated flowchart for a single process shows origins and fates of all documents in the process Process Flowchart A process flowchart is a diagram that shows the data and operation for a single process If a process is complex several flowcharts may be needed to cover it complexity Program Flowchart A program flowchart is a diagram that shows the data steps and logic of a process operation does show logic and additional processing detail It also
27. a program just as they are The literals accepted and the rules of defining them are the following String Literals String literals are always surrounded by quote marks can be up to about two billion characters in length The character literal is exactly one character in length and is recognized by the c trailing after the string for example A c designates the capital A character Date and time literals Date and time literals are surrounded by the number sign pound and can be specified in any format recognized by Microsoft Window in a specific region as for example 11 17 2008 Numeric literals There are 11 different kinds of numeric data values both integers and floating point values which can be defined by typing the number right in the code like 27 or 3 1415926535 Visual Basic also lets you specify which of the 11 numeric types to use for a specific number by appending a special character to the end of the number For example normally 27 is an integer and can be a floating point decimal by appending an sign 27 floating point decimal If you do not specify for a number the trailing character specifying his type the number will be typed depending of his magnitude and format real integer automatically by the compiler The type allows to properly align the result of computations in which those literals involved to the largest precision and to check if they properly used Boolean literals Boolean values represe
28. al condition Preparation used to specify Open Close operations on files or computer ports or connections to host computers or to long distance databases Input Output Block It is used to represent read and write operations on data Inside is written the operation sense such as reading expressed by commands as Read Input Accept Select Get In or writing expressed by commands as Write Display Put Update Modify Print Out followed by the logical device name allowed by the system at opening and the list of values variables on which the command acts Onpage Connector Used to link different points of the logical diagram in the same page Inside is written a label can be a digit number or a word is preferable to be of significance for the reader that must be defined only once as entry point the arrow goes from symbol and how many times needed as exits or go to The entry labels must be unique for a particular flowchart V OO l a ae 92 THE REPRESENTATION OF PROCESSING ALGORITHMS Offpage Connector It links different points of the logical diagram in different pages It has the same rules as the Onpage Connector IID Flow Is a connection from to that links all the blocks in the diagram and shows the transfer sense of the information Fundamental Structures Used in Algorithm Representation Each algorithm can be represented as a combination of three control structures 1 Sequentia
29. alog box The maximum length of prompt is approximately 1024 characters depending on the width of the characters used If prompt consists of more than one line you can separate the lines using a carriage return character Chr 13 a linefeed character Chr 10 or carriage return linefeed character combination Chr 13 amp Chr 10 between each line buttons Optional A numeric expression that is the sum of values specifying the number and type of buttons to display the icon style to use the identity of the default button and the modality of the message box If omitted the default value for buttons is 0 title Optional String expression displayed in the title bar of the dialog box If you omit title the application name is placed in the title bar helpfile Optional String expression that identifies the Help file to use to provide context sensitive Help for the dialog box If helpfile is provided context must also be provided context Optional Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author If context is provided helpfile must also be provided The value for buttons argument can be determined as a sum of the following Visual Basic constants Constant Value Description vbOKOnly 0 Display OK button only vbOKCancel 1 Display OK and Cancel buttons vbAbortRetrylgnore 2 Display Abort Retry and Ignore buttons IN
30. e Then MsgBox Err The value you want convert is not a number vbCritical voOKOnly Me decNumber Focus Exit Sub End If If Trim Me newBase Text Or IsNumeric Trim Me newBase Text False Then MsgBox Err The value for new base is not a number vbCritical voOKOnly Me newBase Focus Exit Sub End If Ni Trim Me decNumber Text b Int Val Trim Me newBase Text If b 0 Then MsgBox Err Actually according to all algebric theory divison by 0 zero not supported amp _ Chr 10 amp Chr 13 amp A fractionary number is converted to integer vbCritical voOKOnly Me newBase Focus Exit Sub End If Me convertedValue Text IntegerToBinary Ni b End Sub This is the code associated to the Close button Private Sub closeButton_Click ByVal sender As System Object ByVal e As System EventArgs Handles closeButton Click Me Close End Sub This is the code associated to the Clear button emptyies the text boxes Private Sub cleanBoxes_Click ByVal sender As System Object ByVal e As System EventArgs Handles cleanBoxes Click Me decNumber Text Me newBase Text Me convertedValue Text End Sub The function ntegerToBinary receives as arguments a copy of the number to be converted and the new base and returns a string containing the number in the new base If the INFORMATICS Computer Hardware and Programming in Visual Basic 135 base is less than or equal to 16 it uses the hexadecimal digits t
31. e decision block figure 3 11 is expressed in a natural language as True Yes x False Not evaluate the condition ae al Coo if the result is True then execute operation Figure 3 11 The decision block without the else continue the execution of the program Else branch The pseudocode can be expressed in one of the formats Basic Access VBA C Java If condition Then statement if condition operation If the condition is True then the statement is executed If condition Then Sequence of statements End If if condition operations If the condition is True Then the group between Then and Else will be executed Else the group of sentences between Else and End If will be executed Inline if lf condition trueReturn falseReturn If the condition is true then the evaluation of the expression trueReturn will be returned INFORMATICS Computer Hardware and Programming in Visual Basic 109 Else the evaluation of the expression falseReturn will be returned PASCAL If condition Then If condition Then operation Begin operations End Almost programming languages allow nesting if then else sentences one if statement inside another to form complex decision structures decisions with multiple alternatives Examples a Another implementation of Min and Max Function Min x As Variant y As Variant Function Max x As Variant y As Variant As Variant As Variant
32. e is not a power of two vbCritical voOKOnly whichPowerOf2 0 Exit Function End If Return nr End Function INFORMATICS Computer Hardware and Programming in Visual Basic 133 VII The conversion algorithm implemented as a Class The algorithm for conversion implemented with basic arithmetic operators The clarity of the code have a greater priority than the optimality and shortest of the code in this example and also in most of examples introduced here a Conversions Decimal Integers to lt anyBase gt Number l Base Converted Value 22 Convert Clear a Close When the button Convert is pressed the event procedure convertButton_ Click is called that realizes the following operations 1 Rezervation of memory cells used to store the number and new base Dim Ni As Long b As Long 2 Check if what typed by user in the text box Number is a number If not a number signals that by a message and returns in the form to retype the number or end processing If Trim Me decNumber Text Or IsNumeric Trim Me decNumber Text False Then MsgBox Err The value you want convert is not a number vbCritical voOKOnly Me decNumber Focus Exit Sub End If 3 Check if what typed by user in the text box Base is a number If not a number signals that by a message and returns in the form to retype the number or end processing If Trim Me newBase Text Or IsNumeric Trim Me newBa
33. e suppose that the user types numbers between 0 zero and 10 ten as integer values Because the function InputBox reads text values the mistakes any other characters than digits and or spaces between digits will produces a computation error message To avoid that is necessary to test whether the typed value is number or not Read_Number reads a value from keyboard and verifies if number or not a process called validation If the value is not a number signals that to the user who can choose between cancel or resume the operation from typing 130 THE REPRESENTATION OF PROCESSING ALGORITHMS Function Read_Number xNr As Variant denNr As Variant As Variant Dim Answer As String Do While True True an infinite cycle xNr InputBox Type the value for amp denNr amp Example If Not IsNumeric Trim xNr Then Answer MsgBox The Value for amp denNr amp must be Numerical voOKCancel _ Example This is a continuation line If Answer 2 Then Cancel Button pressed Read_Number Cancel The returned value to the caller is Cancel Exit Do Exit from the infinite cycle and return to the caller End If Else Read_Number Trim xNr The returned value will be the number without extra spaces to the left or right Exit Do Exit from the infinite cycle and return to the caller End If Loop Restart the cycle End Function V The following example illustrates how the arithmetic operators and intrinsic functio
34. ecify how many times the statements inside the loop are executed counter i In this diagram i is the initial value start value usually 0 or 1 f is the end value the expected value usually how many times g operations K counter counter step az Step is the increasing or decreasing step for counter Figure 3 19 The representation of For The pseudocode for this structure is Basic Access VBA for expression expression2 expression For counter v To f Step s operation operations Exit For Continue For Next counter If many operations desired in the cycle they must be included as block expression is an expression that initialize Where the counter the value for s can be positive or negative if s is positive then must have the inequality v lt f otherwise the cycle never executes if s is negative then must have the inequality v gt f otherwise the cycle never executes if a value for Step not specified the default is used 1 the cycle can be stopped unconditionally by intermediate of the sentence Exit For or can be reiterated by the sentence Continue For goes to the end of For expression contains the definition for ending the loop expression is an expression to increment or decrement the value for the counter The cycle can be unconditionally stopped by using the instruction break and can be unconditionally r
35. emory and save it to disk as a source file Most programming environments offer an integrated editor Ki The executable All N see ss program in nenna Enter the pogram source code and save H as a snee text file Source File Figure 3 1 Steps for preparing a program for execution In VB the source code can be stored in modules files with bas extension or in the source file associated to forms Until you save explicitly the project you work on all new source code or the older one corresponding to loaded objects is stored in temporary files created when loading the project and or adding components You can save your changes any time by pressing the File Save option or by pressing the Save button in the toolbar 2 Use a compiler interpreter program to translate the source program into machine language If there are any syntax errors errors in grammar the compilers interpreter displays these errors on the monitor Use the editor program to correct the errors by editing and resaving the source program In VB environment the syntax errors are signaled as they produced You can correct them in the same editing session In that way you can obtain a syntax error free code VB6 You can run the program by choosing between Run Start the interpreter only command and Run Start With Full Compile the compiler The compiler is started automatically when you select the File Make lt project na
36. eparing a Program The algorithm found for a problem is translated coded into a computer program by using a programming language usually a high level one The text of the program is entered into the computer s memory by typing it in from the keyboard reading from other storage 88 THE REPRESENTATION OF PROCESSING ALGORITHMS devices hard drive memory stick magnetic tape etc receiving along the communication channels from other networked devices etc This program text expressed in terms of sentences of a programming language forms the so called source program source code To be executable for the processor that executes and understands only the machine language our source program goes through a number of transformations syntactic and semantic analysis translations link editing etc that allows be expressed in the machine language The general steps for preparing a program written in a programming language for execution figure 3 1 are the following references ja memory or saved The compiler el interpreter cass pa Modules attempts translate Lat GR Wed the pogram Sovea y to extemal themto our object Sy wot pas pogam Y pa Correct syntax errors and obtain List of errors a revised source file List of enors Other Object q my Add the needed libraries or kis call reregister them in register database and re link 1 Use an editor program to enter each line of the source program into m
37. essage they are very difficult to detect e field testing is realized by users that operate the software with the purpose of locating problems The main purpose of field testing is verifying the program in order to eliminate the logic errors 6 Documenting the program by e internal documentation the instructions and comments within the program itself In VB programs the comments are placed by using the Rem command as a separate line or preceded by the colon character as a multi command line or single apostrophe as the inline comment e external documentation the printed set of instructions the user s manual describing how to operate the program it can be also on line documentation 7 Integrate the program in the data process flow Implementation and use the program to solve problems Exploitation In that step the programmer must maintain and update the program this means to modify the program to remove previously undetected errors and to keep it up to date as government regulations or company policies changes Before the computer can execute an assembly or a high level language program the programmer must enter the sentences of the program as a so called source program into the computer and the computer must store it in executable form in memory expressed as machine language sentences Several system programs such as editors compilers or interpreters linkers etc assist with this task The General Steps for Pr
38. estarted by using the sentence continue INFORMATICS Computer Hardware and Programming in Visual Basic 121 First syntax FOR counter v TO f DO operation normal Second syntax FOR counter v DOWNTO f DO operation in reverse order If many operations desired they must be placed in a begin end block The execution of For VB sentence follows the scenario 1 The value v is assigned to the variable counter 2 The value of variable counter is compared with the end value f If the value for step is negative is checked if counter lt f 3 The operations are executed 4 The value of variable counter is incremented with the value step 1 if step not specified 5 Repeat the steps from 2 to 5 The interpretation of the elements of For Next sentence is what cycle number is how many times For counter start_value To end_value Step increment _decrement statements Exit For stop the cycle statements Next counter Examples I Pope pleases the great mathematician Gauss to tell him when Eastern will be in a wanted year Gauss says that Eastern will be always on 4 April D days E days where D is determined by following the steps 1 the year is divided by 19 2 the remainder is multiplied by 19 3 to the result of step two add fix factor 15 4 the sum of values obtained in the steps 1 to 3 is divided to 30 and the remainder is D E is determined by following the ste
39. ginalText Do While originalText lt gt oneCharacter Microsoft VisualBasic Right originalT ext 1 finalText finalText amp oneCharacter originalText Microsoft VisualBasic Left originalText _ Len originalText 1 Loop MsgBox The original string is amp preservedText amp Chr 10 amp Chr 13 amp The reverse is amp finalText End Sub End Class no oS SO 00 INFORMATICS Computer Hardware and Programming in Visual Basic 87 5 Testing and debugging e testing means running the program executing all its instructions functions and testing the logic by entering sample data to check the output e debugging is the process of finding and correcting program code mistakes syntax errors identified generally at interpreting compiling time a syntax error occurs when your code violates one or more grammar rules of the used programming language In VB environment the syntax errors signaled in the moment they produced by the VB interpreter run time errors are detected and displayed by the computer during the execution of a program A run time error occurs when the program directs the computer to perform an invalid operation such as dividing a number by zero or manipulating undefined or invalid data logic errors or so called bugs identified generally at run time occurs when a program follows a faulty algorithm Because logic errors usually do not cause run time errors and do not display error m
40. h and if a year is leap year or not The function requires three parameters separated by comma character with the general INFORMATICS Computer Hardware and Programming in Visual Basic 131 format DateAdd string integer string2 The first parameter of that function string is the unit of the added value d still for days and is given as a string literal value a value enclosed in quotation marks The second parameter integer gives after how may time units from the initial date stringz the new date This parameter is given as an expression D E where both D and E are integers as defined in line 2 and as computed in lines 3 and 4 respectively The result of adding these two integers will be an integer too as required by the function call model The last required parameter string2 represents the beginning date April 4 of wanted year An Dorit and is given as a string concatenation expression formed by the literal value 04 04 to which is concatenated by the concatenation operator amp the desired year Trim An_ Dorit The An Dorit variable is of Variant data type and the Trim functions eliminates the trailing blanks may be to the left or to the right of the value By using this function we prevent the case the user type a year in the text box of the dialog box preceded or followed by space characters but we don t prevent the spaces between digits if you want do that use the function ReadNumber from example IV The
41. he used programming languages in one of the next following formats x 0 x 0 x 0 store 0 To x x expression variable expression The interpretation of the last form is the variable before the assignment operator is assigned a value of the expression after it and in the process the previous value of variable is destroyed 94 THE REPRESENTATION OF PROCESSING ALGORITHMS An expression can be an expression on character string a logical expression or arithmetic expression It can be a variable a constant a literal or a combination of these connected by appropriate operators An assignment statement stores a value or a computational result in a variable and is used to perform most arithmetic operation in a program 1 An expression on character string can be built in VB but not only using the concatenation operator amp or intrinsic functions for extracting substrings from a string variable or string constant such as Right string number_of_characters extracting substring from the end Left string number_of characters extracting substring from the beginning functions that manipulate strings Cstr expression convert the expression in a character string Lease string_expression convert the string in lower case Ltrim string Rtrim string Trim string eliminates the spaces trailing from left leading blanks right and respectively left right Str number converts number in string Ucase
42. ible that the executable do not work That happened because the program may need some libraries registered in the computer and they are not To be sure that your program runs anyway use the Application Setup Wizard from your VB package to create a setup application program that includes all references needed by the program The setup will help you to install correctly your program on a new computer system running under a compatible operating system Executing a Program As we seen earlier the computer is a programmable device and the part called CPU is responsible with instruction interpretation and execution The program must be represented in machine language patterns of bits To execute a machine language program the CPU must examine each program instruction in memory and send out the command signals required to carry out the instruction Although the instructions normally are executed in sequence as we will discus later it is possible to have the CPU skip over some instructions or execute some instructions more than once 90 THE REPRESENTATION OF PROCESSING ALGORITHMS During the execution data can be entered into asain memory and manipulated in some specified way Special ue Siep 2 program instructions are used swal nogen poo for entering or reading a Central program s data called input Processing data into memory After the N ER a Unit input data have been Input Data eres net
43. ion tree for AverageVelocity p2 p1 t2 t1 A Step 2 Nf Step3 1 Neca AverageVelocity Step 1 Figure 3 4 Using the Parentheses rule for evaluating expressions 2 Operator precedence rule Operators in the same expression are evaluated from left to right in the following order A first mod div gt gt lt lt second e last Example Function CircleArea Radius As Double As Double CircleArea Pi Radius 2 The circle area is given by the formula Per einai Area nr that can be written in VB as CircleArea Pi Radius 2 The formula can The evaluation tree for CircleArea Pi Raqius 2 be written and evaluated as shown in figure 3 5 Step2 F es CircleArea Figure 3 5 Using the operator precedence rule 98 THE REPRESENTATION OF PROCESSING ALGORITHMS 3 Left associative rule Operators in the same expression and at the same precedence level are evaluated left to right Function CircleArea Radius As Double As Double CircleArea Pi Radius Radius Example End Function The evaluation tree for CircleArea Pi Radius Radius The circle area can be written in VB step1 4 as CircleArea Pi Radius Radius g and is evaluated as shown in figure ent aY 3 6 y CircleArea Figure 3 6 Using the left associative rule 3 2 2 Literals Some basic data values such as numbers date values strings etc can be included into the source code of
44. ition Evaluated First Syntax Do While Until condition beginning of cycle statements Exit Do body of the cycle statements Loop the end of sentence block The commands Loop and Exit Do are used to do AA Not Loop an unconditional jump or branch to the beginning lt lt condition gt of the associated cycle the evaluation of the condition Yes Exit Do an unconditional ending of the cycle a jump to the next sentence defined under the loop that ends the body of the cycle Do Until work as 1 execute statements 2 evaluate the condition Loop or Exit Figure 3 15 Loop structure The block of commands between Do and Loop will be executed while until the conditional expression condition evaluates to True Do While Until condition first syntax operations Exit Do while condition operation Continue Do Loop second syntax A set of commands operations while condition placed between Do While and Loop is executed for as longs the logical condition operations remains True continue Exit Do Loop statement immediately break Continue Do immediately jumps to the end of Do Loop statement where continue jump to the condition evaluation break interrupt the cycle and transfer the execution to the sentence that follows to the end block marker INFORMATICS Computer Hardware and Programming in Visual Basic 117 PASCAL First s
45. l or process structure 2 Alternative or decision structure If then else 3 Loop repeating cycle structure the condition evaluated first Do While From these basic structures are derived and used by programmers the following three structures 4 Case of Switch case 5 Do Until loop with the condition evaluated after 6 Counted loop structure For Next The sequence control of the next step in programs is usually carried out with the aid of various combinations of instructions used to model the control flow structures or control structures as the following Direct sequencing of the form do A followed by B or do A and then B HF 04 Conditional branching of the form if C then do A otherwise do B or just if C then do A where C is some condition HF 04 Repeating of the form do A while C or do A until not C where C is some condition or for Y from 1 to N do A 3 2 Sequential Structure The sequential structure can be represented as a sequence of operations gt step Step2 gt Step 3 F gt Sequence or as a transformation block T from the graphical representation is a data transformation such as assignments and or computations data type declarations input output operations etc INFORMATICS Computer Hardware and Programming in Visual Basic 93 Example This algorithm realizes an interchange of the content of the variable named x
46. lse The logical conditions can be simple or complex logical conditions A simple logical condition has the general syntax lt variable gt lt relation_operator gt lt variable gt or lt variable gt lt relation_operator gt lt constant gt Figure 3 9 The decision block The relation operator can be one of Js Lessthan Example delta lt O O pes Less than or equal Example delta lt 0 lt lt in C the operator is Example a 0 in C the operator is Example a lt gt 0 If lt variable gt is number or Boolean then is possible to directly compare with 0 respectively True and is not necessary to write the equal relation operator The simple logical conditions will be connected by the AND OR and NOT logical operators to form complex conditions The logical operators are evaluated in the order NOT AND and OR The change of the natural order of evaluation can be done by using round parenthesis in the same way as for arithmetic expressions The precedence of operator evaluation in Boolean expressions logical expressions is Not lt lt gt gt div mod and or lt lt lt gt gt gt If Then Else The alternative structure can be expressed in pseudocode as INFORMATICS Computer Hardware and Programming in Visual Basic 107 Visual Basic Access VBA C Java If condition Then if condition operation operation Else else operation operation2
47. lue Square Root 1 41421356237309 a SquareRoot ValComp ValRezult coston e i nee Figure 3 17 The formwused as interface for the impJentf ntation of the algorithm 2 The arrows in the figure 3 17 indicate th name given to the object they point to Public Class Newton Een i aA Private Sub Clos Form_Click ByVal sender As System Object ByVal e As System EventArgs Handles CloseForim Click Me Close l End Sub i Private Sub SquareRoot_Click ByVal sender As System Object ByVal e As System EventArgs Handles SquareRoot Click Memory variables reservation Dim x0 As Double x1 As Double a As Double Check if the value typed by the user in the text box labeled Value ValComp Txt is not numeric and sends a warning message to the user about that and returns to fix the mistake If IsNumeric Trim Me ValComp Text False Then MsgBox Type a valid value and repeat voOKOnly Attention Else If the value is a number 1 convert this number from his external representation in a real number 2 initialize the variables x0 and x1 a Val Trim Me ValComp Text x0 1 x1 0 3 starts an infinite loop Do While True True 4 computes the values by applying the formula x1 1 2 x0 a x0 5 exits from cycle when two consecutives computed values are equal If xO x1 Then Exit Do x0 x1 Loop 6 writes the obtained value in the form and exits Me ValRezult Text
48. me gt exe option Visual Studio 2005 VS 05 and up The Build Publish lt project name gt starts the wizard that will allow you to specify the location where the installer is build and INFORMATICS Computer Hardware and Programming in Visual Basic 89 which device the user will use to later on install the application web site Universal Naming Convention UNC path or file share CD ROM DVD ROM 3 When the source program is error free the compiler saves its machine language translation as an object program VS 05 The output of the Build phase is a semi compiled IL intermediate language and includes ready to execute versions of the original source code s types and members all this content can be decompiled using the disassembling tool ildasm exe included in NET package The CLR Common Language Runtime realizes a final just in time JTI compile of IL assembly to prepare it for use on the local platform 4 The linker loader program combines your object program with additional object files that may be needed for your program to execute for example programs for input and output and stores the final machine language in memory ready for execution The linker loader can also save the final machine language program as an executable file on disk In VB environment you can obtain the executable file by activating the File Make lt project name gt exe option If you intend to run your program on another computer is poss
49. means of a series of numbers Function Avg v As Variant n As Integer As Double Sum 0 Fori 1Ton Sum Sum v i Next i Avg Sum n End Function b The function Avg computes the mean of a series of numbers and uses the function Sum defined at a point Function Avg v As Variant n As Integer As Double Avg Sum v n n End Function 2 3 Draw a flowchart that exponentiation a number x at the power n Power x n Dissection of the power flowchart figure 3 21 the Start symbol contains the name of algorithm and the call format In the brackets is indicated the list of arguments to be passed at call time by i we initialize the counter for the exponent and we initialize the result to 1 if n is 0 then x I 126 THE REPRESENTATION OF PROCESSING ALGORITHMS by pow pow x we compute the actual value of the variable pow as a multiplication of the previous value of the variable pow with the variable x 3 in the decision block we check how many times we ___ are realized the repeatedly multiplication If the multiplication is not realized n times we increase the counter and then go to a new multiplication else the algorithm return the result A possible implementation of the algorithm is one of Yes the following e E Figure 3 21 An exponentiation algorithm a The function Power exponentiation a number x to a power n Function Power x As Variant n As Integer As Double Dim pow As Double pow 1
50. nd in the expression is a function call generally expressed as FunctionName argument list first the function is evaluated and his invocation is replaced with a value having the function return data type and later on the operand linking the function call to another operand evaluates Examples Assignment Interpretation x 3 14 The value 3 14 is assigned to the variable named x Delta b 2 4 a c The evaluation of expression b 2 4 a c is assigned to the variable named Delta i i 2 The actual value of variable i is given by the old value of variable i to each value 2 added x Abs x The actual value of x is the absolute value Abs of his older value If an expression contains more than one operator and or parentheses the following rules of evaluation applies INFORMATICS Computer Hardware and Programming in Visual Basic 97 1 Parentheses rule All expression in parentheses must be evaluated separately Nested parenthesized expressions must be evaluated from inside out with the innermost expression evaluated first Example The formula for the average velocity v of a particle traveling on a line between point p and pz in time t to t isv P27 Pi This formula can be written and evaluated in t t VB as shown in figure 3 4 Function AverageVelocity p1 As Variant p2 As Variant t1 As Variant t2 As Variant As Variant AverageVelocity p2 p1 t2 t1 End Function The evaluat
51. ns 1 Function Data_Paste An_Dorit As Variant As Date 2 Dim D As Integer E As Integer 3 D An_Dorit Mod 19 19 15 Mod 30 4 E An_Dorit Mod 4 2 An_Dorit Mod 7 4 6 D 6 Mod 7 5 Data_Paste DateAdd d D E CDate 04 04 amp Trim An_Dorit 6 End Sub Line 1 Declares the name of the function Data paste Easter date and the input argument required An_ Dorit As Variant Wanted year and returns a Datetime type value Line 2 Working variables D and E declarations as integers represent years Line 3 and 4 Compute the value for D and respectively E as described in the algorithm introduced earlier In both formulas are exploited the parenthesis evaluation rule and operator precedence rule In the formula D An_ Dorit Mod 19 19 15 Mod 30 first is computed the modulus 19 of An Dorit and second this value is multiplied by 19 in the third step to the previous value is added the constant 15 in the fourth step the modulus 30 is obtained from the last value and then assigned to D Line 5 In this line a string date value is obtained as a concatenation of strings An_Dorit Variant value with 4 April 04 04 from which a date value is obtained as a conversion CDate and to that obtained date is added the number of days d in terms of date DateAdd this function allow to add days month years to a date and to obtain a correct date it take account of the number of days in which mont
52. nt the simplest type of computer data the bit Boolean values are either true or false on or off yes or no etc Visual Basic includes the Boolean literals True and False INFORMATICS Computer Hardware and Programming in Visual Basic 99 The literals supported by Visual Basic and the trailing characters used to specify the type are the following Literal Type Example Boolean True Char Q c Date 11 7 2005 Decimal 123 45D 123 45 Double 123 45R 123 45 Hexadecimal amp HABCD Integer 123 45l 123 45 Long 123 45L 123 45 amp Octal amp 07654 Short 123 45S Single 123 45F 123 45 String Simple A Bm Cr Description The Boolean data type supports two literal values True and False Single character literals appear in double quotes with a trailing character c A literal of type Char is not the same as a single character literal of type String Date or time literals appear between a set of number signs and can include dates times or a combination of both The date or time values can be in any format recognized by Windows although Visual Studio may reformat your date literal for conformity with its own standards Floating point values of type Decimal are followed by a capital D or the character Floating point values of type Double are followed by a capital R or the character Also if you use a numeric literal with a decimal portion but with no trailing data type character that literal will be considered
53. o express the new number othewise the digits in the new base are written by using the decimal digits and separated by dots The function realizes the operations 1 Reservation of memory cells required by the algorithm Dim newNi As String oldNi As Integer 2 The memory cell tht will store the number in the new base is erased newNi 3 A cycle is started while the number to be converted not 0 Ni gt 1 4 The value of Ni preserved in the variable oldNi and a new value for the number is computed as the integral part of the division of the number Ni to the new base b Ni Int Ni b 5 Check if the base is grather than 16 and if it is add the digit in the new base by concatenating the string of those digits obtained in the previous steps to and the fraction part of the previous step division in reverse order if the base less than or equal to 16 concatenates the digit supplied by the function isTheDigit If b gt 16 Then newNi oldNi Ni b amp IIf newNi lt gt amp newNi Else newNi isTheDigit oldNi Ni b amp newNi End If 6 Go to anew cycle Loop step 3 7 Ifthe convesion ends then the value for the number in the new base is assigned to the function name and returned to the caller of that function IntegerToBinary newNi Function IntegerToBinary ByVal Ni ByVal b As String Dim newNi As String oldNi As Integer newNi Do While Ni gt 1 oldNi Ni Ni
54. ps 1 the year is divided by 4 and the remainder will be multiplied by 2 2 the year is divided by 4 and the remainder will be multiplied by 4 3 compute the sum of values obtained to step 1 and 2 4 to the sum add 6 D and to product add 6 5 the total sum is divided by 7 and the remainder will be E 122 THE REPRESENTATION OF PROCESSING ALGORITHMS A code that implements this algorithm is Sub Date_Pasti Dim An Inceput An Sfarsit As Variant WData As Date Dim rasp As Byte i As Integer An Inceput InputBox Anul de la care amp Chr 10 amp Chr 13 amp calculam data Pastelui Calculul datei Pastelui An Sfarsit InputBox Anul pana la care amp Chr 10 amp Chr 13 amp calculam data Pastelui Calculul datei Pastelui For i An Inceput To An Sfarsit 1 WData Data_Paste i mms mys xExemple Print i WData oe Next i A ras MsgBox Pastele cadem nul amp An Dorit amp la amp Data_Paste vbOKOnly Calcul data Pastelui End Sub Function Data PAMKe An_ Dorit As Variant As Variant Dim D As Integer E As Integer D An Dorit Mod 19 19 15 Mod 30 E An_Dorit Mod 4 2 An_Dorit Mod 7 4 6 D 6 Mod 7 Data_Paste DateAdd d D E CDate 04 04 amp Trim An_Dorit End Sub II For a nonnegative integer n the factorial of n written n is defined by Ol 1 0 n n n 1 n 2 3 2 1 for n gt 0 n n n 1 for n gt 0 a i
55. put Operations by Using InputBox and MsgBox Functions VB offers a variety of sentences for input output operations Even the flowchart symbol is not the same as the one used to represent the sequence structure the behavior is similar and all this operations are executed as sequences For instance we introduce now two functions input InputBox and output MsgBox used to activate a standard dialog InputBox Displays a prompt in a dialog box waits for the user to input text or click a button and returns a string containing the contents of the text box Syntax InputBox prompt title default xpos ypos helpfile context where Argument Description prompt Required Is a string expression that is displayed as the message in the dialog box Can be up to 1024 characters in length If prompt consists of more than one line they must be separated by a carriage return character Chr 13 a linefeed character Chr 10 or carriage return linefeed character combination Chr 13 amp Chr 10 title Optional String expression displayed in the title bar of the dialog box If you omit title the application name is placed in the title bar default Optional String expression displayed in the text box as the default response if no other input is provided If you omit default the text box is displayed empty xpos Optional A numeric expression that specifies in twips the horizontal
56. rations 2 Case Else default sentences operations n End Select INFORMATICS Computer Hardware and Programming in Visual Basic 113 each expression list is represented or expression_int is an expression that must formed by one or many comma separated produced an integral value int values value list constant_expression must be a constant in the block Select Case the case Else can expression appear only once and only as a last case the label default can by be used only if many cases fit to test_ expression then once the first founded will be executed each sentence block sentences can include zero one or many sentences the evaluation of the test expression is realized only once at the beginning of the Select Case structure PASCAL Case expression of expression is also called the selector of label instruction Case The case selector must operations be an ordinal data type data types Integer label Boolean and Char are ordinal types but operations data type Real is not or a data whose values may all be listed label label 2 label are list of possible values of the selector they must else or otherwise be of the same data type with the selector operations if the value of the selector don t fit to a end label the operations specified on branch Else otherwise will be executed the values of constants must be unique for a label
57. red for its solution Your objective is to eliminate unimportant aspects and to focus on the root problem and this may not be as easy as it sound 2 Analyzing the problem Analysis involves identifying the problem a inputs which is the data you have to work with b outputs the desired results and c any additional requirements or constraints on the solution At this stage you should also determine the required format in which the results should be displayed for example as a table with specific columns as a card with predefined items etc and develop a list of problem constants and variables and their relationships At this level the relationships between variables can be expressed as formulas 3 Algorithm development find an algorithm for its solution Design Designing the algorithm to solve the problem requires you to write step by step procedure the algorithm and then verify that the algorithm solves the problem as intended Writing the algorithm is often the most difficult part of the problem solving process Don t attempt to solve every detail of the problem initially instead discipline yourself to use a top down design In a top down design also called divide and conquer you first list the major steps or sub problems INFORMATICS Computer Hardware and Programming in Visual Basic 85 that need to be solved then solve the original problem by solving each of its sub problems For example most computer algorithm
58. s consist of the following sub problems 1 read the data 2 perform the computations 3 display the results Once you know the sub problems you can attack each one individually For example the step 2 called perform the computations may need to be broken down in more detailed lists of steps think to salary computation each perceived tax means other computation formula This process is called algorithm refinements The development can be expressed as e pseudocode a narrative description of the flow and logic of the intended program written in plain language that expresses each step of the algorithm For example the problem is to write a program that will reverse all of the letters in any chunk of text provided to the program The algorithm to solve that problem can be described in pseudo code as 01 Obtain the original text or string from the user 02 If the user didn t supply any content then signal that and quit now 03 Prepare a destination for the reversed string empty for now 04 Repeat the following sequence steps 5 to 7 until the original string is empty 05 Copy the last character from the remaining original string 06 Put that character onto the end of the destination string 07 Shorten the original string dropping the last character 08 End of repeat section 09 Show to the user the original and destination string e flowchart a graphical representation that uses graphic symbols and arrows
59. se Text False Then MsgBox Err The value for new base is not a number vbCritical voOKOnly Me newBase Focus Exit Sub End If 4 Converts the strings of digits for number and base in integer values Ni Trim Me decNumber Text b Int Val Trim Me newBase Text The Val function convert a string in a real number If the string is empty or space the converted value is 0 Int convert the base in an integer number and ensure that the base is integer All these operations must be realized because the user types in a text box that accepts any combination of characters 5 If the new base is 0 then an error message displayed and the control is passed to the user to fill in the form a valid value or end 134 THE REPRESENTATION OF PROCESSING ALGORITHMS If b 0 Then MsgBox Err Actually according to all algebric theory divison by 0 zero not supported amp _ Chr 10 amp Chr 13 amp A fractionary number is converted to integer vbCritical voOKOnly Me newBase Focus Exit Sub End If 6 Calls the function to convert the number in the new base IntegerToBinary Ni b and stores the value in form s box Converted Value Me convertedValue Text IntegerToBinary Ni b Public Class Convesion Private Sub convertButton_Click ByVal sender As System Object ByVal e As System EventArgs Handles convertButton Click Dim Ni As Long b As Long If Trim Me decNumber Text Or IsNumeric Trim Me decNumber Text Fals
60. string converts string to uppercase In Visual Basic NET all this functions are available in the namespace Microsoft VisualBasic and must be prefixed with that construction such as in the call Microsoft VisualBasic Right Mihail Eminescu 8 that returns Eminescu 2 A logical expression can be e simple with the general syntax lt variable gt lt relation_operator gt lt variable gt or lt variable gt lt relation_operator gt lt constant gt lt relation_operator gt lt lt gt gt lt gt e complex with the general syntax e Eqv e2 equivalence e Imp e2 logical implication o Is 02 equal to compare two object reference string like pattern o IsNot o2 not equal to compare two object reference string like pattern VS 05 e XOr ez exclusive or e Like e2 pattern operand returns True if the first operand e matches the string pattern defined by the operand e2 V S 05 lt logical_expression gt lt logical_operator gt lt logical_expression2 gt where the ogical_operator can be And Or as binary operators connectives Not as unary operator returns the opposite of a Boolean operand AndAlso act just like And operator but it doesn t examine or process the second operand if the first one is False VS 05 OrElse act just like Or operator but it doesn t examine or process the second operand if the first one is True VS 05 INFORMATICS Computer Hardware and Programming in Visual
61. t Space 12 amp Format celsius 000 00 12 amp Chr 13 amp Chr 10 10 Next fahrenheit 11 MsgBox tabel Conversion Fahrenheit Celsius End Sub aOnahWN O ON Comments Line 0 is that in which the type of used procedure and scope declared public subroutine in our case together with the name that can be used later on to call the procedure Coresp_ Temp Notes The numbers associated to the lines can be typed as such in the source program they keep from previous versions of Basic The lines that follows after the line numbered 6 and the line numbered 9 are not numbered because they continuation lines of previous sentence A continuation is specified by placing an _ underscore character to the right of the line The writing of many instructions on the same line is also allowed by placing a colon character before each instruction Line 1 Dim min max pas fahrenheit celsius tabel declares and reserve the needed memory space In that line the variables min max pas celsius and tabel that haven t a data type specification are of Variant data type without a specific data type but adapted to those of the first expression in which is used and fahrenheit is a double precision variable Line 2 is a comment line introduced by an single apostrophe his role is to explain the role played by the routine Lines from 3 to 5 are assignment statements What is in the left of the called assignment operator s
62. t be longer than 255 characters 3 Can t contain embedded period or embedded type declaration character 4 Must be unique in same scope the range from which the variable can be referenced Variables are named storage locations that can contain data that can be modified during program execution they are reusable The variables are the memory cells used for storing program s input data and its computational results Using variables is a two step process declaration and assignment The explicit declaration of variables is realized in VB by using the Dim statement Dim variable As data_type variable As data_type where data type can be one of Byte Boolean Integer Long Single Double Currency Decimal String Date user_defined Variant Object as described in table 3 1 variable is a user identifier defined by following the naming rules The explicit declaration of variables can be combined with the assignment Dim variable As data_type value1 variable As data_type value2 Table 3 1 Visual Basic Data Types Required Data T Boundar Byte J J byte 0 to 255 Boolean 2bytes TrueorFalse Cd 0 to 65535 S O Char sd 2bytes SByte 1 byte 127 to 128 Integer Int16 3 Integer Int32 4 bytes 2 147 483 648 to 2 147 483 647 Long 4 bytes 2 147 483 648 to 2 147 483 647 long integer ee eee to 9 223 372 036 854 775 807 Long Int64 BE Bbytes Single 3 402823E38 to 1 401298E
63. terative method b Recursive method factorial n factorial 1 fact nxfactorial n 1 return fact n n 1 INFORMATICS Computer Hardware and Programming in Visual Basic 123 Function Factorial _Iterative n As Integer Function Factorial n As Integer As Double As Double Ifn 1 Then Dim fact As Double Factorial 1 fact 1 Else Fori 1Ton Factorial n Factorial n 1 fact fact i End If Next i End Function Factorial Iterative fact End Function The modern object oriented programming languages offers a for sentence with the syntax For Each Next that allow to apply a set of sentences to an object collection or to a multitude arrays vectors multidimensional massive without specifying the number of cycles that specification is difficult if the dynamic memory reservation used The syntax of that sentence is For Each element In group Sentences Next element Example For Each obj In ctl Tabs obj Caption LoadResString CInt obj Tag obj ToolTipText LoadResString CInt obj ToolTipText Next Loops can be nested just as If statements are Nested loops consist of an outer loop with one or more inner loop Each time the outer loop is repeated the inner loops are reentered their loop control expressions are reevaluated and all required iterations are performed The For instructions can be nested following the model For i sentences For j sentences Fork sentences Next
64. tions written in a language designed to make a computer perform a series of specific tasks The instructions tell computers exactly what to do and exactly when to do it A programming language is a set of grammar rules characters symbols and words the vocabulary in which those instructions are written Programming is the designing and writing programs A computer program does no matter if is a single procedure or function utility tool an application or the operating system itself is nothing else than a list of instructions that the microprocessor or generally processor can execute In turn an instruction is a specific pattern of bits representing a numeric code The computer sends to the microprocessor the list of instructions that forms the program code one by one At receiving of an instruction the microprocessor sees from the instruction code what function is to be done and executes the corresponding actions All the numeric codes allowed by a microprocessor as instructions form the machine language The pattern of bits representing instructions is no easy to be manipulated as such by humans For that reason they represented in a human meaningful 84 THE REPRESENTATION OF PROCESSING ALGORITHMS form The representation of instructions in a human meaningful form is called programming language Any algorithm must have the following properties e Generality the algorithms must solve a class of problems not a particular one
65. ub b We redefine the Min and Max functions by using the procedure Exchange Function Min x As Variant Variant As Variant If x gt y Then Exchange x y Min x End Function c We define a procedure that take as arguments the values of x and y and arrange them in ascending order called Asc x y We do that in two versions first realize all the operations and the second call the procedure Exchange x y In these example the values x and y are arranged sorted in ascending order in conformity with the used comparison operator lt in our case The algorithm can be conformed to any desired ordering by changing accordingly the y As Function Max x As Variant y As Variant As Variant If x lt y Then Exchange x y Max x End Function a b Figure 3 12 The definition of the algorithm for ascending ordering INFORMATICS Computer Hardware and Programming in Visual Basic comparison operator The implementations of the algorithms from figure 3 12 are By using the function exchange switch By programming all operations Sub Asc x As Variant y As Variant Sub Asc x As Variant y As Variant If x gt y Then Exchange x y Dim temp As Variant End Sub Ifx gt y Then temp x y temp End If End Sub d this sequence chooses the case for VAT percent for a VAT calculator 111 Private Sub PTvaGen If PT val Value True Then PrTVA PrTVA1 PTva2 Value False Ptvax Value False
66. value obtained is assigned to the name of the function Data_Paste as the value to be returned to the caller Line 6 End the function execution and returns the processing control to the caller VI The following procedures implement the division conversion method for decimal numbers to any base that is a power of 2 A cell rezervation and initialization with the the string of hexadecimal system Dim myDigits As String 0123456789abcdef Ask the user to type the values for number and base in a dialog box Each value typed by user is checked to be numeric If not numbers a message is given to the user and execution stops The function dec2base decimal number new base Sub Dec2IntAnyBase Dim b As String Dim d As Integer bb As Integer d InputBox Type an integer number If IsNumeric Trim d False Then MsgBox Type an integer value vbCritical voOKOnly Exit Sub End If b InputBox Type an integer number for base If IsNumeric Trim b False Then MsgBox Type an integer value vbCritical voOKOnly Exit Sub End If bb Int Val Trim b b dec2base d bb If b lt gt Err Then MsgBox d ToString amp in base amp bb ToString amp is amp b End If End Sub 132 THE REPRESENTATION OF PROCESSING ALGORITHMS Receives at call time a copy of the values for number and base and determines if the wanted base is a power of 2 two and which one If not a power of two or the base minus one
67. x0 End If End Sub End Class INFORMATICS Computer Hardware and Programming in Visual Basic IL For a nonnegative integer n the factorial of n written n is defined by a iterative mode a iterative method uE nl n n 1 n 2 3 2 1 for n gt 0 Function Factorial _Iterative n As Integer As Double Dim fact As Double fact 1 Initialize to 1 for product Do While n gt 0 fact fact n n n 1 Next cycle Loop fact fact n The returned value Factorial_ Iterative fact End Function Conditional Loop with Condition Evaluated After In this case the operation is executed first and then the condition is evaluated figure 3 18 operations It can be described as the operations are executed rage ndition gt the condition is evaluated kiii if the result of the evaluation of the condition is False True then loop to execute again the operations if the evaluation of the condition is True then Figure 3 18 Do Until continue the execution of the program and close the loop The syntax for the sentences that implements that structure are Basic Access VBA Do operations Loop While Until condition operations while conditions repeat operations until condition 119 120 THE REPRESENTATION OF PROCESSING ALGORITHMS Counter Loop Executes a set of statements operation within a loop a specified number of times figure 3 19 A variable is used as counter to sp
68. y Case 1 x AfiseazaBazaTva If Op1 0 Then MsgBox Nu pot sa impart la 0 ZERO 48 Calculator Else Op1 1 Val Op1 Readout Format Op1 4 4 AHH AHH AHH 00 End If Case AfiseazaBazaTva Op1 Val Op1 100 Case sqrt AfiseazaBazaTva If Op1 lt 0 Then MsgBox Nu pot sa Calculez Radical din Numere Negative 48 Calculator Else Op1 Sqr Val Op1 End If Readout Format Op1 HHH HHH HEH HHH 00 Case T V A If Op1 0 Then MsgBox De ce sa calculez Baza pentru valoarea TVA 0 48 Calculator Else ValBaza Val Op1 ValTva ValBaza PrTVA 100 BazaTVA Caption Str Format ValBaza H HHH HHH HHH HHH 00 TvaAferent Caption Str Format ValT va HHH HHH HHH HH 00 Readout Str Format ValBaza ValTva 4 4 444 444 4 00 End If End Select 3 4 Repeating Structure The repeating structure repeats a block of statements while a condition is True or Until a condition becomes True The repetition of steps in a program is called a loop The executions of such blocks follow the scenario while figure 3 15 the condition is evaluated and if the condition evaluates to e True then executes the block of statements e False then end the execution of the cycle Loop and continue the execution of the program If for the first time the condition is False the sentence block is simply skipped 116 THE REPRESENTATION OF PROCESSING ALGORITHMS Conditional Loop with Cond
69. ymbol are variable names min max pas What is in the right represents a constant and or expression in that case they are numbers and are called numeric constants On these lines we define two instructions one assignment and the second delimited from the first by a comment 128 THE REPRESENTATION OF PROCESSING ALGORITHMS Line 6 is an assignment line that initialize the variable named tabel with a character string formed by two lines string obtained by evaluating the string Fahrenheit Celsius expression Fahrenheit Celsius amp Chr 13 amp poo Conversie Fahrenheit Celsius 017 78 Chr 10 amp String 36 amp Chr 13 amp Chr 10 In 020 006 67 that expressions appears string constants enclosed i eee between concatenated by intermediate of amp 080 026 67 operator with the result of evaluation of string bee eee character text manipulation functions as Chr 140 060 00 String The character _ underscore appearing on 160 07111 i 180 082 22 line 6 instruct the compiler or interpreter that the 200 09333 command line is continued to the line that follows aen ma 260 126 67 Line 7 it introduces a processing cycle that expressed 280 13778 300 148 89 in a natural language as For the variable named fahrenheit starting with the value min fahrenheit min To value max with a Step equal to s from step by step execute the instructions from the lines that follows until the
70. yntax while condition do operation Second syntax While condition do Begin operations Exit End Exit means an unconditional exit from loop If the repeating structure is placed in the body of a subroutine function or procedure we can exit from the cycle by using the returning to caller commands Examples I Let be a a positive real number Define recursively the sequence of x of positive numbers as follow X0 1 xi 1 1 2 a x for i 0 1 2 Draw a flowchart figure 3 16 that reads in the value interactively and uses this algorithm to compute the square root of a it can shown mathematically that ote wa for i gt The algorithm stops when Figure 3 16 A flowchart for the Newton Raphson method x equals with x precision where precision is a positive fraction low value the desired precision that mean to be satisfied the following condition x x Sprecision The condition can be described as the difference from the current value x and the previous one x must be at least the desired precision for example 0 001 if the precision must be at the third decimal 118 THE REPRESENTATION OF PROCESSING ALGORITHMS This algorithm is derived from the so known Newton Raphson method in numerical analysis Figure 3 17 shows a form representing the interface for the implementation in Visual Studio 2005 of the algorithm depicted in figure 3 16 FE Newton_Raphson Va
71. ze the inter exchange permutation of the values assigned at execution time run time to the variables x and y in the sense defined by the used relational operator comparison The algorithm returns the values in the specified order figure 3 20 Sub Order x As Variant y As Variant relop As Variant Select Case relop Case lt Ifx gt y Then Exchange x y End If Case gt If x lt y Then Exchange x y End If INFORMATICS Computer Hardware and Programming in Visual Basic 125 End Select End Sub This code sequence is a possible implementation of the algorithm explained in the flowchart from figure 3 20 The declaration of variables as Variant allows using the subroutine Order to do his action on any kind of data type of the values passed in arguments text number date etc The routine can be generalized to receive at input an array vector or multidimensional massive or can be called as such from routines that processes such arrays by passing in arguments pairs of values IL Given a set of n values v i 1 1 2 3 n 2 1 Build the function that compute the sum Sum v n of this values a a The function Sum adds a series v of n numbers Function Sum v As Variant n As Integer As Double Sum 0 The initial value Fori 1Ton Sum Sum v i Next i End Function 2 2 Build the function that compute the average Avg v n of these values b and b b The function Avg computes the

Download Pdf Manuals

image

Related Search

Related Contents

Effective 5 Slot ATCA DC Shelf User Manual  ifddt Benutzerhandbuch  Lexmark C920dtn  Samsung SF-340 Manual de Usuario  Samsung 32" HD טלוויזיה J4303 סדרה 4 מדריך למשתמש  Ives 430 User's Manual  

Copyright © All rights reserved.
Failed to retrieve file