EXPLAIN COMMONLY USED TERMS AND CONCEPTS IN ... - …



PROGRAM IMPLEMENTATIONWhere do Low-Level and High-Level Languages fit in with Programming ImplementationBefore we start with the comparisons of these levels of programming languages, let's understand a few things!A computer program comprises a series of instructions.The CPU in a computer interprets these program instructions to complete one task or many tasks.These computer programs can be written using different languages that the computer can interpret and execute.These programming languages are categorised as either high-level or low-level languages.?Low-Level LanguagesMachine LanguageNow most CPUs (Central Processing Units) have their own special code to interpret their instructions. We call these set of instructions that only the particular computer can interpret?machine language. So they are many different machine languages. Most of the time the instructions in?machine language?are written in binary using zeros and ones.For example, 01100011 can be a specific instruction to move a number to a location.SO!Machine language is the only language that can be interpreted by computers (or rather the CPUs of computers)The instructions consist of a series of combinations of binary code, that is, zeros and ones (0 and 1)Because they comprise zeros and ones, it is very difficult for people to understand or interpret (it can be very confusing to remember what 00110101011 means!!)Any set of instructions that are written so that people can understand the instructions, must be translated back to machine language for the?computer's CPU to interpret and follow.Machine language is interpreted very quickly by the CPUWe call machine language a?LOW-LEVEL language?since it is closest to or ideally is the language of the computerMachine language is machine dependent. That is each computer has their own machine language that specific to them.?Assembly Language?Since machine code is very difficult for us (programmers and just about everyone else!) to understand, some parts of the binary code that represents instructions (like add, move, store etc.) are coded to help us understand them.?We call this?Assembly Language.?That is, we could use ADD 1100 instead of 1101 1100.Since we are using code to help us understand what instructions we are giving the computer, we now need to convert these instructions BACK to machine code for the ..yes..computer's CPU to interpret and run them!So:Instead of 1101 to mean Add, we would instead use, ah, say, ADD!, and instead of, say, 1110 for Subtract, we would use SUB for example.We therefore use short names to help with the instructions instead of the straight binary code.A special program called an assembler is used to convert the assembly language code to machine language code for the computer to executeAssembly language is also machine dependent?High-level LanguagesIt is so easy to write in your language of choice, just as this note is written in English!So programmers write their code in a?high-level language.These languages are quite similar to english-type words so it easier to understand.?High-level languages are easier to read, write and maintain.The closer the instructions are to english-type words or human languages (like French or even spanish too!), the more difficult it is for the computer to interpret these instructions.?So high-level languages must be interpreted or converted (we would say, compiled) into machine language before they can be executed/run by the computer?High-level languages are NOT dependent on the type of computer used, so many computers can run the same program, but it must still be converted for the particular computer to read (just like many people can read English, but you need a French dictionary or German dictionary for those who want it translated)Examples of high-level programming languages are BASIC, COBOL, C, C++, FORTRAN, Pascal, and PrologDistinguish among the different generations of programming languagesGenerations of Programming LanguagesThe?first generation languages, or?1GL?are?low-level languages?that are essentially written with?machine language code. Machine language code comprises binary code, that is, a series of zeros and ones (0,1).The?second generation languages, or?2GL?are also low-level languages that consist of?assembly?language.Assembly language uses structured commands in place of binary numbers allowing us to read the code easier than looking at?binary code. Although assembly language is easier to read than binary code, it is still a difficult language to understand.The?third generation languages, or?3GL?are?high-level languages such as?Pascal, C, and BASIC. Remember that a?high-level language?is not limited by the computer, so the same program can be executed on different computers. High-level languages are also easier to understand since their code uses some English-type words.?Language Example: Pascal ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? program Hello;??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? begin??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? Write('Hello world');??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? end.??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? BASIC ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? 10 print "Hello World!"??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? 20 END??? ??? ??? ??? ??? ??? ??? ??? ??? C #??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? include <stdio.h>??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? main()??? ??? ??? ??? ??? ??? ??? ??? ??? {?? ??? ??? ??? ??? printf ("Hello World!\n");??? ??? ??? ??? ??? ??? ??? ??? ??? }The?fourth generation languages, or?4GL?are languages that also consist of English-type statements. Fourth generation languages are commonly used in database programming and scripts.Typical examples of code used in 4GLs are:FIND ALL RECORDS WHERE NAME IS "NOTESMASTER"andSELECT * FROM Book WHERE price > 80.00 ORDER BY title;The?fifth generation languages, or?5GL?are programming languages that contain visual tools to help develop a program. A good example of a fifth generation language is?Visual Basic, which was used to create the following form:list the sequence of steps associated with implementing a programIn this section, we will convert some pseudocode to Pascal programs????????????????????????????????????? Problem 1Write a program that reads two values, determines the largest value and prints the largest value with an identifying message.AlgorithmStep 1:? ? Input VALUE1, VALUE2Step 2: ? if (VALUE1 > VALUE2) then? ? ? ? ? ? ? ? ?MAX? ? ? ? ? ? ? ?else?? ? ? ? ? ? ? ? ? ?MAX? ? ? ? ? ? ?endifStep 3: ? Print “The largest value is”, MAXPascal ProgramProgram Large_Small;Var value1, value2, max: Integer;BeginWrite('Enter the first number: ');Readln(value1);Write('Enter the second number: ');Readln(Value2);?if ? ? ? ? ? ?(VALUE1 > VALUE2)then ? ? ? ??MAX := VALUE1else?? ? ? ? ?MAX := VALUE2;Writeln('The largest number is: ',max);End.Problem 2Write an Program to convert the length in feet to centimeter.?Pseudocode:?Step 1:? Input?Len_FTStep 2: ? Len_CM?Step 3: ? Print Len_CM?Pascal ProgramProgram convert;Var Len_FT, Len_CM : Integer;Begin? ?Write('Enter the length in feet that you want to convert to centimetres: ');? ?Readln(Len_FT);? ?Len_CM := Len_FT * 30;? ?Writeln('The length in centimetres is: ',Len_CM);End.Problem 3Write a Pascal Program that will read the two sides of a rectangle and calculate its area.PseudocodeStep 1: ? Input W, LStep 2: ? Area = W * LStep 3: ? Print AreaPascal ProgramProgram convert;Var Width, Length, Area : Integer;Begin? ?Write('Enter the length: ');? ?Readln(Length);? ?Write('Enter the width: ');? ?Readln(Width);? ?Area := Length * width;? ?Writeln('The area is: ',Area);End.Problem 4This is a more complex program.?Write a program that asks the user to type in a sentence ending with a period. Then tell the user how many letters, numbers and blanks were in the sentence.It may be helpful to review the following program which counts the number of letters in a sentence:PROGRAM LetterCount;{Program counts the number of letters in a sentence}CONST Period = '.' ;VAR Count: integer;??? CH: char;BEGIN??? Count := 0;??? writeln('Write a sentence and end it with a period.');??? read(Ch);???? WHILE Ch <> Period DO BEGIN??? ??? Count := Count + 1;??? ??? read(Ch);??? END; {WHILE}??? writeln('The number of characters including blanks is ', Count);END.EXPLAIN COMMONLY USED TERMS AND CONCEPTS IN PROGRAMMINGFrom Source Code to Output?All computer programs must be converted / translated / compiled / interpreted into machine language before the computer's CPU can execute the instructions.?The source program comprises code written in a programming language such as BASIC, Pascal, C and so on.Depending on the level of programming language, the corresponding type of?Translator?will convert the source code to object code which is stored in the matching language program. This code is now at the point where the instructions can be executed by the computer to produce the output.Types of translators?Source ProgramSource Code is the language or words that we use to write the program. Just as English, or French or Spanish, or German is the language that people use to write with, then Pascal is one language that is used to write programming code. This code is called?Source Code.The rules of the language (called syntax) must be followed, in our example, it is the Pascal language.Again, just as English, and those other languages have their own grammar rules, such as spelling and sentence construction, Pascal programming language is no different.So you write your program using the required rules of the language that you are using.Source code is the programming code that is written in either:a low-level programming language such as assembly language, ora high-level programming language such as BASIC, Pascal, C, C++, etc.Translating the Source CodeTranslators are responsible for converting the source code into machine code for the computer to execute.The shaded gray areas above show the different types of translators that are used to convert source code to machine language code.If the source code was written using:an assembly language program, then an?assembler is needed to convert it to machine language codea high-level language program such as Pascal, then either a compiler or an interpreter could be used for the conversion.Since we have a choice of a compiler or an interpreter, let us look at these two in more detail:Comparison of a compiler and an interpreter?CompilerInterpreterHow is the source program translated?The entire program is translated before executionEach line of the program is translated and run before the next programming line is translated and runHow often is the source program translated?Each line of programming code is translated once into object code and kept for execution laterEach line of the source code must be translated into object code every time the program is executed (run)Can the object code be stored for later use?Yes, the object code can be stored and executed (run) laterNo, the object code must be translated from the source code each time it needs to be executed (run).?Executing the Object CodeThis is the machine language code that can now be executed by the computer to follow the instructions and produce some output. Sometimes, when a program is compiled, there are various sub-programs in object code that are created. Before executing the object code, these sub-programs must be?linked together to form one set of object code.?Maintaining programsPrograms need to be kept up to date, or maintained in order to remain useful. Maintaining a program can involve adding extra tasks, entering more data of a different form or outputting data in a different format.Other examples include a?tax rate may need to be changed or a zip code may need to be added.?EXPLAIN COMMONLY USED TERMS AND CONCEPTS IN PROGRAMMING Common Terms and Concepts in ProgrammingThese common terms and concepts that will be explained are used as we move through the phases from writing programming code to seeing your output!Two important parts of programming are:Testing your program, andDebugging your codeTesting your programTesting your program involves checking your programming code for any errors. This checking is done at various stages of the programming cycle. You test your program to ensure that it is written correctly, that is produces the correct output and also to make sure that if any wrong data is input, an appropriate message is output to alert the user.Let us first go through the types of errors that can occur as you write, compile and execute your program:Dry RunPerforming a dry run is usually done once you have written your algorithm or your program in a particular language such as Pascal.This is when you use sample data and manually go through the steps of the program, performing all calculations, writing any output until the data input has be manipulated and some result is produced and output.An example of a dry run is using a trace table where all of the variables are written in a table format.??Syntax ErrorsWhen you compile your source code, the compiler will check to see if you have written your program using the correct syntax (grammar, sentence structure, language rules).?If there are any problems with the syntax, then the compiler will print a list of syntax errors on the screen for you.Sometimes, the compiler will give you a line number in your program to indicate where an error could have possibly occured?When you get a?syntax error, ?the compiler cannot convert any more source code to object code until all syntax errors are corrected. This means that sometimes you have to compile your program many many times to correct all of the errors.An example of a syntax error would be say, a missing semicolon (;) at the end of the Pascal statement, or omitting the?DO in a For loop statement such as 'For count := 1 t0 10', when it should be?For count := 1 to 10 Do?Run-time errorsYour program may have compiled with no errors, and is converted to object code. You are now ready to execute (run) this object code to see what results you will get. Run-time errors are known when you execute your program.?As you execute your program, you will know when a run-time error occurs! The system MAY hang, or you may get an error message that looks like the one below. Sometimes you may have to restart your Pascal application if the error is severe.??A typical example of a run-time error is in performing a calculation, and the statement tries to divide by zero (such as 24 / 0 = ??)The program does not know what to do so it aborts or stops.?Logic ErrorsThis is the time when you will know if the logic of your program will produce the correct results. A logic error?is when your results do not produce the output you expect. For example, you may want the program to produce the smallest number, but it shows the biggest number instead, or you have an IF statement in your program that should output Girl if the character is 'G' and Boy if the character is 'B'. However the result shows G for?Boy and?B for?Girl. These?are examples of?logic errors. The?syntax is correct, but the meaning or logic of the program is faulty.?Debugging your codeNotice that we had three types of errors at different stages in compiling and executing (running) the Pascal program. Once you have been given an error message, you need to?debug it.Debugging?is when you go through your Pascal code to look for (syntax, run-time, logic) errors in the program, and correct each error.Sometimes it is best to correct one error at a time, then compile and execute again, so that you make sure that you don't add more errors to the program.Test DataOnce you have debugged your program and it is now error-free and producing reasonable results and output, you should now test it is various types of data to see how your program performs. You will use test data.Test data involves using data for input, such as 0 or a VERY large number, letters where numbers are required, numbers where letters are expected, different formats of currency, dates and so on in the various fields so that you know exactly what ?error messages you will have and if the program does give an error message or if it hangs up.Your program should never hang, it should stop before it does, by giving you an error message or allowing you to save your files before the program closes.?ELEMENTARY DATA TYPESIt you think of programming as a special code that you are deciphering or need to encrypt so that special agent 'PC' can follow the instructions, then you can make programming fun!So what are elementary data types?'Elementary' suggests basic information, so think of elementary data types as some basic types of code that is necessary to tell 'Secret Agent PC' what data is being sent, received or processed, alright?The basic data types are:Integers (e.g. 1, 45, 90. That is a whole number with no decimals)Real Numbers (e.g. 45.5, 0.95. That is a number with a decimal)Characters (referred to as?Char in Pascal.?e.g. 'L', 'E', or 'R'. That is, a letter!)String (e.g. Pamella, 994-2354, Stop!, Enter, USA, ***B12***. That is a combination of characters)?In writing a Pascal program, you should state what data types you will be using. This is called declaring your variables.So we indicate that these elementary data types will contain values that will change (vary) during the life of the program as numbers and / or characters are swapped in and out of the data names.How do we do it?Here is the code:?VAR variable_Name?: Data_type;?Note the five important pieces in the above statement:VAR indicates that the data will vary during the programVariable_Name indicates the name that you the user will give, just as you, your family, friends and pets have a name for a each person:?separates the name(s) of the variables from the data type. It is similar to english when you have commas and other punctuation.Data_Type will be either Integer, Real, or Char;?represents the end of the program line?So some examples that use variables which can only contain integer data (numbers) are:VAR?Mark?: Integer; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?E.g. Mark can contain the values 20, 15, 67, for exampleVAR?Age?:?Integer; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? E.g. Age can contain 34, 16, 18, for exampleVAR?Number_of_children?:?Integer; ? ? ? ? ? ?E.g. number_of_children can contain 2, 3, 6, for example?Notice that these three variables have been declared for the same data type, which is Integer. These variables can also be declared on one line, as follows:Integer data typeVAR Mark, Age, Number_of_children : Integer;?So some examples that use variables which can only contain real data (numbers) are:VAR?Average_Mark?:?Real?; ? ? ? ? ? ? ? ? ? ??E.g. Average_Mark can contain the values 55.8, 75.9, 90.0, for exampleVAR? temperature?:?Real?; ? ? ? ? ? ? ? ? ? ? ??E.g. temperature can contain the values, 98.4, 32,1, 30.1, or 29.7, for exampleVAR?km_per_hr?:?Real?; ? ? ? ? ? ? ? ? ? ? ? ? ?E.g.?km_per_hr?can contain the values 60.4, 34.9, or 104.2, for example?Again, these three variables can be declared on one line as follows:Real data typeVAR Average_Mark, Temperature, km_per_hr : Real;Some examples that use variables which can only contain character?data (letters ) are:VAR?Grade?:?char; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?E.g. Grade?can contain the values 'C', 'B', or 'A' for exampleVAR? Result?:?char?; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??E.g. Result?can contain the values, 'P', or 'F', for exampleVAR?Raining?:?char?; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?E.g. Raining?can contain the values 'Y' or 'N', for exampleNotice that the values entered in these variables are enclosed in single quotes.Yes indeed, here we go with writing the above three variables on one line:VAR Grade, Result, Raining : Char;String data type?Some examples that use variables which can contain combinations of letters, letters and numbers, combinations of letters with numbers along with special characters are:VAR?Name: string; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?E.g. Name can contain the values 'Carla Sinclair', . 'Morris Benjamin', or 'Alrick Taylor' for exampleVAR? Address?:?string?; ? ? ? ? ? ? ? ? ? ? ? ? ? ?E.g. Address?can contain the values, 'Pineapple . . Avenue', for exampleVAR?Tel_Number?:?String?; ? ? ? ? ? ? ? ? ? ??E.g. Tel_Number can contain the values '1-876-342-2569' ,. . for example?Notice that the values entered in these variables are enclosed in single quotes.This is how we write the three above variables on one line:VAR Name, Address, Tel_Number? : string;Declaring Variables and ConstantsDECLARING VARIABLES AND CONSTANTSIn the previous section we explained how integers, real numbers and characters can be declared in Pascal.Here are the examples again:VAR Mark, Age, Number_of_children : Integer;VAR Average_Mark, Temperature, km_per_hr : Real;VAR?Grade, Result, Raining?:?char; ??Now, if you are declaring the above nine variables in a Pascal program, then you only need to write the Pascal word?VAR once, as shown below:VAR Mark, Age, Number_of_children : Integer;? ? ? ? Average_Mark, Temperature, km_per_hr : Real;? ? ? ? Grade, Result, Raining?:?char; ??Variable and Constant namesIt is best to use variable and constant names that are meaningful and represent what the data will hold. For example, height and width suggest, yes, the height and width of something, compared to?x, y : real;. Weeks or months from now, you may not remember what values?x?or??y?were supposed to contain!?Declaring ConstantsTo declare a constant, we use the Pascal word?CONST. A constant will contain the same data for the entire program and will not change.Its declaration is:CONST PI = 3.14;?Notice the difference between the declarations for a constant and a variable.?MANIPULATE DATAInput, Processing, and OutputIn previous sections, we introduced input and output devices. For example, data can be input to the computer using a keyboard, a mouse or by voice commands. while information can be output using the monitor, a printer, or even stored for later use.As programs are written, instructions need to be used to allow for this data to be input and information output or storage.?Let us look at those instructions using the Pascal programming language.Getting data into the computerThe two Pascal words that are used to accept data through an input device, are:READREADLNRead?and Readln?accept specific data into a variable that has been previously declared. ?For example, consider the following declaration:VAR mark: Integer;This declaration means that the variable?mark can only accept integer values.To read values into the variable?mark, the following statement can be used:Read(mark);orReadln(mark);When the program is executed (run), when the programming statement read(mark); is reached, the cursor on the screen blinks and waits for the user to enter an integer, such as 23, 10, 0r 55.Note that if you enter the number 55.6 or the character 'P', the program will be halted, and an error message will be shown on the computer screen, for example. This is because, the variable mark can only accept integer values.Now, what is the difference between read and?readln?It's all about what the cursor does after the value has been entered.For Read, after the value say, 50 has been entered, the cursor remains next to the value, as shown below. Let?the symbol | represent the cursor.50 |?For?Readln, after the value 50?has been entered, the cursor moves to the next line below, as shown in the example below. Again, the symbol | represents the cursor50 |?Viewing Information?The Pascal commands for viewing your output are quite similar to entering data.The two Pascal words that are used to view your information using an output device such as a monitor, are:WRITEWRITELNWrite and Writeln?output statements, prompts and results typically to a screen or printer. ?Let us use the previous example to illustrate the Write and Writeln statements:VAR mark: Integer;Again, remember that this declaration means that the variable?mark?can only accept integer values.?To output (write) a Statement?You can output statements for the user such as the examples below:Write('This program will add two numbers and output their sum');Writeln('This program will add two numbers and output their sum');?When the program is executed (run), the output to the screen or printer will be:This program will add two numbers and output their sum?Note that the write and writeln are similar to read and readln regarding where the cursor is placed after the line is output to the screen. So for example, for:Write('This program will add two numbers and output their sum');?The cursor will remain after the output, as shown below:This program will add two numbers and output their sum |?Whereas for:Writeln('This program will add two numbers and output their sum');The cursor will move to the line below the statement that is output, as shown below:This program will add two numbers and output their sum|?To output (write) a statement that prompts the user to do somethingHere, the use of write or writeln statements are used with read or readln statements.For example, to ask the user to enter two numbers using the keyboard, you would want to use the following statements:Write('Enter a number between 1 and 10: ');Readln(num1);Write('Enter another number between 1 and 10: ');Readln(Num2);?Notice how we have used the?ln for the readln. The first statement prompts the user to enter a number, and waits for the user to enter the number next to the statement or prompt.?Enter a number between 1 and 10:|???Once the user has entered the number the cursor goes to the next line and waits for the next instruction.Enter a number between 1 and 10: 6|This next instruction is also a prompt to ask the user to enter another number between 1 and 10. Again the cursor stays at the end of the prompt waiting for the user to enter the second number before moving to the line below:?Enter another number between 1 and 10:?3|?To output the result of this addition, we need to work out the answer:Sum := num1 + num2;Write('The sum is ');Writeln(sum);?This will output:The sum is 9?Notice we have two statements to output the answer.?However, we can also use one writeln statement to get the same output, as follows:Writeln('The sum is ',sum);Notice the comma after the quotation mark, then the variable that will output the actual number which is 9 in this example.??SummaryRead, write vs.?Readln, Writeln?Readln?is like?Writeln:? After the command is complete, the cursor moves to the next line??Read is like Write: After the command is complete, the cursor stays on the same line???CONSTANTVARIABLEExample????Pascal WordCONST?VAR?CONST Pi ?= 3.14;????Assignment=?:?VAR Height, width : Real;?Assigning Initial ValuesSometimes you would want to ensure that all variables start with some value or a 'clean slate' before any calculations are added to them. This ensures that you get the correct results held in these variables.?To initialize a constantWhen you declare a constant, this is the same as initializing it, since the value assigned to it does not change.CONST pass_mark = 50;?To initialise a variableHere are some examples to initialize variables. Remember you are assigning a value to it so the assignment?:= is usedMark := 0;Age := 0;Number_of_children := 0;Average_Mark := 0.0;Temperature := 28.5; (if you are using the temperature to say, compare with another temperature)km_per_hr := 60;?Grade: ' ';Result := 'P'; (suppose you want the result to be a Pass (P) to start off and change as you go through the particular program)Raining?:= 'N'; ?(that is, for dry season, suppose most of the days will be sunny, you can assign Raining to 'N' (no rain), and then update to 'Y' (rain) if there is an odd day that it does rain!)CONTROL STRUCTURESConditional BranchingConditional branching involves making a choice between one or two options.Here is the algorithm for a problem to find the average of a set of numbers.Read the number of marks to be averaged into variable called TotalMarksSet Sum to zeroSet Count to zeroWhile Count <> -1 DO? ? ?BEGIN? ? ? ? ? Read the mark? ? ? ? ? IF (Mark <> -1) ? {we have NOT come to the end of the marks}? ? ? ? ? THEN BEGIN? ? ? ? ? ? ? ? ? ? ? Add the mark to Sum? ? ? ? ? ? ? ? ? ? ? Add 1 to Count? ? ? ? ? ? ? ? ? ?END? ? ?END ?{While}Compute the Average (Sum/TotalMarks)Print the average?The IF-THEN statement here will allow the mark to be added to the Sum and also to continue counting how many marks are being entered ONLY IF the mark entered is NOT equal to -1. Remember -1 here is being used as a signal that we have come to the end of the marks that we are adding up.?So if we have a set of marks, they could be:9, 5, 7, 6, 3, 8, 9, 7, -1?These numbers then show that we have eight marks and the 9th number is -1 to indicate that we have no more marks to enter.?Here is the Pascal code that includes an IF-THEN statement :?Program IFTHEN;VAR Sum,num, Mark:: Integer; ?? ? ? ? ? ? ? ? ? ? ? ? ? ?{Assuming the marks are integers, otherwise . they can be of type Real}?? ?Average: Real;BEGIN? ? Sum := 0; ? ? ? ? ? ?{Initialise Sum to zero to add the marks . . entered}? ? Count := 0; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? ? ?{Prompt for the total number of marks to be . . averaged}? ? While (Mark <> -1) ?DO? ? BEGIN? ? ? ? Write("Enter a mark: "); ? ? ? ?{Enter the marks individually}? ? ? ? Readln(Mark);? ? ? ? ?IF (Mark <> -1)THEN BEGIN? ? ? ? ? ? ? ?Sum := Sum + Mark: {Add the mark to the Sum, to get the . total}? ? ? ? ? ? ? ?Count := Count + 1;? ? ? ? ? ? END;? ? END; {While}? ? Average := Sum/Count;? ? Writeln("The average mark is ",Average); Readln;END.??Once the Mark entered is -1, the average is then calculated and output. However, if the Mark entered is not equal to -1, then the mark is added to the sum of marks, and the count is incremented.??Can we improve on this program??Yes we can!Program IFTHENELSE;VAR Sum,num, Mark:: Integer; ?? ? ? ? ? ? ? ? ? ? ? ? ? ?{Assuming the marks are integers, otherwise they can be of type Real}?? ?Average: Real;BEGIN? ? Sum := 0; ? ? ? ? ? ? ? ? ? ? ? ? ? ?{Initialise Sum to zero to add the marks entered}? ? Count := 0; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??{Prompt for the total nnumber of marks to be averaged}? ? While (Mark <> -1) ?DO? ? BEGIN? ? ? ? Write("Enter a mark: "); ? ? ? ? ?{Enter the marks individually}? ? ? ? Readln(Mark);? ? ? ? ?IF (Mark <> -1)? ? ? ? ?THEN BEGIN? ? ? ? ? ? ? ? ? ? ?Sum := Sum + Mark: ? ?{Add the mark to the Sum, to get the total}? ? ? ? ? ? ? ? ? ? Count := Count + 1;? ? ? ? ? ? ? END? ? ? ? ?ELSE BEGIN ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{Else, the Mark entered is -1 }? ? ? ? ? ? ? ? ? ???Average := Sum/Count;? ? ? ? ? ? ? ? ? ? ?Writeln("The average mark is ",Average);? ? ? ? ? ? ? END;? ? ? END; {while}LOOPSDesign:?Pseudocode?refinement?The FOR LoopRead the number of marks to be averagedSet Sum to zeroFOR?GradeNum =?1 TO?TotalMarks?DO? ? ?BEGIN? ? ? ? ? Read the Mark? ? ? ? ? Add the mark to Sum? ? ?END ?{FOR}Compute the AveragePrint the average?Note that when you use the FOR loop you must know how many times you want to perform an action. This causes problems if you didn’t know how many times an action was to be performed?Here is the Pascal code that uses a FOR loop:?Program FORLOOP;VAR Sum,num, Mark,TotalMarks: Integer; ? ? ? ? ? ? ? ? ? ? ? ? ?{Assuming the marks are integers, otherwise they can be of type Real}? ? ? ? Average: Real;BEGIN? ? Sum := 0; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{Initialise Sum to zero to add the marks . . . . entered}? ? Write("Enter how many marks you will be averaging" "); ? ? ? {Prompt for the total number of marks to . be averaged}? ? Readln(TotalMarks);? ? FOR num := 1 to TotalMarks DO? ? BEGIN? ? ? ? Write("Enter a mark: "); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? {Enter the marks individually}? ? ? ? Readln(Mark);? ? ? ? Sum := Sum + Mark; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{Add the mark to the Sum, to get the total}? ? END;? ? Average := Sum/TotalMarks;? ? Writeln("The average mark is ",Average);END.??The WHILE loopWHILE (some Boolean expression is true) DOsome particular action?Here is the algorithm for the same problem to find the average of a set of numbersRead the number of marks to be averaged into variable called TotalMarksSet Sum to zeroSet Count to zeroWhile Count < TotalMarks?DO? ? ?BEGIN? ? ? ? ? Read the mark? ? ? ? ? Add the mark to Sum? ? ? ? ? Add 1 to Count? ? ?END ?{While}Compute the Average (Sum/TotalMarks)Print the average??Here is the Pascal code for the while loop:?Program WHILELOOP;VAR Sum,num, Mark,TotalMarks: Integer; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{Assuming the marks are integers, otherwise they can be of type Real}?? ?Average: Real;BEGIN? ? Sum := 0; ? ? ? ? ? ? ??{Initialise Sum to zero to add the marks entered}? ? Count := 0; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? ? ? ? {Prompt for the total number of marks to be averaged}? ? Write("Enter how many marks you will be averaging" "); ? ? ??? ? Readln(TotalMarks);? ? While Count < TotalMarks DO? ? BEGIN? ? ? ? Write("Enter a mark: "); ? ? ? ? ?{Enter the marks individually}? ? ? ? Readln(Mark);? ? ? ? Sum := Sum + Mark: ? ? ? ? ? ?{Add the mark to the Sum, to get the total}? ? ? ? Count := Count + 1;? ? END;? ? Average := Sum/TotalMarks;? ? Writeln("The average mark is ",Average);END.The REPEAT Loop?Repeat? ? Series of stepsUntil?(some Boolean expression is true)??Here is the algorithm for the same problem to find the average of a set of numbersRead the number of marks to be averaged into variable called TotalMarksSet Sum to zeroSet Count to zeroRepeat?? ? ?BEGIN? ? ? ? ? Read the mark? ? ? ? ? Add the mark to Sum? ? ? ? ? Add 1 to Count? ? ?END ?{Repeat}Until??(Count < TotalMarks)Compute the Average (Sum/TotalMarks)Print the average??Program WHILELOOP;VAR Sum,num, Mark,TotalMarks: Integer; ? ? ? ? ? ? ? ? ? ? ? ? ?{Assuming the marks are integers, otherwise they can be of type Real}? ? ? ? Average: Real;BEGIN? ? Sum := 0; ? ? ? {Initialise Sum to zero to add the marks entered}? ? Count := 0; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{Prompt for the total number of marks to be averaged}? ? Write("Enter how many marks you will be averaging" "); ? ? ??? ? Readln(TotalMarks);? ? While Count < TotalMarks DO? ? BEGIN? ? ? ? Write("Enter a mark: "); ? ? ? ?{Enter the marks individually}? ? ? ? Readln(Mark);? ? ? ? Sum := Sum + Mark: {Add the mark to the Sum, to get the total}? ? ? ? Count := Count + 1;? ? END;? ? Average := Sum/TotalMarks;? ? Writeln("The average mark is ",Average); Readln;END.?Notes on While and Repeat Loops?With these types of loops, at least one of the statements in the loop must change the value of the Boolean expression so it will eventually become false, and move on to the other statements in the program.? Otherwise, the loop will execute forever (this is called an infinite loop).?The variables in the Boolean expression that controls the WHILE loop must all be defined.? ?If they are not defined in an earlier part of the program, you must initialize them before the loop begins.??Suppose you want to jump out of the loop?The above examples illustrated the calculation of a specific number of marks that you want to find the average of. Sometimes you may not know how many marks are to be entered.This is where we use a value that when we enter it, it forces us to stop executing the statements in the loop, and jump out of the loop, so to speak.?So, we use what is sometimes called a sentinel?A sentinel is a piece of data that indicates that you want to stop executing the loop, or that you have reached the end of the data that you have been entering. Values such as 999 or -1 are used as sentinels to indicate that you have reached the end of the data.??For example, if we write a program that a teacher uses to enter the marks for a test, the value AFTER the last test mark?can be indicated by a -1.??Manipulate data in a listArraysSuppose you wanted to count some eggs. You could put them in a bowl as you count them or you could use an egg box.Sometimes it i best to have an area that contains just the amount to space for you to count, add, subtract or manipulate your data.An Array is used to store variable data having the?same?data type, like all integer, or all real values or all characters.An Array is like a small fixed number of boxes joined together one after the other storing values that are the same type. Once you declare an array to be a certain length, then it remains that?same size throughout the time the program is being executed or run, and cannot be changed.The following diagram illustrates an array with 5 locations. Each location or cell can contain values of the same data type (such as, Integer, Real or character)??Declaring an arrayThe format to decare an array is:var arrayname : array [firstcell..lastcell] of data type;?Arrayname can be any name given to your array. You can use the hyphen to join two or more words together like 'array_name'.Examples of declarations are :var our_data : array[1..5] of Integer;This declaration means that?our_data?is an array that comprises integers that can be contained in a maximum of 5 cells.Each element (integer, ?in our example) in the cell can be accessed individually, not affecting the others.?Consider the following declaration again:Var myarray : array[1..6] of char;Here,?myarray?is an array that comprises a maximum of six slots that can each hold one character onlyEach element (character in this example) in the cell can be accessed individually, not affecting the others.?Initializing an arrayJust like variables, arrays should also be initialized, otherwise garbage will be stored in them. ?Suppose you have the same declaration below:var our_data : array[1..5] of Integer;?If you want to initialize the two arrays. Let us initialize the?our_data?array to 0 and initialise the?myarray?array to empty spaces:?This is how arrays are initialized:?For x := 1 to 5 DO? ? our-data :=0; ? ?{ place the number 0 in each element location}????For x := 1 to 6 DO? ? ?myarray := ' '; ? ?{place a space in each cell location"???Assessing data in an array?So how do we access one or more elements in array our_data??To put the integer 10 in the first slot in the?our_data array, we use the following assignment statement:our_data[1] := 10;To put another integer 25 in the forth slot in the?our_data?array, we use the following assignment statement:our_data[4] := 25;?If you check the first element, it is still 10. Even when ?the second element with 15 is placed in the 4th location, the first one still keeps its value.??So how do we access one or more elements in array?myarray??To put the letter (character) 'C' in the forth slot in the?myarray?array, we use the following assignment statement:our_data[4] := 'C';???Searching your array for values - Traversing an arraySuppose you had some letters stored in an array and you wanted to find out at what location is the letter?L?was stored..Here we use a FOR statement to go through each cell to find the letter 'L' and let us know if it was found or not.?FOR x := 1 to 5 DO? IF myarray[x] = 'L'? THEN Writeln('Found the letter L at location ", x);?Here is would return the output?Found the letter L at location 2.?Reading from and writing to arraysTo write the contents of the above array the Pascal code is:FOR x := 1 to 6 DO? ?Writeln(myarray[x]);?This would output:BL?C?A?Whereas, if we had the Pascal code:FOR x := 1 to 6 DO? ?Writeln(myarray[x]);?The output would be:BL?C?ANotice the spaces between L and C, and also C and A?To enter data into an array the Pascal code is:FOR x := 1 to 6 DOBEGIN? ? Write ('Enter a letter ');? ? ?Readln(myarray[x]);End;Perform checks and test your program to verify correctnessTesting and Debugging Techniques?In section 4, we discussed testing and debugging, so let us explore these in a bit more detail.Recall that:Testing is used to find errors in your program code. These errors can be syntax, logic, or run-time errors.Debugging finds the source of the error in the program in order to fix it.Usually, a programmer would create a set of?test cases.You can perform:Black Box testing?which tests that the data input produces the expected output only.White Box testing?which tests?as many sections of the program as possible, from data entry, to every loop, branch or condition, and result or statement output:If your program is subdivided, then you can test the individual sections with the test data, before testing the overall program. This helps you to identify any errors in the various sections and fix them before testing the entire program.You can also test your program by letting groups of users test the program ?to report any errors or problems to ensure that it has no errors before it is marketed to the public for sale or integrated into a bigger program.?Write documented programs DocumentationHave you ever tried to understand someone's handwritting when they are not around to explan what they have written? It can be frustrating sometimes!Well, sometimes programmers write programs that are used for many years, until at some point, it needs to be upgraded or modified for some change or addition. Most likely that programmer has moved on to other green pastures and cannot be located, even if s/he wanted to be contacted.This is when documentation becomes a life- saver!Documentation gives the current programmer, an insight into what the previous programmer's thoughts and ideas were when the solution was created. So instead of having the re-invent the wheel, documentation can help speed up the process of maintaining the application and hopefully, the upgrades or additions would be completed faster than if there were no documentation present.Now!There are different types of documentation:Internal Documentation (for the programmers)External Documentation (for the end users)?Internal DocumentationSome languages, like Pascal, were designed to be 'self-documenting', but many other programs such as C or C++ for example can be difficult to understand without some explanation.Internal documentation provides notes to programmers about what the program code is intended to do and why. You would be surprised to how quickly the original programmer could have forgotten why s/he wrote the code in a particular way (although it is sometimes to save memory or to have the program run faster)!With well written internal documentation, a different programmer can make these adjustments without affecting other parts of the program.?The following Pascal program was written without any Internal Documentation:?PROGRAM LetterCount;CONST Period = '.';VAR Count: integer;CH: char;BEGINCount := 0;read(Ch);?WHILE Ch <> Period DO BEGINCount := Count + 1;read(Ch);END; {WHILE}writeln(Count);END.Imagine if you had a Pascal program that was 60,000 lines long!!The program asks the user to type in a sentence ending with a period. Then at the end, it tells the user?the number of letters in the sentence.It is is with SOME internal documentation. Notice how the use of tabs and blank lines also help to make the program more readable.PROGRAM LetterCount;{Program counts the number of letters in a sentence}CONST Period = '.';VAR Count: integer;??? CH: char;BEGIN??? Count := 0;??? writeln('Write a sentence and end it with a period.');??? read(Ch);???? WHILE Ch <> Period DO BEGIN??? ??? Count := Count + 1; {count the characters in the sentence}??? ??? read(Ch); {Read another character in the sentence}??? END; {WHILE}??? writeln('The number of characters including blanks is ', Count);END.Notice:How the use of tabs and blank lines also help to make the program more readable.The names of the variables that are also used:?Count is used to count the characters in the sentence;?ch is the variable that holds the character as it is read?Period?represents the full-stop at the end of the sentence which also denotes the end of the sentence.?These all help make the Internal Documentation easy to understand and maintain..?External Documentation?External documentation is usually presented as Manuals, whether in paper or as an online version. They help the end-user or customer understand how the program or application works,?identify hardware or software needed for the application, give installation instructions, explain?what the features are, ?and how to use them.The HELP icon in many applications is an example of external documentation. It is somewhat like an online manual.?Manuals are an example of External Documentation?? ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download