Vous êtes sur la page 1sur 38

CHAPTER ONE 1.0 INTRODUCTION Modern society depends largely on computers, phones and other electronic devices.

These devices require programs to drive them. This is why there is increasing demand for professionals who know how to develop programs. Learning to program can be challenging but it is exciting and rewarding. In this chapter you are to introduced to the concepts of program and programming languages and properties of a good program 1.1 LEARNING OBJECTIVES At the end of this chapter, you should be able to: 1. 2. 3. 4. 5. 6. 7. Define and explain the term program Define programming Define programming language Mention some programming languages Identify and explain the features of a good program Give a brief history of programs, programming and programming languages State the steps for developing programs

1.2 DEFINING A PROGRAM A program is a sequence of instructions, commands or statements given to a computer or any programmable device that directs such a device in the execution of intended tasks. It can also be defined a set of instructions written in a logical sequence, that can be interpreted and executed by a computer (or any device), enabling the device to perform a required function. A set of programs is called software. Thus the terms program and software meaning more or less the same are used interchangeably. A program has an executable form that the computer can use directly to execute instructions. This program in machine-executable form is called the object code. The same program in its human-readable form which can be read, understood and modified by a programmer is called source code. Computer source code is often written by professional computer programmers. Source codes are written using programming languages. Examples of programming languages are Visual basic, Java, C, C++, Python, Perl etc. There are hundreds of programming languages.
Introduction to Computer Programming by OLADELE CAMPBELL

Page 1

How does a program look like? Look at the example program in fig. 1.1 below. Now as a newbie to programming you may not understand what the statements or words in the program mean. Never worry you will get to know that by and by. This just to show you what a program look like. The program is written in C language. When it is translated and executed by the computer it makes the computer to display the message : Hello World. #Include <studio.h> Int main (void) { Puts(Hello World); Return 0; } Fig. 1.1: Source code of a program written in the C programming language 1.3 PROGRAMMING Computer programming (often shortened to programming or coding) is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a set of instructions that computers [or devices] use to perform specific operations or to exhibit desired behaviors. (Wikipedia). Simply put programming is process of developing software for devices wherever automation of tasks is needed. Programming languages are the codes programmers use in writing programs. Writing computer programs is like writing instructions for the computer to perform anything the author of the program want. The computer is a dumb but obedient machine that can be programmed to perform whatever we can write the steps for it to do so. The people that perform programming are called programmers. Their job include: i. Coding ii. Compilation (translation) iii. Debugging iv. Documentation v. Software testing vi. Integration vii. Maintenance viii. 1.4 FEATURES OF A GOOD PROGRAM As you embark on the journey of learning to develop computer programs, it is important that you know and cultivate good programming skills, techniques, style or habit that leads to production of good programs. It is not enough just to develop
Introduction to Computer Programming by OLADELE CAMPBELL

Page 2

programs you need to develop good programs that sell! Such programs have these properties: Reliability: This implies correctness of the result from the program. How often the results of the programs result is correct depends on the correctness of the algorithm, absence of programming mistakes and logic errors ( e.g. an attempt by the program to do division by zero). Robustness: This means how well the program anticipates and withstands problems not due to programmer error during its execution on the computer. Such errors may be due inappropriate data input by the computer user, lack of needed resources during execution (e.g. memory, operating system services and network connection). A good program can withstand wrong inputs from computer users without crashing. Usability: This refers to the ease with which users can use a program for its intended purpose, or even in some cases unanticipated purposes. This will require a wide range of textual, graphical and sometimes hardware components that improve the clarity, intuitiveness, cohesiveness and completeness of the programs user interface. Portability: This is the measure of the range of computer hardware and operating systems platforms on which the source code of the program can be translated and run. A good program can run on different platforms with little or no need to modify the original program Maintainability: this refers to the ease with the program can be modified when the need arises in the future. Such modification may be necessitated by the need to fix bugs or security holes in the program, adapt the program to new environment, customization etc. A good program can be easily modified in the future even by a different programmer other than its original author. Efficiency/Performance: This measures the amount of system resources the program uses during execution. Such resources include memory (or storage) space, processor time, bandwidth etc. An efficient program uses fewer resources. Readability: This refers to the ease with which a programmer can read and comprehend from the source code a programs purpose and logic. This quality affects usability, portability and maintainability qualities of a program. 1.5 BRIEF HISTORY OF PROGRAM, PROGRAMMING & PROGRAMMING LANGUAGES Charles Babbage, a British mathematician, also regarded as the father of computer, adopted the use of punched cards around 1830 to control his Analytical Engine. The first computer program was written for the Analytical Engine by another mathematician woman called Lady Ada Lovelace to calculate a sequence of Bernoulli Numbers. The
Introduction to Computer Programming by OLADELE CAMPBELL

Page 3

synthesis of numerical calculation, predetermined operation and output, along with a way to organize and input instructions in a manner relatively easy for humans to conceive and produce, led to the modern development of computer programming. Development of computer programming accelerated through the Industrial Revolution. In the late 1880s, Herman Hollerith invented the recording of data on a medium that could then be read by a machine. Data and instructions could be stored on external punched cards, which were kept in order and arranged in program decks. The invention of the von Neumann architecture allowed computer programs to be stored in computer memory. Early programs had to be painstakingly crafted using the instructions (elementary operations) of the particular machine, often in binary notation. Every model of computer would likely use different instructions (machine language) to do the same task. Later, assembly languages were developed that let the programmer specify each instruction in a text format, entering abbreviations for each operation code instead of a number and specifying addresses in symbolic form (e.g., ADD X, TOTAL). Entering a program in assembly language is usually more convenient, faster, and less prone to human error than using machine language, but because an assembly language is little more than a different notation for a machine language, any two machines with different instruction sets also have different assembly languages. In 1954,FORTRAN was invented; it was the first high level programming language to have a functional implementation, as opposed to just a design on paper. (A high-level language is, in very general terms, any programming language that allows the programmer to write programs in terms that are more abstract than assembly language instructions, i.e. at a level of abstraction "higher" than that of an assembly language.) It allowed programmers to specify calculations by entering a formula directly (e.g. Y = X*2 + 5*X + 9). The program text, or source, is converted into machine instructions using a special program called a compiler, which translates the FORTRAN program into machine language. In fact, the name FORTRAN stands for "Formula Translation". Many other languages were developed, including some for commercial programming, such as COBOL. Programs were mostly still entered using punched cards or paper tape. By the late 1960s, data storage devices and computer terminals became inexpensive enough that programs could be created by typing directly into the computers. Text editors were developed that allowed changes and corrections to be made much more easily than with punched cards. (Usually, an error in punching a card meant that the card had to be discarded and a new one punched to replace it.) As time has progressed, computers have made giant leaps in the area of processing power. This has brought about newer programming languages that are more abstracted from the underlying hardware. Although these high-level languages usually incur greater overhead, the increase in speed of modern computers has made the use of these languages much more practical than in the past. These increasingly abstracted languages typically are easier to learn and allow the programmer to
Introduction to Computer Programming by OLADELE CAMPBELL

Page 4

develop applications much more efficiently and with less source code. However, highlevel languages are still impractical for a few programs, such as those where low-level hardware control is necessary or where maximum processing speed is vital. 1.6 STEPS FOR DEVELOPING PROGRAMS Below is a list of steps for program development that result into real useful software for users.

System Analysis Specification and Design Program Debug Alpha Test Beta Test Deliver the Software

System Analysis involves creating a formal model of the problem to be solved. The model is created by:

talking to the users to assess their needs understanding the complete problem to be solved making a formal representation of the system being designed

Specification and Design: At this stage a detailed design is written which defines the following: Data Structures: defining the format and type of data the program will use. User Interface: the design of the screen the user will see and use to enter data or display data. Inputs: defining the kind of data to enter into the program. Outputs: the possible data displayed from the system. Algorithms: the methods of calculating outputs depending on the inputs. Program or Code Programmers use the specification to write the code necessary to fulfil all the requirements of the program. The code is a text based file which when compiled creates the program. A good programmer will consider: Future Maintenance: any code that may be modified in future and should be allowed for when writing the code. Code Readability: this enables programmers to identify areas of code quickly and easily. Documentation: a document showing how the program works. Debug Virtually all programs have defects in them called 'bugs' and these need to be
Introduction to Computer Programming by OLADELE CAMPBELL

Page 5

eliminated. Bugs can arise from errors in the logic of the program specification or errors in the programming code created by a programmer. Special programming tools assist the programmer in finding and correcting bugs. Some bugs are difficult to locate and fixing them is like solving a complex puzzle. Alpha Test This is a small scale trial of the program. The application is given to a few expert users to assess whether it is going to meet their needs and that the user interface is suitable. Bugs and missing features due to the application being unfinished will be found. Any errors in the code and specification will be corrected at this stage. Beta Test This is a more wide-ranging trial where the application is given to a selection of users with different levels of experience. This is where we hope that the remaining bugs are found, but some may remain undetected or unfixed. Deliver the Software The completed software is packaged with full documentation and delivered to the end users. When they use the software, bugs that were not found during testing may appear. As these new bugs are reported an updated version of the software with the reported bugs corrected is shipped as a replacement.

REVIEW QUESTIONS 1. Explain briefly the following terms in your own words to a non computer science student: i. Program ii. Software iii. Programming language iv. Object code v. Source code 2(a) List five (5) properties of a good program

ANSWERS TO REVIEW QUESTIONS


Introduction to Computer Programming by OLADELE CAMPBELL

Page 6

1i. Programs are essential drivers in computers, phones, home appliances, robots, automobiles, planes etc. So what the driver is to a car is what the program is to a computer or any automated device that has program embedded into it. A program is made up of instructions that tell the computer or any device what to do, how to do it and when to do it. ii. A Software is a set of programs. So the terms program and software can be used interchangeably. Software are needed in any device that we want to use to perform automatically some tasks. iii. Programming language is the language or code we use in converting algorithms into computer programs. They are made up of codes or statements that specify to the computer what operations it is to perform on data. iv. Object code is the equivalent program which is the result of translation of the original program written by a programmer. It is an executable program that is generated by a translator called a compiler. v. A Source code is the program written by a programmer using a particular programming language. Such program is not yet in a form that can be executed by the computer. It has to be converted using a translator program into object code before the instructions it contains can be executed. 2(a) Properties of a good program i. ii. iii. iv. v. Reliability Robustness Readability Maintainability Efficiency

CHAPTER TWO THE CONCEPT OF ALGORITHM Good programs are not just written. They are created. They are the products following particular plan or blueprints. So before you write a program you need to develop a plan or a blue print for the program called algorithms. Hence, essentially what the computers or automated devices need to solve any programming problems is to design algorithms. In this chapter you will be introduced to this important central
Introduction to Computer Programming by OLADELE CAMPBELL

Page 7

subject of algorithms. You will also be introduced to some tools for representing algorithms such as structured English, pseudocode, flowcharts. 2.1 LEARNING OBJECTIVES At the end of this chapter, you should be able to: 1. 2. 3. 4. 5. 6. Define algorithm Explain with illustrations the term algorithm State properties of a good algorithm Differentiate between algorithm and computer program State Methods for representing algorithms. Develop algorithms using design tools such as structure English, decision tree, decision table, logic flowcharts 7. State the strengths and weaknesses of the above design tools 2.1 WHAT IS AN ALGORITHM? Several definitions sometimes depending on the context exist for the word algorithm and so there is generally agreed definition. But we can define algorithm as a finite ordered list of steps for solving a problem or performing a task. The term algorithm has its origin in mathematics and it means a rule for solving a problem. 2.2 ALGORITHMS IN EVERYDAY LIFE To understand concept of algorithms let us consider some real life illustrations of this concept. Some algorithms are learned e.g. arithmetic. This means you have learnt and used some algorithms when solving arithmetic problems when you were in primary or secondary school. Some we figure out ourselveslooking up a phone number Others require written instructionsrecipe, assembly instructions, driving direction, a procedure for changing flat tyre. Others are shown graphically, for example, a building plan is an algorithms that a building contractor will follow to build a structure. Let us also consider an example from day to day activities of students: preparing for class. Below is an algorithm that a student follows to prepare for lectures daily: 1. Wake up 2. Pray 3. Wash-up
Introduction to Computer Programming by OLADELE CAMPBELL

Page 8

4. 5. 6. 7. 8. 9.

1. 2. 3. 4. 5. 6. 7. 8. 9.

Dress-up Take breakfast Take your books Move out of your room Enter the class Sit down for lecture In order to stress the importance of the word ordered list in the definition of algorithms given in section 2.1, let us rewrite the above algorithm for preparing for class as given below: Wake up Pray Dress-up Wash-up Take breakfast Take your books Move out of your room Enter the class Sit down for lecture How do you think the student that follow this second algorithm will appear when he or she turns up for class? You will notice that we still have the same number of steps in the second algorithm. The only change is in the order of the steps; step 3 in the first algorithm has now become step 4 and vice versa.

ASSIGNMENTS: 1. Develop an algorithm (i.e. a cooking recipe) for preparing a dish of fried rice for five guests. 2. Develop an algorithm for sewing a uniform for a pupil of Niger State polytechnic Staff (either a boy or a girl).

2.3 HISTORY OF ALGORITHMS The origin of the term comes from the ancients. The concept became more precise with the use of variables in mathematics. Algorithm in the sense of what is now used by computers appeared as soon as first mechanical engines were invented. The word algorithm comes from the name of the 9th century Persian mathematician Abu Abdullah Muhammad ibn Musa Al-Khwarizmi. The word algorism originally referred only to the rules of performing arithmetic using Hindu-Arabic numerals but evolved via
Introduction to Computer Programming by OLADELE CAMPBELL

Page 9

European Latin translation of Al-Khwarizmi's name into algorithm by the 18th century. The use of the word evolved to include all definite procedures for solving problems or performing tasks. 2.4 ALGORITHMS BY THE ANCIENTS - Euclid has created an algorithm that has been given its The algorithm serves to calculate the greatest common divisor (gcd), here is it: - divide the number a by b, the remainder is r - replace a by b - replace b by r - continue until a can't be more divided. In this case, a is the gcd. - The algorithm of Archimedes gives an approximation of the Pi number. - Eratosthenes has defined an algorithm for retrieving prime numbers. 2.5 PROPERTIES OF A GOOD ALGORITHM Five Essential Properties of Algorithms are: 1. Input is specified Data (or input) to be transformed during the computation to produce the output is stated clearly. An algorithm must specify type, amount, and form of data 2. Output specified Data resulting from the computation, intended result, is also clearly specified. However, for some problems it is possible to have no output 3. Definiteness: An algorithm must specify the sequence of events or steps to be performed using clear word. It provides details of each step, including how to handle errors. It also means each step in algorithm is unambiguous. That means that the action specified by the step cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any confusion 4. Effectiveness: The operations or steps in an algorithm are can be performed by the computing agent. Each step is doable. 5. Finiteness: A good must eventually stop. name.

2.6 DIFFERENCES BETWEEN A PROGRAM AND AN ALGORITHM


Introduction to Computer Programming by OLADELE CAMPBELL

Page 10

The difference between an algorithm and a program is like the difference between an unborn baby and a man. An algorithm is a program in the making. While an algorithm is a finite list of ordered steps for solving a problem or performing a task, a program is an algorithm that has been converted using a programming language into the form that the computer can accept, interpret and execute. So an algorithm cannot be accepted and executed by the computer or any device while a program can. A program is an algorithm that has been customized to solve a specific task under a specific set of circumstances using a specific language. Algorithm is a general method; program is a specific method 2.7 AN ALGORITHM: ALPHABETIZE CDS Imagine CDs in a slotted rack, not organized .You want to alphabetize by name of group, performing musician, or composer. How do you solve this problem? Input: An unordered sequence of CDs filling a slotted rack Output: The same CDs in the rack in alphabetical order Instructions: 1. Use the term Artist_Of to refer to the name or the group or musician or composer on a CD 2. Decide which end is the beginning of the sequence and call the slot at that end the Alpha slot 3. Call the slot next to Alpha the Beta slot 4. If the Artist_Of the CD in Alpha comes later in alphabet than the Artist_Of in Beta, swap the CDs; otherwise continue on 5. If there is a slot following Beta, begin calling it Beta and go to Instruction 4; otherwise continue on 6. If there are two or more slots following Alpha, begin calling the slot following Alpha, Alpha and begin calling the slot following it Beta, and go to Instruction 4; otherwise stop

2.7.1EXPLANATIONS OF EACH STEPS Instruction 1 Use the term Artist_Of to refer to the name of the group or musician or composer on a CD
Introduction to Computer Programming by OLADELE CAMPBELL

Page 11

This gives a name to the operation of locating the name used for alphabetizing Instruction 2 Decide which end of the rack is the beginning of the alphabetic sequence and call the slot at that end the Alpha slot. This gives the process a starting point. It defines the word Alpha. At the start, Alpha refers to the first slot in the sequence; as the algorithm progresses it refers to successive slots Instruction 3 Call the slot next to the Alpha slot the Beta slot Gives Beta its initial meaning. Alpha and Beta have no inherent meaning; they are chosen by the programmer to name slots in the rack Instruction 4 If the Artist_Of the CD in the Alpha slot comes later in the alphabet than the Artist_Of the CD in the Beta slot, swap the CD's; otherwise continue on This is the workhorse instruction of the algorithm. This is where the computing agent will work most in order to sort the CDs. It compares the names of the artists of the CDs in Alpha and Beta and, if necessary, swaps them so that they are in the correct order Instruction 5 If there is a slot following the Beta slot, begin calling it the Beta slot and go to Instruction 4; otherwise, continue This re-defines Beta slot so that it refers to the next slot in the sequence, if any. Then Instruction 4 can be executed again, comparing a different pair of CDs Instruction 6 If there are two or more slots following the Alpha slot, begin calling the slot following the Alpha slot Alpha and the slot following it Beta, and go to Instruction 4; otherwise stop By the time we get to this instruction, the alphabetically earliest CD is in the Alpha slot. We advance Alpha to the next slot and sweep through the CD rack again, locating

Introduction to Computer Programming by OLADELE CAMPBELL

Page 12

the alphabetically earliest CD. When there are no longer enough slots to call one Alpha and one Beta, the entire rack has been alphabetized and the algorithm stops Analyzing Alphabetize CDs Algorithm Illustrates the five basic properties of algorithms Inputs and Outputs were listed Each instruction was defined precisely (definiteness) Operations are effective because they are simple and mechanically doable Alphabetizing is mechanical, so our algorithm is effective Finiteness is satisfied because there are only a finite number of slots that can be paired, so instructions 4, 5, and 6 cannot be repeated indefinitely 2.8 METHODS OF REPRESENTING ALGORITHMS Algorithms can be expressed in many kinds of notations: - Natural language: Natural language (particularly structured) English) expressions of algorithms tend to be verbose and ambiguous, and are rarely used for complex or technical algorithms. - Pseudocode and flowcharts are structured ways to express algorithms that avoid the ambiguities, while remaining independent of a particular implementation language. - Programming languages are primarily intended for expressing algorithms in a form that can be executed by a computer, but are often used as a way to define or document algorithms. 2.8.1 PSEUDOCODE Definitions pseudo adj. 1: being apparently rather than actually as stated. (Webster's New Collegiate Dictionary) Pseudocode (derived from pseudo and code) is a description of a computer programming algorithm that uses the structural conventions of programming languages, but omits detailed subroutines or language-specific syntax. ( WikipediA )
Introduction to Computer Programming by OLADELE CAMPBELL

Page 13

Pseudo-Code is notation for expressing algorithm that resembles a programming language. It is simply a numbered list of instructions (written using English words, arithmetic symbols and programming language constructs). In this course we will enforce three standards for good pseudo code 1. Number each instruction. This is to enforce the notion of an ordered sequence of ... operations. Furthermore we introduce a dot notation (e.g. 3.1 come after 3 but before 4) to number subordinate operations for conditional and iterative operations 2. Each instruction should be unambiguous (that is the computing agent, in this case the reader, is capable of carrying out the instruction) and effectively computable (do-able). 3. Completeness. Nothing is left out. 2.8.1.1 PSEUDOCODE EXAMPLES Pseudo-code is best understood by looking at examples. Each example below demonstrates one of the control structures used in algorithms : sequential operations, conditional operations, and iterative operations. We also list all variables used at the end of the pseudo-code. Example1: Computing Sales Tax : Pseudo-code the task of computing the final price of an item after figuring in sales tax. Note the three types of instructions: input (get), process/calculate (=) and output (display) 1. 2. 3. 4 5. 6. get price of item get sales tax rate sales tax = price of time times sales tax rate final price = price of item plus sales tax display final price halt

Variables: price of item, sales tax rate, sales tax, final price Note that the operations are numbered and each operation is unambiguous and effectively computable. We also extract and list all variables used in our pseudo-code. This will be useful when translating pseudo-code into a programming language Example #2 - Computing Weekly Wages: Gross pay depends on the pay rate and the number of hours worked per week. However, if you work more than 40 hours, you get paid time-and-a-half for all hours worked over 40. Pseudo-code the task of computing gross pay given pay rate and hours worked.
1. 2. 3. get hours worked get pay rate if hours worked 40 then Page 14

Introduction to Computer Programming by OLADELE CAMPBELL

4. 40) 5. 6.

3.1 else 4.1

gross pay = pay rate times hours worked gross pay = pay rate times 40 plus 1.5 times pay rate times (hours worked minus

display gross pay halt

variables: hours worked, ray rate, gross pay This example introduces the conditional control structure. On the basis of the true/false question asked in line 3, we execute line 3.1 if the answer is True; otherwise if the answer is False we execute the lines subordinate to line 4 (i.e. line 4.1). In both cases we resume the pseudo-code at line 5. Example #3 - Computing a Quiz Average: Pseudo-code a routine to calculate your quiz average. 1. 2. 3. 4. get number of quizzes sum = 0 count = 0 while count < number of quizzes 4.1 get quiz grade 4.2 sum = sum + quiz grade 4.3 count = count + 1 average = sum / number of quizzes display average halt variables: number of quizzes, sum ,count, quiz grade, average This example introduces an iterative control statement. As long as the condition in line 4 is True, we execute the subordinate operations 4.1 - 4.3. When the condition becomes False, we resume the pseudo-code at line 5. This is an example of a top-test or while do iterative control structure. There is also a bottom-test or repeat until iterative control structure which executes a block of statements until the condition tested at the end of the block is False. Pseudo-code is one important step in the process of writing a program. 2.8.1.2 Pseudo-code Language Constructions: A Summary - Computation/Assignment set the value of "variable" to :"arithmetic expression" or "variable" equals "expression" or

5. 6. 7.

Introduction to Computer Programming by OLADELE CAMPBELL

Page 15

"variable" = "expression" - Input/Output get "variable", "variable", ... display "variable", "variable", ... - Conditional (dot notation used for numbering subordinate statements) 6. 7. if "condition" 6.1 (subordinate) statement 1 6.2 etc... else 7.1 (subordinate) statement 2 7.2 etc ...

-Iterative (dot notation used for numbering subordinate statements) 9. while "condition" 9.1 (subordinate) statement 1 9.2 etc ... 2.8.1.3 Common Action Keywords in Pseudocode Several keywords are often used to indicate common input, output, and processing operations. Input: READ, OBTAIN, GET. Output: PRINT, DISPLAY, SHOW Compute: COMPUTE, CALCULATE, DETERMINE Initialize: SET, INIT Add one: INCREMENT, BUMP

2.8.2 FLOWCHART TECHNIQUES Programmers use different kinds of tools or aids which help them in developing programs faster and better. Apart from pseudocode other Important aids available to a programmer are flowcharting and decision tables which help him in constructing programs very fast and very easily.

Introduction to Computer Programming by OLADELE CAMPBELL

Page 16

2.8.2.1 Flowcharts A flowchart is a graphical representation of the sequence of operations or steps in an algorithm, an information system or a program. Also known as a block or logic diagram, a flowchart represents the processing steps in visual form. Program flowcharts show the sequence of instructions in a single program or subroutine. Flowchart uses symbols to denote different types of instructions. The actual instructions are written within these boxes using clear and concise statements. These symbols are connected by solid lines having arrow marks called flow lines to indicate the flow of operation, that is, the exact sequence in which the instructions are to be executed. Since a flowchart shows the flow of operations in pictorial form, any error in the logic of the procedure can be detected easily. Once the flowchart is ready, the programmer can forget about the logic and can concentrate only on coding the operations indicated by symbol of the flowchart in terms of the statements of the programming language. This will normally ensure an error-free program. A flowchart is basically the plan to be followed when the program is written. It acts like a road map for a programmer and guides him in proceeding from the starting point to the final point while writing a computer program. For a beginner it is strongly recommended that a flowchart be drawn first in order to reduce the number of errors and omissions in the program. Moreover, it is a good practice to have a flowchart along with a computer program as it is very helpful during the testing of the program and also in incorporating any modifications in the program. 2.8.2.2 Flowchart Symbols

Only a few symbols are needed to indicate the necessary operations in a flowchart. These symbols have been standardized by the American National Standards Institute (ANSI). These symbols are shown in Figure 2.1 and their functions are discussed below.

SYMBOL

EXAMPLE
UT/ OUTPUT

TERMINAL I N P

Introduction to Computer Programming by OLADELE CAMPBELL

Page 17

BEGIN END

INPUT X,Y

START ACTIO N HERE.

TWO VALUES FROM AN EXTERNAL SOURCE AND ASSIGN THEM TO X & Y ON A TERMINAL/SCREEN WRITE THE VALUES CONTAINED IN X & Y ON A TERMINAL/SCREEN

S T O P

PRINT X,Y

A C T I O N

H E R E .

T A K E

Introduction to Computer Programming by OLADELE CAMPBELL

Page 18

Z PROCESSING

(X+Y)

ADD THE VALUE CONTAINED IN Y TO THE VALUE CONTAINED IN X AND PLACE THE RESULT IN Z AN ENTRY IN THE FLOW CHART IS MADE AT THE CONNECTING POINT MARKED 1 IF CONDITION IS SATISFIED THEN YES PATH IS TO BE FOLLOWED OTHERWISE NO ROUTE IS TO BE TAKEN.

1 ENTRY CONNECTOR

CONDITION ? NO

YES

DECISION DIAMOND THE ARROWS INDICATE THE ROUTES FOR SYSTEMATIC SOLUTION OF THE PROBLEM. A TRANSFER OF PROBLEM SOLUTION IS MADE AT THE 2 CONNECTOR POINT IN THE FLOW CHART

FLOW LINES 2 CONNECTOR (TRANSFER)

Fig. 2.1 Flowchart Symbols

Terminal The terminal symbol, as the name implies, is used to indicate the starting (BEGIN), stopping (END), and pause (HALT) in the program logic flow. It is the first symbol and the last symbol in the program logic. In addition, if the program logic calls for a pause in the program, that also is indicated with a terminal symbol. A pause is normally used in the program logic under some error conditions or in case the forms had to be changed in the computers line printer during the processing of that program. Input/Output The input/output symbol is used to denote any function of an input/output device in the program. If there is a program instruction to input data from a disk, tape, card reader, terminal, or any other type of input device, that step will be indicated in the flowchart with an input/output symbol. Similarly, all output instructions, whether it is output on a printer, magnetic tape, magnetic disk, terminal screen, or any output device, are indicated in the flowchart with an input/output symbol.
Introduction to Computer Programming by OLADELE CAMPBELL

Page 19

Processing A processing symbol is used in a flowchart to represent arithmetic and data movement instructions. Thus, all arithmetic processes such as adding, subtracting, multiplying and dividing are shown by a processing symbol. The logical process of moving data from one location of the main memory to another is also denoted by this symbol. When more than one arithmetic and data movement instructions are to be executed consecutively, they are normally placed in the same processing box and they are assumed to be executed in the order of their appearance. Flow lines Flow lines with arrowheads are used to indicate the flow of operation, that is, the exact sequence in which the instructions are to be executed. The normal flow of flowchart is from top to bottom and left to right. Arrowheads are required only when the normal top to bottom flow is not to be followed. However, as a good practice and in order to avoid confusion, flow lines are usually drawn with an arrowhead at the point of entry to a symbol. Good practice also dictates that flow lines should not cross each other and that such intersections should be avoided whenever possible. Decision The decision symbol is used in a flowchart to indicate a point at which a decision has to be made and a branch to one of two or more alternative points is possible. Figure 2.2 shows three different ways in which a decision symbol can be used. It may be noted from these examples that the criterion for making the decision should be indicated clearly within the decision box. Moreover, the condition upon which each of the possible exit paths will be executed, should be identified and all the possible paths should be accounted for. During execution, the a p p r o p r i a t e path is followed depending upon the result of the decision. Connector If a flowchart becomes very long, the flow lines start crisscrossing at many places that causes confusion and reduces the clarity of the flowchart. Moreover, there are instances when a flowchart becomes too long to fit in a single page and the use of flow lines becomes impossible. Thus, whenever a flowchart becomes too
Introduction to Computer Programming by OLADELE CAMPBELL

Page 20

complex that the number and direction of flow lines is confusing or it spreads over more than one page, it is useful to utilize the

IS I = 10?

No

Yes
(a) Two-way branch

A<B

COMPARE

A&B

A>B

A=B

b)

Three-way branch

I=?

0 (c) Multiple-way branch

Other

Figure 2.2

Different decision symbols with different ways of branching

connector symbol as a substitute for flow lines. This symbol represents an entry from, or an exit to another part of the flowchart. A connector symbol is represented by a circle and a letter or digit is placed within the circle to indicate the link. A pair of identically labeled connector symbols are commonly used to indicate a continued flow when the use of a line is confusing. So two connectors with identical labels serve the same function as a long flow line. That is, they show an exit to some other chart section, or they indicate an entry from another part of the chart. How is it
Introduction to Computer Programming by OLADELE CAMPBELL

Page 21

possible to determine if a connector is used as an entry or an exit point? It is very simple: if an arrow enters but does not leave a connector, it is an exit point and program control is transferred to the identically labeled connector that does have an outlet. It may be noted that connectors do not represent any operation and their use in a flowchart is only for the sake of convenience and clarity. Example 2.1 Draw a flowchart for adding marks in ten subjects obtained by a student in an examination. The output should print the percentage of marks of the student in the examination.

The flowchart for this problem is given in Figure 2.3 The first symbol is a terminal labeled START. It shows that this is the starting point or beginning of our flowchart logic. The second symbol is an input/output (I/O) symbol that is labeled specifically to show that this step is to read input data. This step will input the roll number, name, and the marks obtained by the student from an input device into the main storage of the computer system. The third symbol is a processing symbol which is suitably labeled to indicate that at this step, the computer will add the marks obtained by the student in various subjects and then store the sum in a memory location which has been given the name TOTAL. The fourth symbol is again a processing symbol. The label inside it clearly indicates that the percentage marks obtained by a student is calculated at this stage by dividing TOTAL by 10 and the result is stored in a memory location which has been given the name PERCENTAGE. The fifth symbol is an input/output (I/O) symbol and is labeled WRITE OUTPUT DATA.

START

READ ALL INPUT DATA

ADD MARKS OF ALL SUBJECTS GIVING TOTAL Introduction to Computer Programming by OLADELE CAMPBELL

Page 22

PERCENTAGE = TOTAL/10

WRITE OUTPUT DATA

STOP

Figure2.3 Flowchart for calculating percentage of marks Example 2.2 Draw a flowchart for calculating the average percentage marks of 50 students. Each student appeared in ten subjects. The flowchart should show the counting of the number of student who have appeared in the examination and the calculation should stop when the number of counts reaches the number 50. Since all the students have appeared in the same examination, so the process of calculation and printing the percentage marks obtained by each student will basically remain the same. The process of reading the input data, adding the marks of all subjects, calculating the percentage, and then writing the output data, is to be repeated for all the 50 students. In this situation where the same logical steps can be repeated, the flow line symbols are used in a flowchart to indicate the repetitive nature of the logic in the form of a loop. Figure 2.4 shows a flowchart which uses a decision step to terminate the algorithm. In this flowchart, another variable COUNT has been introduced which is initialized to zero outside the process loop and is incremented by 1 after processing the data for each student. Thus, the value of COUNT will always be equal to the number of students whose data has already been processed. At the decision step, the value of COUNT is compared with 50 which is the total number of students who have appeared for the
Introduction to Computer Programming by OLADELE CAMPBELL

Page 23

examination. The steps within the process loop are repeated until the value of COUNT becomes equal to 50. As soon as the value of COUNT becomes equal to 50, the instruction at the decision step causes the control to flow out of the loop and the processing stops because a terminal symbol labeled STOP is encountered.
START COUNT = 0 READ ALL INPUT DATA ADD MARKS OF ALL SUBJECTS GIVING TOTAL PERCENTAGE = TOTAL/10 WRITE OUTPUT DATA ADD 1 TO COUNT

COUNT = 50?

NO Yes STOP

Figure2.4 Flowchart for example 2.2 2.8.2.3 Designing a General Flowchart The flowchart shown in Figure 2.4 is not a general flowchart for the Example 2.2 for calculating the p e r c e n ta g e of marks of any number of students appearing in the examination. A good program should be general in nature. For example, in this case we should write a program that need not be modified every time, even if the total number of students changes.
Introduction to Computer Programming by OLADELE CAMPBELL

Page 24

To overcome these drawbacks, another method can be adopted to control the loop. In this method, the end of input data is marked by a trailer record, that is, the last data record in the input is followed by a record whose main purpose is to indicate that the end of the input data has been reached. Suppose the first 7 characters of the input record of a student represents his roll number (ROLLNO). Since 0000000 is never used as a roll number, a value of 0000000 as the first 7 characters can be used to represent the trailer record. As each input record is processed, the ROLLNO can be compared with 0000000 to determine if processing is complete. The logic of this process is illustrated in the flowchart given in Figure 2.5.
STOP READ INPUT DATA

ROLL NO = 0000000
No

Yes

ADD MARKS OF ALL SUBJECTS GIVING TOTAL PERCENTAGE = TOTAL/10 WRITE OUTPUT DATA Figure 2.5 A General Flowchart for example 2.2

STOP

2.8.2.4 What is Trailer Record? The concept of a trailer record centers around the notion of selecting a field (a particular item of data) in the input record which will be used to indicate the end of data, and then selecting a trailer value also known as sentinel value which will never occur as normal data value for that field. The roll number 0000000 is a trailer record for Example 2.2.
Introduction to Computer Programming by OLADELE CAMPBELL

Page 25

Example 2.3 Extend the flowchart represented in Figure 2.5 to count the number of students who have scored percentage marks more than 30. The flowchart should give the result of the students scoring the percentage marks equal to or more than 30. The flowchart in Figure 2.6 is a solution to this problem. There are two decision symbols in this flowchart. The first decision symbol checks for a trailer record by comparing ROLLNO against the value 9999999 to determine if processing is complete. The second decision symbol is used to check whether the student has passed or failed by comparing the percentage marks obtained by him against 30. If the students PERCENTAGE is equal to or more than 30, then he has passed, otherwise he has failed. Note from the flowchart that the operation WRITE OUTPUT DATA is performed only if the student has passed. If he has failed, we directly perform the operation READ INPUT DATA without performing the WRITE operation. This ensures that the output list provided by the computer will contain the details of only those students who have passed in the examination. Another point to be noted in this flowchart is the use of variable COUNT. This variable has been initialized to zero in the beginning and is increased by 1 every time the operation WRITE OUTPUT DATA is performed. But we have seen that the operation WRITE OUTPUT DATA is performed only for the students who have passed. Hence, the variable COUNT will be increased by 1 only in the case of those students who have passed. Thus, the value of COUNT will always be equal to the number of students whose data has already been processed and who have been identified as passed. Finally, when the trailer record is detected, the operation WRITE COUNT will print out the final value of COUNT that will be equal to the total number of students who have passed the examination.

Introduction to Computer Programming by OLADELE CAMPBELL

Page 26

START

COUNT = 0 READ INPUT DATA

ROLL NO = 9999999? No

yes

ADD MARKS OF ALL SUBJECTS GIVING TOTAL PERCENTAGE = TOTAL/10

WRITE OUTPUT DATA

STOP

IS PERCENTAGE = > 30 ? Yes ?

No

WRITE OUTPUT DATA ADD 1 TO COUNT

Figure2.6

Flowchart for example 2.3

2.8.2.5Flowcharting Rules (a) First formulate the main line of logic, then incorporate the details. (b) Maintain a consistent level of detail for a given flowchart. (c) Do not give every detail on the flowchart. A reader who is interested in greater details can refer to the program itself. (d) Words in the flowchart symbols should be common statements and easy to understand. (e) Be consistent in using names and variables in the flowchart. (f) Go from left to right and top to bottom in constructing the flowchart. (g) Keep the flowchart as simple as possible. The crossing of flow lines

should be avoided as far as possible. (h) If a new flowcharting page is needed, it is recommended that the flowchart be broken at an input or output point. Moreover, properly labeled connectors should be used to link the portions of the flowchart on different pages. 2.8.2.6 Advantages of Flowcharts Conveys Better Meaning Since a flowchart is a pictorial representation of a program, it is easier for a programmer to understand and explain the logic of the program to some other programmer. Analyses the Problem Effectively A macro flowchart that charts the main line of logic of a software system becomes a system model that can be broken down into detailed parts for study and further analysis of the system. Effective Joining of a Part of a System A group of programmers are normally associated with the design of large software systems. Each programmer is responsible for designing only a part of the entire system. So initially, if each programmer draws a flowchart for his part of design, the flow- charts of all the programmers can be placed together to visualize the overall system design. Any problem in linking the various parts of the system can be easily detected at this stage and the design can be accordingly modified. Flowcharts can thus be used as working models in the design of new programs and software systems. Efficient Coding Once a flowchart is ready, programmers find it very easy to write the concerned program because the flowchart acts as a roadmap for them. It guides them in proceeding from the starting point of the program to the final point ensuring that no steps are omitted. The ultimate result is an error free program developed at a faster rate. Systematic Debugging Even after taking full care in program design, some errors may remain in the program because the designer might have never thought about a particular case. These errors are detected only when we start executing the program on a computer. Such type of program errors are called bugs and the process of removing these errors is known as debugging. A flowchart is very helpful in detecting, locating, and removing mistakes (bugs) in a program in a systematic manner. Systematic Testing Testing is the process of confirming whether a program will successfully do all the jobs for which it has been designed under the specified constraints. For testing a program, different sets of data are fed as input to that program to test the different paths in the program logic.

2.8.2.7 Limitations of Flowcharts Takes More Time to Draw Flowcharts are very time consuming and laborious to draw with proper symbols and spacing, especially for large complex pro- grams. Difficult to Make Changes Owing to the symbol-string nature of flowcharting, any changes or modifications in the program logic will usually require a completely new flowchart. Redrawing a flowchart is tedious and many companies either do not change them or produce the flowchart by using a computer program to draw it. Non-standardization There are no standards determining the amount of detail that should be included in a flowchart. 2.8.3 Decision tables Purpose A decision table is a two-dimensional table that shows the action to be taken following a series of related decisions (or conditions). Strengths, weaknesses, and limitations When an algorithm involves more than two or three nested decisions, a decision table gives a clear and concise picture of the logic. Such algorithms are difficult to describe using logic flowcharts, Nassi-Shneiderman charts, pseudocode or structured English. Additionally, decision tables are relatively easy for non-technical users to follow. Decision tables are not useful for describing non-decision algorithms. They were common in the 1970s and 1980s, but few modern analysts or programmers are familiar with them. Inputs and related ideas Before creating a decision table, the designer must understand the algorithm or procedure. The necessary information might be compiled from direct observation, extracted from existing documentation, or derived from the problem definition and/or analysis stages of the system development life cycle. Concepts Assume that the mens basketball coach wants to look through the student records and produce a list of all full-time male students who are at least 6 feet 5 inches (or 77 inches) tall and who weigh at least 180 pounds. A decision table for an appropriate algorithm is shown as fig. 2.7 It is divided into four sections or quadrants: a condition stub at the upper left, a condition entry at the upper right, an action stub at the lower left, and an action entry at the lower right. The questions are listed in the condition stub; note that each question (in this case) requires a yes/no response. The associated actions are listed in the action stub. The responses (Y or N) are recorded in the condition entry, while the appropriate action is indicated in the action entry.

Figure 2.7 A decision table. The easiest way to understand a decision table is to read one. Start with the first question: Is the student male? There are two possible answers: yes (Y) or no (N). If the answer is no, then the student is not male, is not a candidate for the mens basketball team, and can be rejected. Move down the column containing the N and note the X on the action entry line following the action Reject the student. If the answer is yes, however, the coach cannot yet make a decision to add the student to the list because the student must first pass three more tests. Move on to the second question: Is the student taking at least 12 credit hours? Again, there are two possible answers: yes or no. Note how the answers are recorded on Figure 2.7. The second Y is directly under the first one, implying that the answers to both questions (plus two more) must be yes before the action identified by an X in that columns action entry can be taken. If the answer to the second question is no, however, the student can be rejected. Note that any single N, by itself, is enough to reject the student. Read the rest of the table. It clearly shows that the students name and address will be listed only if the answers to all four questions are yes, but that the student will be rejected if the answer to any one question is no. Software for Drawing Decision Tables Decision tables can conveniently be constructed using a spreadsheet program. They can also be prepared using Visio. Other charting programs (such as Micrografxs Flowcharter) can also be used. Summary of Key terms Decision table A two-dimensional table that shows the action to be taken following a set of related decisions

Action entry The box at the lower right of a decision table where the appropriate action is indicated. Action stub The box at the lower left of a decision table where the possible actions are listed. Condition entry The box at the upper right of a decision table where the responses (Y or N) to the questions in the condition stub are listed. Condition stub The box at the upper left of a decision table where the questions (or decisions) are listed. 2.8.4 Decision trees Purpose A decision tree is a two-dimensional graphic representation of the decisions, events, and consequences associated with a problem. Decision trees are decision science tools typically used to determine probabilities and/or expected values and to illustrate alternative system strategies. They can also be used to plan or document all possible paths through a series of nested decisions. Strengths, weaknesses, and limitations When an algorithm involves more than two or three nested decisions, a decision tree gives a clear and concise picture of the logic. Such algorithms are difficult to describe using logic flowcharts, Nassi-Shneiderman charts , pseudocode or structured English Decision trees are not useful for planning or documenting non-decision algorithms. Many technical people are unfamiliar with decision science, so a decision tree might not be an effective communication tool. Inputs and related ideas Before creating a decision tree, the designer must understand the algorithm or procedure. The necessary information might be compiled from direct observation, extracted from existing documentation, or derived from the problem definition and/or analysis stages of the system development life cycle. Concepts Decision trees are decision science tools that can be used to plan or document nested decision logic. Decisions, events, and outcomes Imagine a company has an opportunity to purchase for $500,000 exclusive rights to market a new product. If the product succeeds, the company stands to make $1,000,000. On the other hand, if the product fails, the company loses its entire investment.

The decision tree pictured in Figure 2.8 graphically represents the problem. The tree starts (on the left) with an act fork (a small box) that indicates a decision. Emanating from it are two branches representing the two choices: buy or do not buy the rights.

Figure.2.8 A decision tree. Move along the buy branch. The circle represents an event fork. An event is an occurrence that is not entirely subject to the decision-makers control. (In other words, an event carries risk.) Coming from the event fork are branches representing all possible consequences (or outcomes) of the decision. (In this case, the product is either a success or a failure.) At the far right, each branch terminates in an outcome. If the product is successful, the company stands to make $1,000,000. If it fails, the company loses $500,000. Go back to the act fork. Before the decision is made, the company has an option not to buy the rights. Clearly, this decision will cost nothing. There are no consequences associated with this choice, so the outcome is zero whether the product is successful or not. The oval symbols at the right of the decision tree list all possible outcomes. At this point, a management scientist or decision scientist might associate probabilities with each outcome, compute the expected values, and determine whether or not rights should be purchased. Nested decisions Decision trees can also be used to model nested decisions. Assume, for example, that the mens basketball coach wants to look through the student records and produce a list of all full-time male students who are at least 6 feet 5 inches (or 77 inches) tall and who weigh at least 180 pounds. The algorithm consists of a series of four nested questions or decisions (Figure 2.9), each one represented as a box (an act fork).

Figure 2.9

A decision tree can be used to model nested decisions.

Start with the first question: Is the student at least 77 inches tall? There are only two possible answers. If the student is less than 77 inches tall, he or she is rejected. If the student is greater than or equal to 77 inches tall, a second question is asked, and so on. Follow each branch on the tree to its logical outcome. Note that a students name and address are listed only if the student meets all four criteria. Key terms Act fork A point on a decision tree (represented by a box) where a decision is made. Event An occurrence that is not entirely subject to the decision-makers control represented by a circle in the decision tree. Event fork A point on a decision tree (represented by a circle) where subsequent branches identify the consequences (or possible outcomes) of a decision. Outcome On a decision tree, a final result of a series of decisions and/or outcomes. It is represented by an oval in the decision tree. CHAPTER THREE SOFTWARE DESIGN PRINCIPLES

LEARNING OBJECTIVES At the end of this chapter you should be able to: 1. 2. 3. 4. Understand the basic building blocks for developing algorithms Explain modular programing concept Explain top-down design technique Illustrate program design with structure chart

CHAPTER FOUR SOLVING PROGRAMMING PROBLEMS

L OBJECTIVES At the end of this chapter, you should be able to 1. Understand the concept of solvability of programming problem 2. Understand the procedure for developing computer program 3. Design algorithms

CHAPTER FIVE PROGRAMMING LANGUAGES CHAPTER OBJECTIVES

At the end of this chapter, you should be able to 1. 2. 3. 4. 5. Explain the distinguishing features of machine, low level and High level languages State the advantages and disadvantages of ML, LL, and HL Know various programming languages Differentiate between types of programming languages Distinguish between system commands and program statements.

CHAPTER SIX CONCEPT OF DEBUGGING AND MAINTENANCE OF PROGRAMS CHAPTER OBJECTIVES At the end of this chapter, you should be able to :

1. 2. 3. 4. 5. 6.

Explain debugging Identify sources of bugs in programs Explain syntax, logical and runtime errors Identify techniques of locating bugs in programs Explain program maintenance Distinguish between debugging and maintaining programs

CHAPTER 7 GOOD PROGRAMMING PRACTICES CHAPTER OBJECTIVES At the end of this chapter, you should be able to : 1. Explain Graphic User Interface

2. Structured approach to

Vous aimerez peut-être aussi