Program Control Structuresprogram control structures are blocks of statements that determine how statements are to be executed, in structured programming languages, there are three control structures namely; sequence, selection and iteration (looping) SequenceIn this structure, the computer reads instructions from a program file starting from the first top line and proceeding downwards one -by -one to the end. This is called sequential programming execution i.e. SelectionIn selection control, execution of statements depends on a condition which is either a true or false There are four types of selection controls. Namely:
The IF....THEN selection is used if only one option is available. All other options are ignored Format: IF <condition> THEN Statements; ENDIF IF....THEN....ELSE This type of selection is suitable where there are two available options General Format IF <condition> THEN Statements; ELSE Statements; EndIF Nested IF Selection This type of selection is used where two or more options have to be considered to make a selection. General Format IF <condition> THEN statements ELSE IF <condition> THEN statements ELSE IF<condition> THEN Statements ELSE Statements ENDIF ENDIF ENDIF CASE Construct This is an alternative to the Nested IF especially where there are several options to choose from. Its preferred because it reduces the many lines of code. However, the boolean expression for the case selection can only be expressed using integers and alphabetic characters only. The General format should be CASE integer OF or CASE Char OF Example: Case x of label 1: statement 1 label 2: statement 2 label 3: statement 3 . . . label n: statement n-1 Else statement Endcase Iteration (looping)Iteration is also referred to as looping or repetition. Its designed to execute the same block of code again and again until a certain condition is fulfilled. The three main looping controls are:-
The "WHILE" loop is used if a condition has to be met before the statements within the loop are executed. General Format WHILE condition DO statement ENDWHILE The REPEAT....UNTIL loop The REPEAT....UNTIL loop allows the statements within it to be executed at least once since the condition is tested at the end of the loop. General Format REPEAT statements UNTIL <condition> The FOR Loop
The FOR loop is used in circumstances where the execution of the chosen statements has to be repeated a predetermined number of times. General Format //pseudocode for 'FOR" loop that counts from the lower limit FOR loop variable = lower limit to upper limit DO statements ENDFOR
0 Comments
PROGRAM DEVELOPMENT.Stages involved in the program development cycle. The process of program development can be broken down into the following stages:
Problem recognition.Problem recognition refers to the understanding and interpretation of a particular problem. The programmer must know what problem he/she is trying to solve. He/she must also understand clearly the nature of the problem & the function of the program. In order to understand a problem, look for the keywords such as compute, evaluate, compare, etc. Usually, a programmer identifies problems in the environment and tries to solve them by writing a computer program. There are 3 situations that cause the programmer to identify a problem that is worth solving:
Sample problem: Develop a program that can be used to calculate/find the area of a circle. Use the equation A = π * r2. Problem definition (Problem Analysis).In Problem definition, the programmer tries to define (determine) the:
For example: In calculating the area of any circle, the parameters needed to determine the area of any circle are:
Note. Problem definition should be done thoroughly to ensure user satisfaction, and to facilitate the subsequent stages in the program development cycle. A failure at this stage usually results in a system that will not work as intended, or that may not work at all.
Program designProgram design is the actual development of the program’s process or problem solving logic called the Algorithm. It involves identifying the processing tasks required to be carried out in order to solve the problem. The design stage enables the programmer to come up with a model of the expected program (or a general framework (outline) of how to solve the problem, and where possible, break it into a sequence of small & simple steps. The models show the flow of events throughout the entire program from the time data is input to the time the program gives out the expected information.
Note. It is important to design programs before entering them into the computer. The programmer should only attempt to covert a design into a program code after ensuring that it is logically correct. If possible, check the logical order on the desk. Some programmers produce rough & ready solutions at a Keyboard, and continue to amend the programs until eventually the program appears to do what was expected. This is not recommended in programming because of the following reasons:
Modular programmingMany programs are non-monolithic (i.e., they are not usually made up of one large block of code). Instead, they are made up of several units called modules, that work together to form the whole program with each module performing a specific task.This approach makes a program flexible, easier to read, and carry out error correction. Program codingProgram coding is the actual process of converting a design model into its equivalent program. Coding requires the programmer to convert the design specification (algorithm) into actual computer instructions using a particular programming language. For example; The programmer may be required to write the program code either in Pascal, C++, Visual Basic or Java, and develop (invent) suitable identifiers, variable names, & their data types. However, remember that, at this stage the coding is still a Pencil & paper exercise. The end result of this stage is a source program that can be translated into machine readable form for the computer to execute and solve the target problem. Rules followed in coding a program.
Example 1: Develop a program code that would be used to solve the equation of a straight line given by the expression: Y = mx + c Program StraighLine (input, output);
VAR BEGIN
y, m, x, c: INTEGER;
Writeln (‘Input the value of M’); END.
Readln (M); Writeln (‘Input the value of X’);
Readln (X); Writeln (‘Input the value of C’);
Readln (C); Y: = (m * x) +c;Writeln (‘The value of y is:’, Y);
Explanation of the Pascal source code aboveProgram StraightLine (input, output); This is the program Header.The word “Program” indicates the beginning of the program whose name is StraightLine. The (input, output) statements shows that the program expects some input from the Keyboard and display the output on the Screen. VAR is short form for Variable. A variable is a location for data in the computer memory. This statement tells the computer that variables are about to be declared. When a variable is declared, the computer sets aside some memory space to store a value in the variable. y, m, x, c: INTEGER; Four variables of type Integer have been declared. This means that, the memory spaces that will be set aside can only hold values that are whole numbers. BEGIN The Begin statement marks the start of the program body. Statements in this section are executed by the computer. E.g., execution starts by asking the user to input the value of m. Writeln (‘Input the value of M’); The Writeln statement displays whatever is between the inverted commas in the brackets. The statements will be sent to the screen exactly the way they appear in the brackets. This is because; the inverted commas are meant to make the output readable on the screen. To display the value held in a variable on the screen, remove the inverted commas and write the name of the variable in the brackets, e.g., Writeln (y) will display the value held in the variable y. Readln (M); The Read or Readln statement reads a value and stores it in a variable. When the program is running, a Read/Readln statement in the code will displays blinking cursor that indicates to the user where to type the input. Y: = (m * x) +c; Calculates the value of y. in Pascal, the symbol ‘: =’ is called the Assignment statement. The values on the right are calculated then the answer stored in the variable y which is on the left of the assignment symbol. Writeln (‘The value of y is:’, Y); The Writeln displays the value held in the variable y on the screen. Note. Y is not within the inverted commas. END. The ‘END.’ statement shows the end of a program. Example 2:Program AreaCircle (input, output); CONST
Pi = 3.142; VAR
Radius, Area: REAL; BEGIN
Writeln (‘Enter the radius’);
Readln (Radius); Area: = Pi * Radius * Radius;
Writeln (‘The Area is’, Area);
Explanation of Pascal source codeProgram AreaCircle (input, output); The Header of the program.The statements in ( ) shows that the user inputs data via Keyboard and the program display information on the Screen. CONST Pi = 3.142; A constant has been declared with a name Pi and value 3.142. VAR Radius, Area: REAL; Variables with fractional parts have been declared. BEGIN Marks the beginning of the program body. Writeln (‘Enter the radius’); Displays on the screen the string between the inverted commas. Readln (Radius); Displays a blinking cursor that tells the user that an input is needed before the program can continue. Area: = Pi * Radius * Radius; Calculates the Area. An assignment statement (: =) has been used. Writeln (‘The Area is’, Area); Displays the value stored in the variable Area. END. Marks the end of the program. Revision Questions.
Program Testing and DebuggingAfter designing & coding, the program has to be tested to verify that it is correct, and any errors detected removed (debugged). TESTING:Testing is the process of running computer software to detect/find any errors (or bugs) in the program that might have gone unnoticed. During program testing, the following details should be checked;
Types of program errorsThere are 5 main types of errors that can be encountered when testing a program. These are:
Syntax errorsEvery programming language has a well-defined set of rules concerning formal spellings, punctuations, naming of variables, etc. The instructions are accepted only in a specified form & and must be obeyed by the programmer.Syntax errors are therefore, programming errors/mistakes that occur if the grammatical rules of a particular language are not used correctly. Examples:
Syntax errors are committed by the programmer when developing, or transcribing the program, and can be detected by the language translators, such as the Compiler as it attempts to translate a program. Such errors must be corrected by the programmer before the program runs. Logical (arithmetic) errors.These are errors in the program logic.Logical errors relate to the logic of processing followed in the program to get the desired results. E.g., they may occur as a result of misuse of logical operators. Logical errors cannot be detected by the translator. The programmer will detect them when the program results are produced. The program will run, but give the wrong output or stop during execution. Run-time (Execution) errors.These errors occur during program execution.Run-time (execution) errors occur when the programmer introduces new features in the program, which are not part of the translator’s standards. For example; they may occur if:
To detect and eliminate Execution errors, a test run should be performed on the program after it has been translated. Semantic errors.These are meaning errors. They occur when the programmer develops statements, which are not projecting towards the desired goal. Such statements will create deviations from the desired objectives.Semantic errors are not detected by the computer. The programmer detects them when the program results are produced. Example;
a). IF GP>=1500 OR 2200 THEN TAX: = GP - (GP * 13%) b). IF GP>=1500 AND GP<= 2200 THEN TAX: = GP - (GP * 13%) In the 1st statement, if the selection is between 1500 & 2200, the computer will pick only 1500 & 2200, and the other values will not be touched. In the 2nd statement, the computer will be able to pick all the values between 1500 & 2200 because of the ‘AND’ operator. Lexicon errors.These are the errors, which occur as a result of misusing Reserved words (words reserved for a particular language).Revision Questions.
DEBUGGING:The term Bug is used to refer to an error in a computer program.Most programming errors often remain undetected until an attempt is made to translate a program. The most common errors include:-
Debugging is therefore, the process of detecting, locating & correcting (removing, eliminating) all errors (mistakes or bugs) that may exist in a computer program. TYPES OF TESTING (Methods of error detection)For the program to be assumed as correct, several testing needs to be conducted by the programmer to ascertain/establish their validity. There are several methods of testing a program for errors. These include:
Dry Running (Desk checking):Dry running is a method of checking a program for errors by making the corrections on a paper before entering it in the program editor.It involves going through the program while still on paper verifying & validating its possible results. If the final results agree with the original test data used, the programmer can then type the program into the computer and translate it.
Translator system checking:This is a type of testing, which involves the computer & the translator programs.After entering the program, it is checked using a translator to detect any syntax errors. The translator can be a Compiler or an Interpreter, which goes through the set of instructions & produces a list of errors, or a program/statement listing which is free from errors. Functional testing (White-box testing):This type of testing is based upon examining the internal structure of a program & selecting test data, which give rise to the alternative cases of control flow.Use of Test data.The accuracy of a program can be tested by inputting a set of values referred to as Test data. The test data is designed to produce predictable output.There are 2 types of test data;
Notes.
Use of debugging utilities.After the program has been entered in the program editor, debugging utilities which are built in the computer can be run during translation to detect any syntax errors in the program.The errors are corrected and the debugging process is repeated again to find out more errors, before the program is executed. Diagnostic procedures.For complex programs, diagnostic procedures, such as Trace routines, may be used to find logical errors.A Trace prints out the results at each processing step to enable errors to be detected quickly. System Test with actual data.This is whereby the new program is run in parallel with the existing system for a short time so that results can be compared and adjustments made. In such cases, the system test is made using actual data.Review Questions.
Implementation and Maintenance.IMPLEMENTATIONImplementation refers to the actual delivery, installation and putting of the new program into use.The program is put into use after it is fully tested, well documented, and after training the staff who will be involved in the running of the new program. Structured Walk Through:It is an organized style of evaluating/reviewing a program by a team of other programmers, which then reports to the programming team. REVIEW AND MAINTENANCE.Once the program becomes operational, it should be maintained throughout its life, i.e., new routines should be added, obsolete routines removed, & the existing routines adjusted so that the program may adapt to enhanced functional environments. The main objective of maintenance is to keep the system functioning at an acceptable level. Program maintenance mainly involves: -
Program documentation.After writing, testing, and debugging a program, it must be documented. In other words, the programmer should describe all what he was doing during the program development stages.Program documentation is the writing of supportive materials explaining how the program can be used by users, installed by operators, or modified by other programmers. Note. All the program development activities (i.e., from the initial stage up to the complete program) should be documented/recorded in order to assist in the development of the program, future modification of the program, general maintenance, machine & software conversion at a later date, and program changeover. Documentation can either be; Internal or External. Internal documentation is the writing of non-executable lines (comments) in the source program that help other programmers to understand the code statements. External documentation refers to reference materials such as user manuals printed as booklets. Types of program documentation.There are 3 target groups for any type of documentation:
Contents in a program document.Documentation includes:
Review Questions.
Linkers & Loaders
Computer programs are usually developed in Modules or Subroutines (i.e., program segments meant to carry out the specific relevant tasks). During program translation, these modules are translated separately into their object (machine) code equivalents.
The Linker is a utility software that accepts the separately translated program modules as its input, and logically combines them into one logical module, known as the Load Module that has got all the required bits and pieces for the translated program to be obeyed by the computer hardware. The Loader is a utility program that transfers the load module (i.e. the linker output) into the computer memory, ready for it to be executed by the computer hardware.
Syntax
Each programming language has a special sequence or order of writing characters.
The term Syntax refers to the grammatical rules, which govern how words, symbols, expressions and statements may be formed & combined. Semantics
These are rules, which govern the meaning of syntax. They dictate what happens (takes place) when a program is run or executed.
Review Questions.
DEFINITION AND DEVELOPMENT OF ALGORITHM E.G. PSEUDO-CODE, FLOW CHART
Definition and development of Algorithm e.g.
To design a good pseudocode, proceed as follows
FLOWCHART
Flowcharts are used by programmers to:
​Description of terms: assembler, compiler, interpreter, source program, object program18/11/2021
LANGUAGE TRANSLATORS
A computer uses & stores information in binary form, and therefore, it cannot understand programs written in either high-level or low-level languages. This means that, any program code written in Assembly language or high-level language must be translated into Machine language, before the computer can recognize & run these programs.
A Translator is special system software used to convert the Source codes (program statements written in any of the computer programming languages) to their Object codes (computer language equivalents). The Translators reside in the main memory of the computer, and use the program code of the high-level or Assembly language as input data, changes the codes, and gives the output program in machine-readable code. In addition, translators check for & identify some types of errors (e.g., Syntax/grammatical errors) that may be present in the program being translated. They will produce error messages if there is a mistake in the code. Each language needs its own translator. Generally, there are 3 types of language translators:
Note. Interpreters & Compilers translate source programs written in high-level languages to their machine language equivalents.
Assembler
An assembler translates programs written in Assembly language into machine language that the computer can understand and execute.
Functions of an Assembler.
Note. The Assembler cannot detect Logic errors. The programmer knows of these errors only when the program is run & the results produced are incorrect (not what the programmer expected). The programmer must therefore, go through the program & try to discover why an incorrect result was being produced. Compiler
A compiler translates the entire/whole source program into object code at once, and then executes it in machine language code. These machine code instructions can then be run on the computer to perform the particular task as specified in the high-level program.
The process of translating a program written in a high-level source language into machine language using a compiler is called Compilation. For a given machine, each language requires its own Compiler. E.g., for a computer to be able translate a program written in FORTRAN into machine language; the program must pass through the FORTRAN compiler (which must ‘know’ FORTRAN as well as the Machine language of the computer). The object code file can be made into a fully executable program by carrying out a Linking process, which joins the object code to all the other files that are needed for the execution of the program. After the linking process, an executable file with an .EXE extension is generated. This file is stored on a storage media. Points to note.
Functions of a compiler.
A Compiler performs the following tasks during the compilation process:
Differences between Compilers and InterpretersInterpreter
An interpreter translates a source program word by word or line by line. This allows the CPU to execute one line at a time.
The Interpreter takes one line of the source program, translates it into a machine instruction, and then it is immediately executed by the CPU. It then takes the next instruction, translates it into a machine instruction, and then the CPU executes it, and so on. The translated line is not stored in the computer memory. Therefore, every time the program is needed for execution, it has to be translated. Source Program
Source program (source code)
The term Source program refers to program statements that the programmer enters in the program editor window, and which have not yet been translated into machine-readable form. Source code is the code understood by the programmer, and is usually written in high-level language or Assembly language. Object Code
Object code (object program).
The term Object code refers to the program code that is in machine-readable (binary) form. This is the code/language the computer can understand, and is produced by a Compiler or Assembler after translating the Source program into a form that can be readily loaded into the computer.
Advantages and disadvantages of low and high level languages.
Machine language
Assembly language
High-level languages
Levels of programming languages
LEVELS OF PROGRAMMING LANGUAGES
There are many programming languages. The languages are classified into 2 major categories:
LOW-LEVEL LANGUAGES
These are the basic programming languages, which can easily be understood by the computer directly, or which require little effort to be translated into computer understandable form.
They include:
Features of low-level languages
Machine languages (1st Generation languages)
Machine language is written using machine codes (binary digits) that consist of 0’s & 1’s.
The computer can readily understand Machine code (language) instructions without any translation. A programmer is required to write his program in strings of 0’s & 1’s, calculate & allocate the core memory locations for his data and/or instructions. Different CPU’s have different machine codes, e.g., codes written for the Intel Pentium processors may differ from those written for Motorola or Cyrix processors. Therefore, before interpreting the meaning of a particular code, a programmer must know for which CPU the program was written. A machine code instruction is made up of 2 main parts;
Note. The computer can only execute instructions which are written in machine language. This is because; it is the only language which the computer can understand. Therefore, any program written in any other programming language must first be translated into machine language (binary digits) before the computer can understand. Assembly language (2nd Generation Languages).
Assembly languages were developed in order to speed up programming (i.e., to overcome the difficulties of understanding and using machine languages).
The vocabulary of Assembly languages is close to that of machine language, and their instructions are symbolic representations of the machine language instructions.
To write program statements in Assembly language, the programmer uses a set of symbolic operation codes called Mnemonic codes. The code could be a 2 or 3 shortened letter word that will cause the computer to perform specific operation. E.g., MOV – move, ADD - addition, SUB – subtraction, RD - read. Example; RD PAT, 15 (read the value 15 stored in the processor register named PAT) SUB PAT, 10 (subtract 10 from the value in register PAT) A program written in an Assembly language cannot be executed/obeyed by the computer hardware directly. To enable the CPU understand Assembly language instructions, an Assembler (which is stored in a ROM) is used to convert them into Machine language. The Assembler accepts the source codes written in an Assembly language as its input, and translates them into their corresponding computer language (machine code/ object code) equivalent. Comments are incorporated into the program statements to make them easier to be understood by the human programmers. Assembly languages are machine-dependent. Therefore, a program written in the Assembly language for a particular computer cannot run on another make of computer. Advantages of Low-level languages
Disadvantages of Low-level languages
Very few computer programs are actually written in machine or Assembly language because of the following reasons;
HIGH-LEVEL PROGRAMMING LANGUAGES
High-level languages were developed to solve (overcome) the problems encountered in low-level programming languages.
The grammar of High-level languages is very close to the vocabulary of the natural languages used by human beings. Hence; they can be read and understood easily even by people who are not experts in programming. Most high-level languages are general-purpose & problem-oriented. They allow the programmer to concentrate on the functional details of a program rather than the details of the hardware on which the program will run. High-level language programs are machine-independent, (i.e., they do not depend on a particular machine, and are able to run in any family of computers provided the relevant translator software is installed). Programs written in a high-level language cannot be obeyed by the computer hardware directly. Therefore, the source codes must be translated into their corresponding machine language equivalent. The translation process is carried out by a high-level language software translator such as a Compiler or an Interpreter. Features of high-level programming languages.
Purpose of High-level languages.
Advantages of High-level languages.
Disadvantages of using High-level languages
TYPES OF HIGH-LEVEL LANGUAGES
High-level languages are classified into five different groups:
The various types of high-level languages differ in:
STRUCTURED LANGUAGES
A structured (procedural) language allows a large program to be broken into smaller sub-programs called modules, each performing a particular (single) task. This technique of program design is referred to as structured programming.
Structured programming also makes use of a few simple control structures in problem solving. The 3 basic control structures are:
Advantages of structured programming.
Examples of Third generation programming languages include:
FOURTH GENERATION LANGUAGES (4GL’S).
4GLs make programming even easier than the 3GLs because; they present the programmer with more programming tools, such as command buttons, forms, textboxes etc. The programmer simply selects graphical objects called controls on the screen, and then uses them to create designs on a form by dragging a mouse pointer.
The languages also use application generators (which in the background) to generate the necessary program codes; hence, the programmer is freed from the tedious work of writing the code. 4GLs are used to enquire & access the data stored in database systems; hence, they are described as the Query languages. Purpose of fourth generation languages.
The 4GL’s were designed to meet the following objectives: -
Examples of 4GLs are:
Advantages of fourth generation languages.
FIFTH GENERATION LANGUAGES (5GL’S).The 5GL’s are designed to make a computer solve a problem by portraying human-like intelligence. The languages are able to make a computer solve a problem for the programmer; hence, he/she does not spend a lot of time in coming up with the solution. The programmer only thinks about what problem needs to be solved and what conditions need to be met without worrying about how to implement an algorithm to solve the problem. 5GLs are mostly used in artificial intelligence. Examples of 5GLs are:
OBJECT-ORIENTED PROGRAMMING LANGUAGES (OOPs)
Examples of Object-oriented programming languages are: -
JAVA
WEB SCRIPTING LANGUAGES.
Comparison of Programming languages.
Factors to consider when choosing a Programming language.
The following factors should be considered when choosing a Programming language to use in solving a problem:
Review Questions
Definition of ProgrammingComputer Program:
A computer program is a set of coded instructions given to the computer, and represents a logical solution to a problem. It directs a computer in performing various operations/tasks on the data supplied to it.
Computer programs may be written by the hardware manufacturers, Software houses, or a programmer to solve user problems on the computer.
Programming:
Programming is the process of designing a set of instructions (computer programs) which can be used to perform a particular task or solve a specific problem.
It involves use of special characters, signs and symbols found in a particular programming language to create computer instructions. The programming process is quite extensive. It includes analyzing of an application, designing of a solution, coding for the processor, testing to produce an operating program, and development of other procedures to make the system function. The program created must specify in detail the logical steps to be taken & the method of processing the data input into the computer in order to carry out the specified task.
A computer program performs the following:
Programming Languages:
A programming language is a set of symbols (a language) which a computer programmer uses to solve a given problem using a computer.
The computer must be able to translate these instructions into machine-readable form when arranged in a particular sequence or order.
(a)When invoicing customers, the invoice clerk has to work out the discounts allowable on each order. Any order over 20,000/= attracts a “bulk” discount of 7%. A customer within the trade is allowed 10%. There is also a special discount of 2% allowed for any customer who has been ordering regularly for over 2 years. Using a flowchart show clerical procedure for working out discount entitlement.(b) Name the control structures you have used in the flow chart (2mks)
Describe three methods you would use in error detection during program testing
error detection methods
Write an algorithm to computer the area of a circle. (2mks)Pseudocode
Start
input pie = 3.14 area = pie*r*r print area end
Start
input area = 3.14 *r*r print r, area stop
FlowchartState two qualities of a good pseudocode.
(b) With the aid of flowchart diagrams, describe each of the following programme control structures:
|
Categories
All
Archives
December 2024
|