Вы находитесь на странице: 1из 45

INTRODUCTION TO COMPUTER PROGRAMMING

AIM: This course seeks to introduce you to the ever promising and profitable field of computer programming; a field that has turned many who came into it just like you into worlds richest men! GENERAL LEARNING OBJECTIVES After reading and studying this lecture note, and performing or participating in the accompanying lab exercises, you should be able to: 1. Understand the features of a good program.
2. Understand the concept of Algorithm and flowcharting. 3. Understand the principles of designing algorithm for common

programming problem.
4. Understand the procedure for solving programming problem. 5. Understand the modular program design principle 6. Understand the various levels of programming language. 7. Understand the concept and art of debugging and maintaining

programs. 8. Understand good programming practices.

Chapter 1
1

INTRODUCTION TO PROGRAMMING
LEARNING OBJECTIVES: After reading and studying this chapter, and performing the lab exercises you should be able to: 1.
2. 3. 4. 5. 6.

Define a program Define programming State who a programmer is Explain the features of a good program. Mention some programming languages Run simple programs in Java and V.B

INTRODUCTION Computer programs are the essential drivers in todays world of information technology. They are needed on computers, your GSM phones, home appliances, robots, planes, etc. Any where you want to bring automation, in which you intend to employ artificial drivers; you will need to have programs in such areas to make automatic operation of devices possible. This is reason why your knowledge and skills at developing good computer programs will give you exciting and profitable career, as the world in still in need of people with such knowledge. WHAT IS A PROGRAM As earlier stated programs are embedded in computer and other devices where automation in needed. These programs direct these devices to perform as the human users and designers intended. Simply, a program is a set of instructions that tell a computer (or any similar system) what to do, how to do it and when to do it. A FORMAL DEFINITION A program is a set of instructions written in a logical sequence, interpreted and executed by a computer (or any similar system or device), enabling the system to perform a required function. A set of programs is called software. Thus the terms program and software are
2

used interchangeably. Programs are the thought processes of such computing agents. A program has an executable form that the computer can use directly to execute the instructions. The same program in its humanreadable source code form, from which executable programs are derived (e.g., compiled) can be read, understood, and modified by another programmer. Computer source code is often written by professional computer programmers. Source code is written in a programming language. Examples of programming languages are Visual Basic, Java, C, C++, Python, Perl, etc.

#include <stdio.h> int main(void) { puts("Hello world!"); return 0; } Figure 1: Source code of a program written in the C programming language

A computer program model Since a computer program is a sequence of instructions which operate on data we can show this in a simple model: The model implies that the program processes data which comes from a source and goes to a destination - the data sink. Although it isn't always the case, in larger programs and programming systems the source and sink are usually external to the program. A data source will be an input or storage device like a keyboard, disk drive, scanner, tape drive, a data sink will be an output or storage device like a computer screen, printer, disk drive, tape drive, plotter etc.
3

WHAT IS PROGRAMMING? Computer programming is the iterative process of writing or modifying computer programs. Computer programming involves testing, analyzing, and refining, and sometimes coordinating with other programmers on a jointly developed program. A person who practices this skill is referred to as a computer programmer or software developer. The sometimes lengthy process of computer programming is usually referred to as software development. The term software engineering is becoming popular as the process is seen as an engineering discipline.

Software Development Life Cycle A program may result from some problem, in this case problem means some task requiring a solution, or from a bright idea, or because it is a project which has been set for student. No matter what their first causes computer programs, aka software, and software systems, collections of softwares, have quite well-defined life cycles. The need for a program is recognised, the requirements are analysed, a possible solution is designed, the prototype is built and tested, and finally the program is put into use. Figure 3 shows the typical life-cycle for a computer program. During phase one the emphasis is on fact-gathering and determining where the boundaries of the problem are. Phase two involves the steps of identifying the variables and processes which make up the problem. Phase 3 is where you will use the tools and techniques that you learn in this course. During this phase the strategies which will solve the problem are developed. Phase 4 represents the time when the solution to the problem, the programs or system, is constructed.
4

Phase 5 is a critical time but can be minimised if the previous steps are correct. Phase 6, the maintenance phase, is the time when the solution is in active use. It may undergo enhancements or it may have bugs fixed during its lifetime. There is a strong connection between phases 2 and 3 since the process of designing a solution to a problem is an iterative process and often involves a great deal of discovery. For example as you refine an algorithm you might discover that there are variables and/or processes that weren't obvious during phase 2. This is to be expected, after all you are just learning about this kind of thing, but you can expect to meet this kind of discovery right throughout your life as a program designer. Variables and Processes A variable is something whose value will change over time. For example daily temperature is a variable. If you measure the room temperature now and measure it one hour from now there is every chance that the two measurements will give different values. In this example the word temperature represents a variable. A process is an activity which, in computing terms, transforms data. In general terms a process is an activity which involves some steps designed to achieve a particular outcome. Processes take data, the contents or values of variables, and transform it. It is useful to show processes and the data they act on in a simple diagram form as shown here in Figure 2. This figure is very similar to the Data Source - Program - Data Sink figure you saw in the introduction. It shows that processes have inputs, transform data and generate outputs. An example might be a payroll calculation process which has inputs called Hours_Worked and Pay_Rate and which produces an output called Gross_Pay. In this example Hours_Worked, Pay_Rate and Gross_Pay are all variables Figure 3 shows a more usual way of representing processes and variables and is used here just to emphasise the nature of processes and variables. Note that variable names like Hours_Worked, Pay_Rate and Gross_Pay are often written with underscores. This is to help clearly identify the variables by giving them
5

names and because most computer languages don't recognise variable names which contain spaces. There is no substantial difference between computer processes as they are described here and computer programs. In Figure 3 the Calculate_Gross_Pay process could be a complete computer program or it could be a process within a program. This is an important point to keep tucked away at the back of your mind as you develop your skills and knowledge in 3GL Program Design. CHARACTERISTICS OF A GOOD PROGRAM Many programs that are written are eventually rejected by the users for failure to satisfy some of the following requirements. So as a beginning programmer or a professional programmer in the making you will need take the following into consideration when developing programs so that your program will sell! However, as a beginning you may have problems appreciating some of the good programming principles or counsels you will be reading below. As u gain some experience in this programming course you will begin to understand and appreciate this pieces of programming wisdom. 1. The Right Problem Has Been Solved Programmers must be very careful that each module eventually implemented is the module that was, in fact, required. It is all too easy to become immersed in details and, as a result, to lose sight of original requirements. Requirements are what the users want the program to do. Solving almost the required problem results in unsatisfied customers and/or unfortunate incidents. It is important that requirements (which may, in fact, change with time) be reviewed continually throughout implementation. The requirements themselves might be erroneous or incomplete, or simply misunderstood. Be careful not to embellish the implementation with features not specifically requested (but fun to do). This introduces even further chance of error. 2. The Implementation is free of Errors
6

Of equal importance to solving the right problem is producing an implementation that works. It must work for all valid inputs and must produce the required response, for example, an error indication, for all invalid inputs. This seems obvious, yet is difficult to ascertain for modules of any significant size or complexity. Too many programmers accept bugs (or errors) as a natural consequence of the human condition and view debugging as an eternal fact of life. There is no particular reason why this should be so. Programmers are usually responsible for bugs through carelessness, lack of understanding of design specifications or language features, or failure to anticipate a particular situation to which the program was applied. Programmers do not do this deliberately (nobody enjoys debugging) and, in fact, can avoid making most of these errors. However it might be done, it is clearly the responsibility of the programmer to ensure that the program is error-free. The programmer must resort to methods, such as testing, to establish the correctness of a program. 3. The Program Is Well Documented A computer program without documentation is like a major appliance without operating instructions. Just as the operator of the appliance needs instructions on how to use it, so too does a user of the computer program. This forms part of what is known as documentation. It is important that computer programs be well documented. Documentation exists to assist in the understanding or use of a program. This can be of great value not only to those charged with maintaining or modifying a program, but also to the programmers themselves. Details of particular programs, or particular pieces of programs, are easily forgotten or confused without suitable documentation. Documentation comes in two forms: external documentation, which includes such things as reference manuals, algorithm descriptions, flowcharts, and project workbooks; and internal documentation, which
7

is part of the source code itself (essentially, the declarations, statements, and comments). The value of internal documentation cannot be overemphasized. For any program, the source text and/or compilation listing itself constitutes the front line of program documentation. For this reason, we emphasize the importance of highly readable programs. 4. The Program Is Maintainable Programs modification require to a continuing pace with process of and maintenance requirements modifiability and and are keep changing

implementation

technologies.

Maintainability

essential characteristics of real programs. A program's ability to be read and understood is an important prerequisite to its maintainability and modifiability. You can make your program maintainable by: - dividing the program into modules - making sure that the program is well-documented - using symbolic constants Many programming languages permit the declaration of a named constant, which equates a user-chosen identifier, say, CLASS_SIZE, with a literal constant. Thus, #define CLASS_SIZE =37 will occur, in only one place, namely, the constant declaration in a C program. This, then, requires only one alteration to change the value class size throughout the program. 5. The Program must be Robust A program is said to be robust if it survives various unexpected events, such as incorrect or invalid input data. Here are some guidelines to ensure robustness: (i) Always validate the input data. Never assume that the data is always correct. (ii) Always initialize relevant variables.

(iii)

Avoid

syntactic

constructs

that

could

lead

to

undesirable

interpretation. e.g. if condition then if condition then statement else statement Use delimiters (such as begin/end pairs or { .... } to clarify logic. 6. Readability: The program codes will be easy for a programmer to read and understand the logic involved in the programming. 7. Storage Saving: A good program design is not to be verbose, that is, it will not be allowed to be unnecessary long, thereby consuming much storage that will be required for processing data and storage of information produced from processing. 8. Efficiency: The less the amount of system resources a program consumes (processor time, memory space, slow devices, network bandwidth and to some extent even user interaction)the better. ELEMENTS OF PROGRAMMING STYLE The individual programmer's style (or lack of it), can contribute significantly to the outcome and maintainability of a program. It is important that you as a beginning programmer recognize the importance of style in the practice of your craft, and develop habits of programming style that will carry you in good stead in your professional life. Just as a good writing style does not come simply from a thorough knowledge of rules of English grammar, neither does a good programming style come from a thorough knowledge of the syntax of a programming language.

Here are some guidelines to aid in the development of good programming style: - Choice of Identifiers An appropriate choice of identifiers for the names of modules, subprograms, types, variables, and other elements is crucial in producing a readable program. The goal is to use meaningful identifiers which help the reader remember the purpose of an identifier without constantly referring to the declarations or to a variable list external to the program. - Avoid cryptic abbreviations! Longer identifiers should be used for the most significant objects in a program and for those objects used in many locations, as for example, the name of a frequently used subprogram. Shorter identifiers should be used for strictly local objects. For example, I is useful as the index of an array in a loop; ARRAYINDEX is not necessary. K, on the other hand, is undesirable as the name of a major data structure. Where languages allow a break character, use it in multiword identifiers. Use MONTHLY_PAY rather than MONTHLYPAY. Alternatively, use capitalization, as in MonthlyPay. If abbreviation is to be used, abbreviate the more common word(s) of the multiword identifiers. Thus, use BADDATA-MSG rather than BAD-DAT-MESSAGE. Use a standard set of abbreviations on a project. The same program should not have INITIALMSG, ERROR_MES, and OVERFLOW-MESG, where MSG, MES, and MESG are all abbreviations for message. Parts of speech should be used consistently. A typical standard is as follows:
-

Use nouns to name data objects such as variables, constants, and types. Use PAYMENT rather than PAID or TO-PAY as the value to be paid.
10

Use verbs to name procedures. Thus, COMPUTE_NEXT_MOVE or GET_NEXT_CHAR is the procedure to perform these actions, rather than NEXT_MOVE_COMPUTATION or NEXT_CHAR.

We summarize this discussion as follows: the identifier naming an object should suggest the meaning of the object to the reader of the program. Structured Programming To a large extent the structure of a program is determined by the constructs used to direct the flow of control. It is important to remember that while you read the program listing from top to bottom, execution of the program may proceed in a very different way. One of the main goals of structured programming is to structure the flow of control in such a way that the execution sequence is as close as possible to the reading sequence. This enforces a discipline on the programmer in terms of control structures that can be used, and further, on the manner in which they can be used. Program Presentation Issues Comments constitute a major component of a program's internal documentation. They serve to help the reader understand the intent or purpose of portions of code, and can also assist in explaining the logic of difficult sections. Beginning programmers are seldom given any instruction in the writing of comments; yet the writing of good comments is probably as important, and perhaps as difficult to learn, as the writing of good programs. Good comments cannot do much to improve bad code, but bad comments can seriously detract from good code. Always make sure that comments and code agree. If you make a change to the code, be sure that a similar change is made to any comment relating to it. This is often overlooked.

11

Indentation (or paragraphing) is another important feature used to enhance readability. In any written text, paragraphing serves two main purposes: to identify structural units of the text and to relieve the tedium of the reading process. Both apply to programs as well. Indentation can be of great assistance in revealing the logical structure of a program (or algorithm). We have adopted the convention that, as a rule, a new line is begun for each alternative of an if construct, and that where alternatives consist of more than a single statement, subsequent statements be indented to the point of the first. This shows the alternatives clearly, and the conditions affecting their choice. Further, if nesting is involved, it too is clearly shown. One difficulty that can arise is running out of space on a line within a very deeply nested control structure. More likely, however, this results from failure to modularize the program sufficiently. Some authors advocate that no more than four levels of nesting be allowed in a single module. Effective Use of White Spaces: Most programming languages allow the use of blank lines and spaces embedded within the program code to improve its readability. Always separate blocks by one or more blank lines. Statements such as x=x+1 would be better written as x = x + 1. Use spaces and blank lines effectively to avoid clutter and make program more readable. Issues of program presentation seldom cause errors, but they can play a large role in avoiding them. Too many programmers dismiss these matters as simply window dressing, preferring instead to devote their energies to the more creative aspects of the job. As a key factor in the readability of the final program, its presentation serves to enhance its overall quality, in addition to giving the program a pleasing, professional appearance.

12

Chapter 2
INTRODUCTION TO ALGORITHMS
LEARNING OBJECTIVES: After reading and studying this chapter, and performing the lab exercises you should be able to: - Define algorithm - Explain features of an algorithms
-

Describe and use the various methods of representing algorithms: English (step form) Pseudocode Flowcharts Decision trees Programming language

2.1 ALGORITHMS The term algorithm originally referred to any computation performed via a set of rules applied to numbers written in decimal form. The word is derived from the phonetic pronunciation of the last name of Abu Ja'far Mohammed ibn Musa al-Khowarizmi, who was an Arabian mathematician who invented a set of rules for performing the four basic arithmetic operations (addition, subtraction, multiplication and division) on decimal numbers. An algorithm is a representation of a solution to a problem. If a problem can be defined as a difference between a desired situation and the current situation in which one is, then a problem solution is a
13

procedure, or method, for transforming the current situation to the desired one. We solve many such trivial problems every day without even thinking about it, for example making breakfast, travelling to the workplace etc. But the solution to such problems requires little intellectual effort and is relatively unimportant. However, the solution of a more interesting problem of more importance usually involves stating the problem in an understandable form and communicating the solution to others. In the case where a computer is part of the means of solving the problem, a procedure, explicitly stating the steps leading to the solution, must be transmitted to the computer. This concept of problem solution and communication makes the study of algorithms important to computer science. Throughout history, man has thought of ever more elegant ways of reducing the amount of labour needed to do things. A computer has immense potential for saving time/energy, as most (computational) tasks that are repetitive or can be generalised can be done by a computer. For a computer to perform a desired task, a method for carrying out some sequence of events, resulting in accomplishing the task, must somehow be described to the computer. The algorithm can be described on many levels because the algorithm is just the procedure of steps to take and get the result. The language used to describe an algorithm to other people will be quite different from that which is used by the computer, however the actual algorithm will in essence be the same. 2.2 ALGORITHM DEVELOPMENT Programming is difficult (like many activities that are useful and worthwhileand like most of those activities, it can also be rewarding and a lot of fun). When you write a program, you have to tell the computer every small detail of what to do. And you have to get everything exactly right, since the computer will blindly follow your program exactly as written. How, then, do people write any but the most simple programs?
14

Its not a big mystery, actually. Its a matter of learning to think in the right way. A program is an expression of an idea. A programmer starts with a general idea of a task for the computer to perform. Presumably, the programmer has some idea of how to perform the task by hand, at least in general outline. The problem is to flesh out that outline into a complete, unambiguous, step-by-step procedure for carrying out the task. Such a procedure is called an algorithm. (Technically, an algorithm is an unambiguous, step-by-step procedure that terminates after a finite number of steps; we dont want to count procedures that go on forever.) An algorithm is not the same as a program. A program is written in some particular programming language. An algorithm is more like the idea behind the program, but it is the idea of the steps the program will take to perform its task, not just the idea of the task itself. The steps of the algorithm dont have to be filled in complete detail, as long as the steps are unambiguous and its clear that carrying out the steps will accomplish the assigned task. An algorithm can be expressed in any language, including English. Of course, an algorithm can only be expressed as a program if all the details have been filled in. So, where do algorithms come from? Usually, they have to be developed, often with a lot of thought and hard work. Skill at algorithm development is something that comes with practice, but there are techniques and guidelines that can help. Here is an algorithm that a student performs in order to be ready for lectures. ALGORITHM FOR PREPARING FOR CLASS 1. WAKE UP 2. PRAY 3. WASH UP 4. DRESS UP 5. EAT YOUR BREAKFAST 6. TAKE YOUR BOOKS 7. GO TO CLASS 8. ENTER THE LECTURE ROOM
15

9. SIT DOWN
10.

FINISH

Now try out this exercise :

1.

Write an algorithm for a cook to follow in order to prepare a dish of jollof for four visitors.

2.3 DEFINITION: A procedure is a finite sequence of well-defined instructions, each of which can be mechanically carried out in a finite amount of time. The procedure must break up the problem solution into parts that the recipient party can understand and execute. In the case of a computer, the problem solution is usually in the form of a program that encompasses the algorithm and explains to the computer a clearly defined procedure for achieving the solution. The procedure must consist of smaller steps each of which the computers understand. There may be no ambiguities in the translation of the procedure into the necessary action to be taken. A program is then just a specific realisation of an algorithm, which may be executed on a physical device. A computer is essentially a physical device designed to carry out a collection of primitive actions. A procedure is a sequence of instructions written in terms which evoke a proper operation. To make effective use of an algorithm on a computer one must not only find and understand a solution to the problem but also convey the algorithm to the computer, giving the correct sequence of understood commands that represent the same algorithm. Formal Definition:
16

An algorithm is procedure consisting of a finite set of unambiguous rules (i.e., steps or instructions) which specify a finite sequence of operations that provides the solution to a problem, or to a specific class of problems for any allowable set of input quantities (if there are inputs). In other word, an algorithm is a step-by-step procedure to solve a given problem Alternatively, we can define an algorithm as a set or list of instructions for carrying out some process step by step. A recipe in a cookbook is an excellent example of an algorithm. The recipe includes the requirements for the cooking or ingredients and the method of cooking them until you end up with a nice cooked dish. In the same way, algorithms executed by a computer can combine millions of elementary steps, such as additions and subtractions, into a complicated mathematical calculation. Also by means of algorithms, a computer can control a manufacturing process or coordinate the reservations of an airline as they are received from the ticket offices all over the country. Algorithms for such large-scale processes are, of course, very complex, but they are built up from pieces. One of the obstacles to overcome in using a computer to solve your problems is that of translating the idea of the algorithm to computer code (program). People cannot normally understand the actual machine code that the computer needs to run a program, so programs are written in a programming language such as C or Pascal, which is then converted into machine code for the computer to run. In the problem-solving phase of computer programming, you will be designing algorithms. This means that you will have to be conscious of the strategies you use to solve problems in order to apply them to programming problems. These algorithms can be designed through the

17

use of English text ( or step-form), pseudocode, flowcharts, NassiSchneiderman Diagram, Decision tree. 2.4 STEP-FORM ALGORITHMS This form of algorithm is the simplest and consists of a sequence of numbered steps or points. It is the easiest to learn at first since it is rather like a "to-do" list however once you have mastered other ways of stating algorithms you are unlikely to continue using this form. You have already seen this form in the algorithm for preparing for class( see page 16).

2.2 PSEUDOCODE Pseudocode is one of the tools that can be used to write a preliminary plan that can be developed into a computer program. Pseudocode is a general way of describing an algorithm without use of any specific programming language syntax. It is, as the name suggests, pseudo code it cannot be executed on a real computer, but it models and resembles real programming code, and is written at roughly the same level of detail. Pseudocode, like step-form, is a written way of stating algorithms but uses a much more restricted vocabulary. It is very much like a 3GL and for many programmers and program designers is the preferred way to state algorithms and program specifications. Although there is no standard for pseudocode it is generally quite easy to read and use, for instance here is some pseudocode: DOWHILE kettle_empty Add_Water_To_Kettle END DOWHILE
18

As you can see it is a precise statement of a while loop. Pseudocode is a written statement of an algorithm using a restricted and well-defined vocabulary. In the next section you look at the vocabulary in detail. Input, output, iteration, decision and processing in pseudocode It is useful to separate the pseudocode keywords into several groups as shown here: Group Key words Example INPUT, ACCEPT, READ Used to get values from a data INPUT counter Input/Outp source, a keyboard for instance ut DISPLAY DISPLAY new_value Iteration Used to output values to a data sink, a screen or printer for instance REPEAT SET count_value TO statement 0 UNTIL <condition> REPEAT DISPLAY The REPEAT loop executes the count_value statement until the condition ADD 1 TO becomes true. count_value; UNTIL count_value > DOWHILE<condition> 10 statement END DOWHILE DOWHILE count_value < 10 The WHILE loop executes the DISPLAY statement while the <condition> is count_value true. count_value = count_value + 1 FOR <var> = <start value> to END DOWHILE <stop value> ENDFOR FOR count = 1 to 10 DISPLAY count + You haven't seen this loop before count but it is a special case of the While ENDFOR loop. The FOR loop iterates for a fixed number of steps. The While The statements and Repeat loops can be for a inside the loops are variable number of steps. indented to aid the readability of the
19

Decision

IF <condition> statement ENDIF IF THEN ELSE ENDIF

THEN

pseudocode. IF count > 10 THEN DISPLAY count ENDIF IF count > 10 THEN DISPLAY 'count > 10' ADD 4 to sum ELSE DISPLAY 'count <= 10' ADD 3 to sum ENDIF ADD 3 TO count SUBTRACT 5 FROM count SET count TO 12 COMPUTE 10 + count GIVING new_count

<condition> statement statement

Processing ADD, SET

SUBTRACT,

COMPUTE,

Although the processing group are very useful most program designers tend to prefer to use operators like:

+ * / =

add subtract multiply divide assign

These are the arithmetic operators. These are more intuitive since we use them in arithmetical expressions and they are easier to write, for instance: count = count + 22 x = count / 12 sum = sum - count x = count * sum

20

The assignment operator, = (as count = count + 32) means assign the results of the operation on the right-hand side to the variable on the lefthand side. There are two other classes of operators which are useful in pseudocode. One class is called the relational operators. These are used to evaluate the relationship between variables and are:

== <= >= <>

equal to (a pair of equals signs) less than or equal to greater than or equal to not equal to

Here are some examples of the use of the relational operators: IF count THEN ... == 32 This decision states that if the variable count contains 32 execute the statement following THEN. The statements in the while loop will execute while the value of count is 50 or less.

DOWHILE count <= 50 ... END DOWHILE REPEAT ... UNTIL count > 12

The statements in the repeat loop will execute until the value of count exceeds 12. If the value of count is not the same as the IF count <> total THEN value of total execute the statement ... following THEN. Using relational operators Don't confuse == (equal) with = (assignment). The first determines if a variable is the same as a value or another variable, but the second (assignment) makes a variable become some value. Remember == is two equals signs. A statement like count <= 50 is a proposition, you might remember from an earlier lesson that a proposition is a statement that has a truth value, it can be TRUE or FALSE. If count is less than or equal to 50 then the proposition count <= 50 is true. For example some pseudocode might help: count = 51 IF count <= 50 THEN DISPLAY 'Count is less than 51' ENDIF IF count > 50 THEN DISPLAY 'Count is greater than 50' ENDIF
21

The other class is called the logical operators which are used to form compound propositions and the logical operators are:

AND OR NOT

Using logical operators AND IF (x = = 32) AND (y == 7) THEN sumxy = x + y OR IF (letter = = 'A') OR (letter = = 'E') THEN DISPLAY 'Vowel' NOT IF NOT (letter = = 'A') THEN DISPLAY 'Not letter A' The logical operators can be used to combine relational expressions. The statement IF (x == 32) AND (y == 7) THEN sumxy = x + y says that if it is true that x == 32 AND it is also true that y == 7 then add x and y together and store the result in variable sumxy. The statement IF (letter == 'A') OR (letter == 'E') THEN DISPLAY 'Vowel' says that if the variable letter contains either 'A' or 'B' then display the word vowel on the output device. The whole expression (letter == 'A') OR (letter == 'E') is false if both letter == 'A' is false and letter == 'E' is false. The NOT operator in the last example statement IF NOT (letter = 'A') THEN DISPLAY 'Not letter A' is used to reverse the sense of a relational expression. If it is true that letter is equal to 'A', the NOT operator in NOT (letter = 'A') will give a value of FALSE. Here are some examples using the relational and logical operators, assume that A contains 20 and B contains 15
Expression A >= 20 A > 20 A == B A == B + 5 (A > B) AND (A > 20) (A > B) OR (B > A) (A < B) OR (B > A) NOT (A > B) NOT (NOT (A > B)) Result TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE

Problems with evaluating expressions:


22

What do we do with an expression like x = a * b + 7? If a is 10 and b is 5 is the answer 57 or is it 120? In other words do we do the multiplication part first (a * b) followed by the addition ( + 7) or do we do the addition part first (b + 7) then multiply by a? You might remember from school that there is an order of precedence for evaluating arithmetic expressions. In my day it was called PODMAS or BODMAS which I think meant parentheses (or brackets) outside divide, multiply, add, subtract. This means do what inside the parentheses first, and do divide, multiply before add and subtract. If we apply the PODMAS rule in the case of x = a * b + 7 the correct answer is 57. The same applies in computer languages and for our operators, arithmetic, logical and relational the order of precedence is:

( ) parentheses NOT * / AND + - OR == > < <> >= <=

The precedence is from top to bottom and on each line from left to right. Evaluate whatever is in parentheses first, then NOT followed by *, /, AND then +, -, OR then last the relational operators. FLOWCHARTS Flowcharting is a graphic representation of an algorithm. It is a tool developed in the computer industry, for showing the steps involved in a process. A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by arrows - each shape represents a step in the process, and the arrows show the order in which they occur. Flowcharting combines symbols and flowlines, to show figuratively the operation of an algorithm. In computing, there are dozens of different symbols used in flowcharting (there are even national and international flowcharting symbol standards). In business process analysis, a couple of symbols are sufficient. A box with text inside indicates a step in the process, while a diamond with text represents a decision point. See the figure for an example.
23

If the flowchart is too messy to draw, try starting again, but leaving out all of the decision points and concentrating on the simplest possible course. Then the session can go back and add the decision points later. It may also be useful to start by drawing a high-level flowchart for the whole organisation, with each box being a complete process that has to be filled out later. From this common understanding can come a number of things process improvement ideas will often arise spontaneously during a flowcharting session. And after the session, the facilitator can also draw up a written procedure - a flowcharting session is a good way of documenting a process. Process improvement starts with an understanding of the process, and flowcharting is the first step towards process understanding. Flowcharting Symbols There are 6 basic symbols commonly used in flowcharting of programs: Terminal, Process, input/output, Decision, Connector and Predefined Process. This is not a complete list of all the possible flowcharting symbols, it is the ones used most often Name Process in the structure of Assembly language programming. Symbol Function Indicates operation Memory input/output Used for any Input / Output (I/O) operation. computer is to obtain data or display output results Decision Used to ask a question that can
24

any

type

of

internal

inside the Processor or

Indicates

that

the

be Connector

answered

in

binary

format

(Yes/No,True/False) Allows the flowchart to be drawn without intersecting lines or without a reverse flow. Predefined Process Used to invoke a subroutine or an interrupt program. Terminal Indicates the starting or ending of the program, program. Flow Lines Off-page connector from one page to another page. Generally, there are many standard flowcharting symbols. General Rules for flowcharting 1. All boxes of the flowchart are connected with Arrows. (Not lines) 2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for all flowchart symbols is on the bottom except for the Decision symbol. 3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side. 4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it does not exceed 3 symbols. 5. Connectors are used to connect breaks in the flowchart. Examples are: From one page to another page. From the bottom of the page to the top of the same page.
25

process,

or

interrupt

Shows direction of flow. to connect breaks in the flowchart

An upward flow of more than 3 symbols 6. Subroutines have their own and independent flowcharts. 7. All flow charts start with a Terminal or Predefined Process (for subroutines) symbol. 8. All flowcharts end with a terminal or a contentious loop. Flowcharting uses symbols that have been in use for a number of years to represent the type of operations and/or processes being performed. The standardised format provides a common method for people to visualise problems together in the same manner. The use of standardised symbols makes the flow charts easier to interpret, however, standardizing symbols is not as important as the sequence of activities that make up the process. Examples of Algorithms and Flowcharts Example 1. Design an algorithm and the corresponding flowchart for adding the test scores as given below: 26, 49, 98, 87, 62, 75 a) Algorithm
1. Start 2. Sum = 0 3. Get the first testscore 4. Add firsttest score to sum 5. Get the second testscore 6. Add to sum 7. Get the third testscore 8. Add to sum 9. Get the Forth testscore 10. Add to sum 11. Get the fifth testscore 12. Add to sum 13. Get the sixth testscore 14. Add to sum 15. Output the sum 16. Stop

b) The corresponding flowchart is as follows:


Start Sum =26 0

Get Firsttestscore Sum = Sum + Firsttestscore Get Secondtestscore Sum = Sum + Secondtestscore Get Third testscore Sum = Sum + Thirdtestscore A

Get Fourthtestscore Sum = Sum + Fourthtestscore Get Fifthtestscore Sum = Sum + Fifthtestscore Get Sixthtestscore Sum = Sum + Sixthtestscore Display Sum Stop

27

The algorithm and the flowchart above illustrate the steps for solving the problem of adding six testscores. Where one testscore is added to sum at a time. Both the algorithm and flowchart should always have a Start step at the beginning of the algorithm or flowchart and at least one stop step at the end, or anywhere in the algorithm or flowchart. Since we want the sum of six testscore, then we should have a container for the resulting sum. In this example, the container is called sum and we make sure that sum should start with a zero value by step 2. Example 2: The problem with algorithm in example 1 is that, some of the steps appear more than once, i.e. step 5 get second testscore, step 7, get third testscore, etc. One could shorten the algorithm or flowchart as follows: 1. Start 2. Sum = 0 3. Get a testscore 4. sum = sum + testscore 5. Go to step 3 to get next testscore 6. Output the sum 7. Stop This algorithm is a bit shorter than the first one. In this algorithm, step 3 to 5 will be repeated, where a number is obtained and added to sum. One problem indicates that these steps will be repeated endlessly, resulting in an endless algorithm or flowchart. The algorithm needs to be improved to eliminate this problem. In order to solve this problem, we need to add a last value to the list of possible numbers for a student test score. This value should be unique so that, each time we get such a value, we test the value to see if we have reached the last value.

28

In this way our algorithm will be a finite algorithm which ends in a finite number of steps as shown below. There are many ways of making the algorithm finite. The value 1 is a unique number since we expect student testscore to be a positive number. 1. Start 2. Sum = 0 3. Get a testscore 4. If the value is equal to 1, go to step 7 5. Sum = Sum + testscore 6. Go to step 3 to get next testscore 7. Display sum 8. Stop Corresponding flowchart

Start Sum = 0

Get a testscore

Testscore

= -1

Yes

No
Sum = Sum + testscore Display Sum

Stop

2.3 DATA TYPES

29

Although some contemporary languages allow programmers to invent his own data types, and define their related operations, there are a number of traditional data types found in most languages: Integer Integers are numeric data items, which are either positive or negative including zero, i.e. 1, 488, -22, 0, 456. Some programming languages put restrictions on the magnitude of integers which may be used in program instructions. These restrictions are usually dependent on the size of the memory location of the computer in which the language may run. Real Numbers There are two types of real numbers, Fixed-Point and Floating Point. Fixed Point Fixed point data items are numbers which have embedded decimal point i.e. 1.5, 458.4589, -0.569. Floating Point Floating point data items are numbers, which are, held as binary fractions by a computer. The numbers are expressed in a form where you have a mantissa and an exponent, for example Number 12.3 = 0.123 * 102 123000 = 0.123 * 106 0.000123 =0.123 * 10-3 Mantissa Exponent 0.123 0.123 0.123 -3 2 6

Floating point representation of data is used to overcome the restrictions placed on the magnitude of numbers by the size of computers memory locations. Character Character data, sometimes referred to as string data, may consist of any digits, letters of the alphabet or symbols which, the internal coding system of the computer is capable of representing. Many programming
30

languages require character data to be enclosed by quotation marks when used in program instructions, for example PRINT HAPPY NEW YEAR. Boolean Boolean data items are used as status indicators and may contain only one of two possible values: True or False. DATA ITEM There are two basic methods of using data items in a program: a) Constants Data items are sometimes required to keep their values throughout the program, hence the term constant. A constant is a specific value or character string used explicitly in an operation. Consider the constant values 47.5, 1, and 13 in the example below. Multiply by 47.5 Add 1 to If = 13 Print PLEASE INPUT TODAYS DATE b) Variables and Variable names A variable is a symbolic name assigned to a data item by the programmer. At any particular time, a variable will stand for one particular data, called the value of a variable, which may change from time to time during a computing process. The value of a variable may change many times during the execution of a program. A variable is usually given a name by the programmer. Assignment The assignment operation has the form:
31

variable := expression. (Pascal) variable = expression. (C/C++/Java) The assignment operation is used to assign a name to a value. Thus it is used whenever you need to keep track of a value that is needed later. Some typical uses include: initialize a variable ( count = 0 ) increment/decrement a counter ( count = count + 1 ) accumulate values ( sum = sum + item ) capture the result of a computation ( y = 3*x + 4 ) swap two values ( t = x; x = y; y = t ) The assignment operator is not commute i.e. x = e is not the same as e = x. The variable must be declared. Variables used in the expression must be defined (have values). The type of the expression must be compatible with the type of the variable. The order in which assignments are performed is important for example, if the first and second assignments in the swap sequence were interchanged, x and y would end up assigned to the same value. The input operation and the output operation share some of the same constraints. The following section deal with the control structures (control constructs) Sequence, Selection and Iteration or Repetition. CONTROL STRUCTURES OR LOGICAL STRUCTURES The key to better algorithm design and thus to programming lies in limiting the control structure to only three constructs. These are illustrated below: The sequence structure The first type of control structures is called the sequence structure. This structure is the most elementary structure. The sequence structure is a case where the steps in an algorithm are constructed in such a way that,
32

no condition step is required. The sequence structure is the logical equivalent of a straight line. For example, suppose you are required to design an algorithm for finding the average of six numbers, and the sum of the numbers is given. The pseudocode will be as follows 1. Start
2. Get sum

3. Average = sum / 6 4. Output the average 5. Stop The corresponding flowchart will appear as follows:
START

Get Sum

Average = Sum/6

Display Average

STOP

Example 3: This is the pseudo-code required to input three numbers from the keyboard and output the total of the numbers. Use variables: sum, number1, number2, number3 of type integer 1. Accept number1, number2, number3 2. Sum = number1 + number2 + number3
33

3. Print sum 4. End Example 4: The following pseudo-code describes an algorithm which will accept two numbers from the keyboard and calculate the sum and product displaying the answer on the monitor screen. Use variables: sum, product, number1, number2 of type real
1. Display Input two numbers 2. Accept number1, number2

3. sum = number1 + number2 4. print The sum is , sum 5. product = number1 * number2 6. print The Product is , product 7. end program Decision Structure or Selection Structure The decision structure or mostly commonly known as a selection structure, is case where in the algorithm, one has to make a choice of two alternatives by making decision depending on a given condition. Selection structures are also called case selection structures when there are two or more alternatives to choose from. This structure can be illustrated in a flowchart as follows: In pseudocode form we write If condition is true Then Do task-A else Do Task-B

Conditi on?

34

TASK-A

TASK-B

In the above example, the condition is evaluated, if the condition is true Task-A is evaluated and if it is false, then Task-B is executed. We have another selection construct: If condition is true then Do Task-A In this case, if condition is false, nothing happens. Otherwise Task-A is executed. The selection requires the following: Choose alternative actions as a result of testing a logical condition Produce code to test a sequence of logical tests Making Choices There are many occasions where a program is required to take alternative actions. For example, there are occasions where we need to take action according to the user choice. All computer languages provide a means of selection. Usually it is in the form of If statement and our pseudo-code is no exception to this. We will use the if statement together with logical operators to test for true or false as shown below. If a = b print a = b The action is only taken when the test is true. The logical operators used in our pseudo-code are = is equal to > is greater than < is less than >= is greater than or equal <= is less than or equal
35

<> is not equal to Example 5: The following shows how the selection control structure is used in a program where a user chooses the options for multiplying the numbers or adding them or subtracting. Use variables: choice, of the type character ans, number1, number2, of type integer 1. Display choose one of the following
2. Display m for multiply

3. Display a for add


4. Display s for subtract

5. Accept choice 6. Display input two numbers you want to use 7. Accept number1, number2 8. If choice = m then ans = number1 * number2 9. If choice = a then ans = number1 + number2 10. 11. 12. If choice = s then ans = number1 - number2 Display ans Stop.

Compound Logical Operators There are many occasions when we need to extend the conditions that are to be tested. Often there are conditions to be linked. In everyday language we say things like If I had the time and the money I would go on holiday. The and means that both conditions must be true before we take an action. We might also say I am happy to go to the theatre or the cinema. The logical link this time is or . Conditions in if statements are linked in the same way. Conditions linked with and only result in an action when all conditions are true. For

36

example, if a >b and a > c then display a is the largest. Conditions linked with an or lead to an action when either or both are true. Example 6: The program is to input a examination mark and test it for the award of a grade. The mark is a whole number between 1 and 100. Grades are awarded according to the following criteria: >= 80 Distinction >= 60 Merit >= 40 Pass < 40 fail The pseudo-code is Use variables: mark of type integer If mark >= 80 display distinction If mark >= 60 and mark < 80 display merit If mark >= 40 and mark < 60 display pass If mark < 40 display fail An if statement on its own is often not the best way of solving problems. A more elegant set of conditions can be created by adding an else statement to the if statement. The else statement is used to deal with situations as shown in the following examples. Example 7: A person is paid at top for category 1 work otherwise pay is at normal rate. If the work is category 1 pay-rate is top Else pay-rate is normal The else statement provides a neat way of dealing with alternative condition. In pseudocode we write If work = cat1 then p-rate: = top
37

Else p-rate = normal Or If work = cat1 then p-rate: = top Else p-rate = normal The following example illustrate the use of if else statements in implementing double alternative conditions. If salary < 50000 then Tax = 0 Else If salary > 50000 AND salary < 100000 then Tax = 50000 * 0.05 Else Tax = 100000 * 0.30 The case statement Repeating the if else statements a number of times can be somewhat confusing. An alternative method provided in a number of languages is to use a selector determined by the alternative conditions that are needed. In our pseudo-code, this will be called a case statement. Example 8: The following program segment outputs a message to the monitor screen describing the insurance available according to a category input by the user. Use variables: category of type character 1. Display input category 2. Accept category 3. If category = U 3.1 Display insurance is not available
4. Else If category = A then

4.1Display insurance is double


38

5. Else If category = B then

5.1 Display insurance is normal


6. Else If category = M then

Display insurance is medically dependent 7. Else 8. Display entry invalid This can be expressed in a case statement as follows: Use variables: category of type character 1. Display input category 2. Accept category 3. DO case of category 4. CASE category = U 4.1Display insurance not available 5. CASE category = A 5.1Display insurance is double 6. CASE category = B 6.1 Display insurance is normal 7. CASE category = M 7.1 Display insurance is medically dependent 8. OTHERWISE Display entry is invalid 9. ENDCASE Instead of using the word otherwise, one can use else. Repetition or Iteration Structure A third structure causes the certain steps to be repeated. The Repetition structure can be implemented using Repeat Until Loop The While Loop
39

The For Loop Any program instruction that repeats some statement or sequence of statements a number of times is called an iteration or a loop. The commands used to create iterations or loops task are all based on logical tests. There three constructs for iterations or loops in our pseudocode. The Repeat Until loop. The syntax is REPEAT A statement or block of statements UNTIL a true condition Example 9: A program segment repeatedly asks for entry of a number in the range 1 to 100 until a valid number is entered. REPEAT DISPLAY Enter a number between 1 and 100 ACCEPT number UNTIL number < 1 OR number > 100 Example 10. A survey has been carried out to discover the most popular sport. The results will be typed into the computer for analysis. Write a program to accomplish this. REPEAT DISPLAY Type in the letter chosen or Q to finish DISPLAY A: Athletics DISPLAY S: Swimming DISPLAY F: Football DISPLAY B: Badminton DISPLAY Enter data ACCEPT letter If letter = A then
40

Athletics = athletics + 1 If letter = S then Swimming = Swimming + 1 If letter = F then Football = Football + 1 If letter = B then Badminton = Badminton + 1 UNTIL letter = Q DISLAY Athletics scored, athletics, votes DISLAY Swimming scored, swimming, votes DISLAY Football scored, football, votes DISLAY Badminton scored, Badminton, votes The WHILE loop The second type of iteration we will look at is the while iteration. This type of conditional loop tests for terminating condition at the beginning of the loop. In this case no action is performed at all if the first test causes the terminating condition to evaluate as false. The syntax is WHILE (a condition is true) fA statement or block of statements ENDWHILE Example 11: A program segment to print out each character typed at a keyboard until the character q is entered. WHILE letter <> q ACCEPT letter DISPLAY The character you typed is, letter ENDWHILE
41

Example 12: Write a program that will output the square root of any number input until the number input is zero. In some cases, a variable has to be initialised before execution of the loop as shown in the following example. Use variable: number of type real DISPLAY Type in a number or zero to stop ACCEPT number WHILE number <> 0 Square = number * number DISPLAY The square of the number is, square DISPLAY Type in a number or zero to stop ACCEPT number ENDWHILE The FOR Loop The third type of iteration, which we shall use when the number of iterations is known in advance, is a for loop. This, in its simplest form, uses an initialisation of the variable as a starting point, a stop condition depending on the value of the variable. The variable is incremented on each iteration until it reaches the required value. The pseudo-code syntax will be: FOR (starting state, stopping condition, increment) Statement(s) ENDFOR Example 13. FOR (n = 1, n = 4, n + 1) DISPLAY loop, n ENDFOR The fragment of code will produce the output Loop 1 Loop 2
42

Loop 3 Loop 4 In the example, n is usually referred as the loop variable, or counting variable, or index of the loop. The loop variable can be used in any statement of the loop. The variable should not be assigned a new value within the loop, which may change the behaviour of the loop. Example 14: Write a program to calculate the sum and average of a series of numbers. The pseudo-code solution is: Use variables: n, count of the type integer Sum, number, average of the type real 1. DISPLAY How many numbers do you want to input 2. ACCEPT count 3. SUM = 0 4. FOR (n = 1, n = count, n + 1) 4.1 DISPLAY Input the number from your list 4.2 ACCEPT number 4.3 SUM = sum + number 5. ENDFOR 6. Average = sum / count 7. DISPLAY The sum of the numbers is , sum 8. DISPLAY Average of the numbers is , average Flowcharts have been used in this section to illustrate the nature of the three control structures. These three are the basic control structures out of which all programs are built. Beyond this, flowcharts serve the programmer in two distinct ways: as problem solving tools and as tools for documenting a program.
43

Example Design an algorithm and the corresponding flowchart for finding the sum of n numbers. Pseudocode 1. Start 2. Sum = 0 3. Display Input value n 4. Input n 5. For(I = 1, n, 5) 5.1 Input a value 5.2 Sum = sum + value 6. ENDFOR 7. Output sum 8. Stop In this example, we have used I to allow us to count the numbers, which we get for the addition. We compare I with n to check whether we have exhausted the numbers or not in order to stop the computation of the sum (or to stop the iteration structure). In such a case, I is referred to as a counter. Now draw the corresponding flowchart of the algorithm above. Exercises 1. Design an algorithm and the corresponding flowchart for finding the sum of the numbers 2, 4, 6, 8, , n 2. Using flowcharts, write an algorithm to read 100 numbers and then display the sum. 3. Develop an algorithm to read two numbers then display the largest. 4. Develop an algorithm to read two numbers then display the smallest 5. Develop an algorithm to read three numbers then display the largest. 6. Develop an algorithm to read 100 numbers then display the largest.
44

45

Вам также может понравиться