Sei sulla pagina 1di 120

Allied Consultants

Concepts of
Computer Programming
Concepts of Computer Programming Allied Consultants

Preface
The purpose of this material is to lay the foundation for computer programming and problem solving.
Writing an algorithm for any software requires much thinking, careful planning, logical precision, and
attention to details. In addition, it is challenging, exciting and satisfying task associated with creativity. If
computer problem solving is thought of this way then the chances of success will be increased.

This material includes two main parts. Part One introduces the main concepts of programming
languages, different generations in the history of programming languages evolution, and problem design
techniques.

Part Two presents Algorithms in six chapters. Chapter 1 introduces the concept of problem solving, the
steps of designing an algorithm, the written algorithms and using flowcharts. Chapter 2 is dedicated to
explaining the algorithms with decisions. The algorithms that contain loops, counters, and accumulators
are discussed in Chapter 3. Chapter 4 presents the concept of structured programming and designing
modules with parameters. In the first four chapters, the examples are solved using written algorithms and
flowcharts as well. In Chapters 5 and 6 the examples are solved using the written algorithms only.
Chapter 5 explains the concept of arrays, array operations such as searching and sorting, and a brief idea
about performance analysis. Although the concept of recursion is not a part of the course syllabus, it is
introduced in Chapter 6 as a problem solving technique because of its importance.

The instructor of the course is required to provide the students with additional examples. The students are
required to try solving the exercises at the end of each chapter.

A
Concepts of Computer Programming Allied Consultants

Table of Contents

PART I 1
1 PROGRAMMING IN PERSPECTIVE 2
1.1 WHAT IS COMPUTER PROGRAMMING‫؟‬ 2
1.2 WHAT ARE THE QUALITIES OF A WELL-DESIGNED PROGRAM? 2
1.3 COMPUTER PROGRAMS 2
1.4 STRUCTURED PROGRAM DESIGN: DIVIDE AND CONQUER 3
1.5 GOALS OF STRUCTURED PROGRAMMING : 4

2 GENERATIONS OF PROGRAMMING LANGUAGES 6


2.1 LOW- AND HIGH-LEVEL PROGRAMMING LANGUAGES 6
2.2 THE FIRST AND SECOND GENERATIONS: “LOW-LEVEL” 8
2.2.1 MACHINE LANGUAGE 8
2.2.2 ASSEMBLY LANGUAGE 8
2.3 THE THIRD GENERATION: “HIGH-LEVEL LANGUAGE” 10
2.4 THE FOURTH GENERATION: 4GLS 18
2.5 THE FIFTH GENERATION LANGUAGE 19
2.6 THE DIFFERENCE BETWEEN PROCEDURAL AND NONPROCEDURAL LANGUAGES 21
2.7 HOW DO YOU CHOOSE A PROGRAMMING LANGUAGE? 21

3 PROBLEM DESIGN TECHNIQUES 23


3.1 FLOWCHARTING 23
3.2 PROGRAMMING CONTROL STRUCTURE 26
3.3 PSEUDOCODE 32
3.4 CONCEPTS AND PRINCIPLES OF PROGRAMMING 34
3.5 THE PROGRAM DEVELOPMENT STEPS 34

PART II 37
.1 ALGORITHMS AND COMPUTERS 38
1.1 BASIC CONCEPTS 38
1.2 STEPS OF DESIGNING AN ALGORITHM 39
1.3 METHODS OF PRESENTING AN ALGORITHM 42
PROBLEMS 50

2 ALGORITHMS WITH DECISIONS 51


2.1 BASIC CONCEPTS 51
2.2 TESTS AND OPERATORS 51
2.3 SINGLE DECISION STEP (ONE-WAY DECISION) 52
2.4 DOUBLE DECISION STEP (TWO-WAY DECISION) 55
PROBLEMS 62

3 ALGORITHMS WITH LOOPS 63


3.1 BASIC CONCEPTS 63
3.2 ASPECTS OF A CORRECT LOOP STRUCTURE 63
PROBLEMS 75
B
Concepts of Computer Programming Allied Consultants

4 SUBPROGRAMS 76
4.1 BASIC CONCEPTS 76
4.2 WHAT IS A MODULE? 76
4.3 MODULE STRUCTURE 80
4.4 MODULE CALL 81
PROBLEMS 85

5 ARRAYS (SUBSCRIPTED VARIABLES) 86


5.1 BASIC CONCEPTS 86
5.2 WHAT IS AN ARRAY? 87
5.3 ARRAY OPERATIONS 91
PROBLEMS 103

6 RECURSION 104
6.1 HOW MODULES WORK TOGETHER 104
6.2 RECURSIVE PROBLEMS 105
6.3 RECURSIVE MODULES 106
PROBLEMS 110

APPENDIX A 111
DIGITAL NUMBER SYSTEMS 112

C
Concepts of Computer Programming Allied Consultants

PART I

1
Concepts of Computer Programming Allied Consultants

1 Programming In Perspective
1.1 What Is Computer Programming ?
• Computer programming involves writing instructions and giving them to the
computer so it can complete a task.
• A computer program, or software, is a set of instructions written in a
computer language and executed by a computer to perform a useful task.
• The application packages such as word processors, spreadsheets, and database
management systems are computer programs.
• A programmer is an individual who translates the tasks that you want a
computer to accomplish into a form the computer understands.

1.2 What Are The Qualities of a Well-Designed Program?


• Correct and accurate
• Easy to understand
• Easy to maintain and update
• Efficient
• Reliable
• Flexible

1.3 Computer Programs


• A single program addresses a particular problem.
• When you write a program, you are solving a problem.
• To solve a problem you must use your power of logic and develop an
algorithm, or procedure, for solving the problem.
• The algorithm is the finite set of step-by-step instructions that convert the
input into the desired output, that is, solve the problem.

2
Concepts of Computer Programming Allied Consultants

1.4 Structured Program Design: Divide and Conquer


• Given a task, programmers were left on their own to create a solution any
way they could. This was called the free-form method of software
development.
• Three major problems arose from this free-form method:
1. Long development time.
2. High maintenance cost.
3. Low-quality software.
• Structured programming stresses the systematic design and management of
the program development process.
• Example: Figure 1 illustrates a common programming problem:
The printing of weekly payroll checks for hourly and commission employees.
In the figure a structure chart is used to break the programming problem into a
hierarchy of tasks. The most effective programs are designed to be written in
modules, or independent tasks.
It is much easier to address a complex programming problem in small, more
manageable modules than as one big task by using the principles of structured
programming.
Weekly
Payroll check
Program

Input data Compute Compute Output


Gross Earnings Net Pay (update database
and print checks)

Read record End-of-file Hourly Commission Update Print


from check and master file payroll checks
Employee Database finish

Figure 1 Program Structure Chart


3
Concepts of Computer Programming Allied Consultants

• In structured programming, the logic of the program is addressed


hierarchically in logical modules.
• BY dividing the program into modules, the structured approach to
programming reduces the complexity of the programming task.

1.5 Goals of structured programming :


1. Decrease program development time by increasing programmer
productivity and reducing the time needed to test and debug a program.
2. Decrease program maintenance costs by reducing errors and making
program code easier to understand.
3. Improve the quality of software by providing programs with fewer
errors.

• Structured programming accomplishes these goals by incorporating the


following three concepts:
1. Top-down design and use of modules.
2. Use of limited control structures.
3. Management control.

• Top-down design starts with the major functions involved in a


problem and divides them into sub functions until the problem has
been divided as much as possible.
• Each unit is small enough to be programmed by an individual programmer
in the required time frame. This forces an examination of all aspects of a
problem on one level before considering the next level.
• A programmer is left with small groups, or modules, of processing
instructions, which are easy to understand and code.
• A program consists of a main logic module that controls the execution of
the other modules in the program.
4
Concepts of Computer Programming Allied Consultants

• Working from the top down avoids solutions that deal with only part of a
problem.
• A program that uses a main logic module to control smaller modules is
easier to read, test, and maintain.
• In structured programming, modules ensure these qualities by:
♦ Having only one entrance and one exit
♦ Performing only one program function
♦ Returning control to the module from which it was received

5
Concepts of Computer Programming Allied Consultants

2 Generations of
Programming Languages

2.1 Low- and High-Level Programming Languages


• A programming language is a set of written symbols that tells the computer
hardware how to perform specified operations.
• Programming languages fall into two fundamental categories:
1. Low-level language
2. High-level language
• Low-level languages are machine-dependent; that is, they designed to be run on a
particular computer.
• High-level languages are machine-independent and can be run on a variety of
computers.
• The hierarchy of programming languages in Figure 2 summarizes the various types
of programming languages.
• The higher the level of the language, the easier it is to understand and use.
• For example, in a fourth-generation language you need only instruct the computer
system what to do, not necessarily how to do it.
• In the first three generations of languages, programmer has to tell the computer what
to do and how to do it.
• Languages after the fourth generation are referred to as very high-level languages.

6
Concepts of Computer Programming Allied Consultants

Natural

Very
high-level
languages

Application generators

Fourth-generation language

Fourth
Production-oriented User-oriented
generation

Object-oriented

High-level
languages

Problem-oriented
Third

generation

Procedure-oriented

Multipurpose
Business Scientific
BASIC (65) C (72)
COBOL (59) FORTRAN (55)
Pascal (68)
RPG (64) APL (68)
PL/1 (64) Ada (80)

More sophistication in
Second Assembler programmer/computer
interaction
generation Low-level
languages

First
Machine
generation

Figure 2 The Hierarchy of Programming Languages


7
Concepts of Computer Programming Allied Consultants

2.2 The First and Second Generations: “Low-Level”

2.2.1 Machine Language


• Machine language is a binary code made up of 1s and 0s, the only programming
language that a computer can understand.
• There is no universal machine language. The arrangement of 1s and 0s to represent
instructions, data, and memory locations differs among computers because of
different hardware designs.
• The advantage of machine language:
1) Fast execution speeds
2) Efficient use of main memory
• The disadvantage of machine language:
1) Usually limited to one machine
2) Time-consuming
3) Difficult to read and understanding binary code
4) Difficult to find and debug error
5) Requires detailed knowledge of how computers work, since every detail of an
operation must be specified.

See Appendix A for Digital Number Systems.

2.2.2 Assembly Language


• Assembly language is classified as a low-level language because detailed
knowledge of hardware specifics is still required.
• Assembly language uses mnemonics in place of 1s and 0s to represent instructions.
• A mnemonic is an alphabetical abbreviation used as a memory aid.
For example, instead of using a combination of 1s and 0s to represent an addition
operation, a programmer might use the mnemonic “ADD”.

8
Concepts of Computer Programming Allied Consultants

• Assembly language is the set of rules for the programmer to obey in writing
symbolic language programs.
• Assembly language program is a source program written according to the rules of an
assembly language.
• Before a computer can use an assembly language, it must translate the assembly
language into a machine language. The computer makes this conversion with a
language-translator program called an assembler.
• An assembler is used to translate assembly language code into machine language.
• The advantage of programming in assembly language instead of machine code:
1) Assembly language is easier to learn.
2) Assembly language is faster to write.
3) Assembly language is less error prone.
For example,
STR A → 011 010 000 111
{In machine code}
ADD A → 001 010 000 111
While STR and ADD are quite different in assembly language, in the binary
machine code, there is only a difference in one bit between two instructions.
4) An assembly language program is more easily documented.
• The advantage of programming in assembly language:
1) It is useful for writing, e.g., operating systems, games programs, where a fast and
efficient use of the CPU is needed.
2) It may be used for security reasons. Fewer people understand it; therefore fewer
people can copy and amend it.
3) Mnemonics and symbols make it easier to use than machine code.
4) Symbolic addresses can easily be changed or moved around without upsetting the
rest of the program.
• The disadvantage of programming in assembly language:
1) Tends to be “machine-oriented” and requires thorough knowledge of computer
9
Concepts of Computer Programming Allied Consultants

hardware.
2) Quite hard to learn and slow to write.

2.3 The Third Generation: “High-Level Language”


• The limitations of the low-level language, machine code and assembly, led to the
development of high-level language.
• A high level language contains instructions that
1) Closely resemble human language and mathematical notation.
2) Do not require the programmer to have detailed knowledge about the internal
operations of a computer.
3) High-level languages are much easier to learn and use than either machine or
assembly languages.
4) Typically, less time and effort are required for high-level programming because
errors are easier to avoid and correct.
• Further contrasts between high-and low-level programming languages are shown in
Table 1.
Criterion High-level Low-level
Programmer training required for:
i) Common algorithms Yes Yes
ii) Language rules Less More
iii) Hardware functions No Yes
Machine independence Yes No
Ease of documentation Yes No
Development time Shorter Longer
Execution time Longer Shorter
resources Computer required for translation
(time and memory size) More Less
Table 1 Further Contrasts Between High-and Low-level
Programming Languages

10
Concepts of Computer Programming Allied Consultants

• A high-level language must also be translated into a machine language before a


computer can use it.
• A translator is a program that converts a source program into some other form such
as object code or machine code.
• The source program is the form of the program as the programmer writes it. It must
be translated before it can be executed.
• The object code is an intermediate form between the source code and machine code.
It must be linked before it can be executed.
• The binary machine code program is a sequence of binary instructions that is
executable by a computer.
• The linker converts the object code into machine code.
• Types of language-translator programs are
1) Assemblers
2) Compilers
3) Interpreter
• A compiler translates a whole program written in a human-readable high-level
programming language, called the source code, into object code all at one time
before the program is executed.
1) The object code can be executed anytime thereafter.
2) The source code remains intact after the conversion and can be updated and
changed as required and then recompiled into object code.
• An interpreter translates a program into machine language one line at a time,
executing each line after it is translated.
♦ With most interpreters, the machine-readable form is not stored in main memory or
on a secondary storage medium; therefore, the program must be interpreted each
time it is executed.

11
Concepts of Computer Programming Allied Consultants

• A separate compiler (or an interpreter) is required for each programming language


intended for use on a particular computer system.
• The differences between compilers and interpreters are shown in Table 2.

Compilers Interpreters
1) Output is object program 1) Output is executed result
2) Execution time is faster 2) Execution time is slower
3) Development time is generally 3) Development time is generally faster
slower
4) Flexible; may be interfaced with 4) Inflexible; may not usually be
other languages interfaced
5) Programs may be saved in source 5) Programs may be saved in source
or object form. form only
Table 2 A Comparison of Compilers and Interpreters
• The Third-generation languages (3GLs) fall into three categories:
1) Procedure-oriented languages,
2) Problem-oriented languages, and
3) Object-oriented languages.

• Procedure-Oriented Languages
1) Programmers code the instructions in the sequence in which they must be
executed to solve the problem.
2) They are generally classifieds as:
Business (COBOL and RPG)
Scientific (FORTRAN and APL
Multipurpose (C, BASIC, Pascal, PL/I, and Ada).
3) Other third-generation languages include LISP, LOGO, FORTH, Prolog, and
Modula-2.
1- Business Languages
12
Concepts of Computer Programming Allied Consultants

Business-oriented 3GLs are designed to be effective tools for developing


business information systems.

2- Scientific Languages
Theses algebraic formula-type languages are specifically designed to meet typical
scientific processing requirements, such as matrix manipulation, precision
calculations, iterative processing, the expression and resolution of mathematical
equations.
3- Multipurpose Languages
Multipurpose languages are equally effective for both business and scientific
applications.

C
The C programming language, developed at Bell Laboratories in 1972,
incorporates many advantages of both low-level and high-level languages.
Like assembly language, C gives programmers extensive control over
computer hardware, but because C uses English-like statements, which are
easy to read, it is often classified as a high-level language.
C also incorporates sophisticated control and data structures, which make
it a powerful but concise language.
C is relatively machine-independent: A C program written for one type of
computer can be run on another type with little or no modification.
Figure 15 illustrates a C program that computes gross pay for hourly
wage earners.

BASIC
BASIC (Beginner’s All-Purpose Symbolic Instruction Code) was
developed at Dartmouth College in 1965 to provide students with an easy-
to-learn, interactive language on a time-sharing computer system.
13
Concepts of Computer Programming Allied Consultants

Because it is easy to learn and use, BASIC has become the most popular
language for microcomputers, and it is available for many microcomputers
in use today.
There are variations on BASIC, such as Microsoft’s QuickBasic and
Visual Basic.
QuickBasic provides a convenient user interface that helps to simplify
and expedite the development process.
Visual Basic enables programmers to create programs within the context
of the Windows GUI.
Visual Basic is used to create simple Windows-based applications.
Pascal
Pascal was developed in 1968.
Pascal is suited to both scientific and file processing applications.
It was originally designed to teach the concepts of structured
programming and top-down design to students.
Figure 17 illustrates a Pascal program that computes gross pay for hourly
wage earners.
• Other Procedure-Oriented Languages
LISP
A list-processing language (List Processing, 1959) is a language that
processes symbol sequences (lists) and strings of text rather than numbers.
It is a programming language designed to handle data strings more
efficiently than other languages.
LISP is used for artificial intelligence applications.
Prolog
Prolog (Programming in Logic, 1972) is another language for symbol
processing.
It can manipulate relationships between facts.
14
Concepts of Computer Programming Allied Consultants

Prolog is used for artificial intelligence applications such as expert


systems.
Logo
Logo (1967) is an interactive education-oriented language designed to
teach inexperienced users logic and programming techniques.
It includes list-processing capabilities.
Logo employs a triangular object called a “turtle” so users can draw,
animate, and color images very simply.

FORTH
FORTH (1971) is used for device control applications, arcade games, and
robotics.

Modula-2
Modula-2 (1981) enables self-contained modules to be combined in a
program.

• Problem-Oriented Languages
1) A problem-oriented language is designed to address a particular application
area or to solve a particular set of problems.
2) Problem-oriented languages do not require the programming detail of procedure-
oriented ones.
3) The emphasis of problem-oriented languages is more on input and the desired
output than on the procedures or mathematics involved.
4) Problem-oriented languages have been designed for scores of applications:
Simulation (for example, GPAA, SLAM);
Programming machine tools (ATP); and
Analysis of stress points in building and bridges (COGO).

15
Concepts of Computer Programming Allied Consultants

• Object-Oriented Languages
There are two main parts of a program:
Instructions
Data
A traditional programming language treats the data and instructions as separate
entities.
A programmer applies programming instructions to data.
In procedure-oriented languages, the emphasis is on what is done (the action).
In object-oriented languages, the emphasis is on the object of the action, thus
the object orientation.
An object-oriented programming language (OOPL) treats a program as a
series of objects and messages.
An object is a combination of data and instructions that works on the data and is
stored together as a reusable unit.
Messages are instructions sent between objects.
Basically, what an object-oriented language does is allow a programmer to build
program with pre-assembled chunks of code instead of individual pieces.
It eliminates the need for the programmer to start from scratch every time a new
program is coded.
To qualify as an OOPL a language must incorporate the concepts of
encapsulation, inheritance, and polymorphism.
The combination of data and instructions into a reusable structure is called
encapsulation, one of the basic principles of an OOPL.
Encapsulation can be thought of as a prefabricated component of a program.
For example, building a house
Using a traditional programming approach you would buy wood for the
window frame, paint, glass, putty, appropriate tools and construct and install
the window yourself.

16
Concepts of Computer Programming Allied Consultants

Using an object-oriented programming approach you buy a prefabricated


window and pop it in.
The prefabricated window is encapsulated because it is a single entity and not a
collection of individual materials.
One of the most powerful concepts of an OOPL is inheritance, the ability of the
programming language itself to define a new object that has all the attributes of an
existing object.
To define an object that is similar to an existing object all the programmer needs
to do is inherit the existing object and write the code that describes how the new
object is different from the existing one.
This capability increases code sharing and eliminates the need to write repetitive
code.
The third concept of an OOPL is polymorphism, the ability of an object to
respond to a message in many ways.
For example, you have a circle object and a square object.
Each object has the same characteristic of drawing.
When a drawing message is sent to the circle object it draws a circle but when the
same drawing message is sent to the square object it draws a square.
Thus each object has the same characteristic (drawing) but the characteristic is
implemented differently.
Advantages of object-oriented programming languages:
Code reuse rather than reinvention and adaptable code.
Speed the development and maintenance of applications and reduce costs.
Generic functions can be developed to allow easy assembly of applications
from prefabricated parts.
Increased programmer productivity and clarity of logic.
The hierarchical structure of OOP makes programs easier to design and
understand.

17
Concepts of Computer Programming Allied Consultants

Smalltalk, C++, and Java are examples of object-oriented programming


languages.

2.4 The Fourth Generation: 4GLs


• A fourth-generation language is one of a variety of programming languages that
require much less effort creating programs than high-level languages.
• In fourth-generation languages, the programmer need only specify what to do, not
how to do it.
• In procedure-oriented languages, the programmer specifies what to do and how to
do it.
• The objectives of fourth-generation languages include
Increasing the speed of developing programs,
Minimizing end user effort to obtain information from a computer,
Decreasing the skill level required of users (they can concentrate on an application
rather than the coding and solve their own problems without a professional
programmer), and
Minimizing maintenance by reducing errors and making programs easy to change.
• The features of 4GLs include
English-like instructions,
Limited mathematical manipulation of data,
Automatic report formatting,
Sequencing (sorting), and
Record selection by criteria.
• There are two types of 4GLs.
1) Production-oriented 4GLs.
This type is designed for computer professionals to create information systems.
2) User-oriented 4GLs.
This type is designed for end users.

18
Concepts of Computer Programming Allied Consultants

Users write 4GL programs to query (extract information from) a database and
to create personal or departmental information systems.
• The fourth-generation languages are usually used in conjunction with a database and
include database query languages, report generators, and application
generators.
• A database query language permits the user to formulate inquiries that relate to
records from one or more files.
The appropriate records are printed or displayed in a suitable format.
• A report generator permits data from a database to be extracted and formatted into
reports.
Substantial arithmetic and logic operations can be performed on data before they
are displayed or printed.
• An application generator allows data entry so a user can specify how to update a
database, what calculations or logic operations to perform, and what output to create.
A user can build an entire application.
When using application generators to develop information systems, programmers
specify information processing tasks to be performed by engaging in an interactive
dialogue with the system.
Application generators interpret the programmer-supplied information and
actually generate program code.

2.5 The Fifth Generation Language


• Many individuals consider natural languages to be fifth-generation languages.
• Natural languages are similar to query languages, but the user or programmer does
not need to learn and use a specific vocabulary, grammar, or syntax.
• A natural language closely resembles normal human speech (English).
• For example, if a user enters the command “Get me sales figures for January 1999,”

19
Concepts of Computer Programming Allied Consultants

a computer that understands natural language interprets this and supplies the desired
information.
• Because of the complexity of interpreting a command entered in human speech
format, natural languages require very powerful hardware and sophisticated
software.
• The natural language software parses a user inquiry into a parse tree that is
translated into applications commands through a semantic analysis.

20
Concepts of Computer Programming Allied Consultants

2.6 The Difference between Procedural and Nonprocedural


Languages

• Programming languages are classifieds into two different types: procedural and
nonprocedural.

• Procedural languages specify how something is accomplished.


Common procedural languages include BASIC, Pascal, C, Ada, COBOL, and
FORTRAN.
• Nonprocedural languages specify what is accomplished without going into the
details of how.
Database query languages and report generators are examples of nonprocedural
languages.
• The difference between procedural and nonprocedural languages is analogous to
giving directions to a taxi driver.
With a procedural language, the directions would be specified as: “Drive 600
yards forward. Turn right. Drive 350 yards forward. Turn left. Drive 500 yards
forward. Stop.”
With a nonprocedural language, you simply tell the driver what you want:
“Take me to the Hilton Hotel.”

2.7 How Do you Choose A Programming Language?


• Consider these factors before selecting one language for programming use.
1. What is the nature of the problem?
Is the programming language designed for this type of problem?
For example, COBOL is suited for business data processing, but it is not suited

21
Concepts of Computer Programming Allied Consultants

for robotics because it doesn’t have the vocabulary or features to control tasks
such as robot arm movements.

2. What is the speed at which the program needs to execute?


If the program will be used frequently and requires efficient execution, a language
such as an assembly language or C may be necessary to reduce execution time.

3. What is the expertise of the programming staff?


Do the programmers already know the language under consideration?
If not, can they learn it in the required time period, and is the additional cost for
training justifiable?

4. What is the portability of the language?


Will the program have to run on more than one type of computer?
Machine and assembly languages are machine-specific and require extensive
changes or complete rewrites for new hardware.
High-level languages are more portable, and can usually be run on different
computers with few if any changes.

5. What is the amount of program maintenance expected?


Will the program be subjected to periodic updates and revisions?
A structured high-level language may be the best choice.

6. Does your organization require the use of a particular programming


language?
This may be the case to ensure that current and future programs work together as
well as for simplification of program maintenance.

22
Concepts of Computer Programming Allied Consultants

3 Problem Design Techniques


Two popular techniques, flowcharting and Pseudocode, are commonly used to represent
systems and programming logic.

3.1 Flowcharting
• Flowcharts illustrate data, information, and work flow by the interconnection of
specialized symbols with flow lines.
• A program flowchart is the graphical representation of the logic operation sequence.
• The more commonly used flowchart symbols are shown in Figure 3.
• A flowchart is used to:
♦ Clarify the program logic
♦ Identify alternate processing methods available
♦ Serve as a guide for program coding
♦ Serve as documentation

• Figure 4 is an example of a program flowchart constructed for a program that checks a


client’s payment record.
• The program flowchart of Figure 4 portrays the logic for the structure chart of
Figure 1.

The Driver Module

• In, structured programming, each program has a driver module, or a main


program, that calls subroutines as they are needed.
• The driver module (see Figure 4) is a loop that “calls” each of the subroutines, as
needed for the processing of each employee.

23
Concepts of Computer Programming Allied Consultants

Shape Use Example

Computer Specialized I/O


Compute
process net pay Workstation

Call Printer
Predefined compute (document or
earnings report)
process routine

Read a
On-line storage
record
Input/output

Decision Salary Commission


code
Hourly

Terminal point
(end or begin Input Data

procedure)

Connector A A

Log
Manual number
of last
process check

Done for each


Hourly and
Comment Commission

Annotation Employee

Flow lines See Figure 4

Figure 3 Flowchart Symbols

24
Concepts of Computer Programming Allied Consultants

Start

Read
overdue

Yes End
Of
File?

No

Is bill more
Yes than 30 days
overdue?

Calculate
Late payment No
fees

Update
Client billing Print
file reminder

Print new
bill
A

Stop

Figure 4 A Program Flowchart

25
Concepts of Computer Programming Allied Consultants

3.2 Programming Control Structure


• In early programs, unconditional branch (jumps from one portion of the program to
another) was used.
• Programs designed with several of these unconditional branches were confusing and
difficult to follow, thereby earning them name “spaghetti code.”
• Part of the first step toward structured programming methodology was the
avoidance of unconditional branching.
• Control structure determines the order of execution of program statement.
• Program logic can be conceptualized in three basic Control structures:
3) Sequence
4) Selection
5) Repetition (looping)
• A sequence control structure executes statements one after another in a linear
fashion (Figure 5).

Instruction 1

Instruction 2

Instruction 3

Figure 5 A Sequence Control Structure

26
Concepts of Computer Programming Allied Consultants

6) Example 1:
Prepare an algorithm for Fahrenheit to Celsius temperature conversion.

Input F
Input F

Subtract 32 from F
F <----- F - 32
Multiply F by 5 / 9

Output C

C <----- F * 5 / 9

Output C

7) Example 2:
Prepare an algorithm for simplified payroll problem. The hourly pay rate R,
number of hours worked H, and total deductions D for one employee are provided.
The gross pay G and take home pay P are to be calculated and a check printed.

Input
Input R, H, D R, H, D

G = R * H
G <----- R * H
P = G - D

Print Check
P <---- G - D

Print Check

27
Concepts of Computer Programming Allied Consultants

• The selection control structure depicts the logic for selecting the appropriate
sequence of statements. The selection depends on the result of the decision criterion
(Figure 6).

False True False True


IF IF
condition condition

Instruction(s) Instruction(s) Instruction(s)

IF condition, THEN instructions(s) (1 Option) IF condition, THEN instruction(s),


ELSE instruction(s) (2 Optrions)

condition

CASE 1 CASE 2 CASE 3 CASE 4


Instruction(s) Instruction(s) Instruction(s) Instruction(s)

CASE condition: CASE 1, CASE 2, CASE 3, CASE 4 (4 Options)

Figure 6 Selection Control Structures

28
Concepts of Computer Programming Allied Consultants

8) Example 3:
In payroll Example 2, suppose it is possible for gross pay to be less than
deductions. How should the algorithm shown in Example 2 be modified?

Input
Input R, H, G R, H, D

G=R*H
G <----- R * H
P=G-D

IF P is Positive,
P <----- G - D
then print a check

N T
P>0

Print
Check

• A repetition control structure executes an instruction(s) more than once without


having it recoded.
♦ There are three basic variations of the loop structure:

1) DO FOR loop:

It uses an index variable to control the loop.


The loop will usually have the form
Repeat for K = M to N by I
[Module]
[End of loop.]
K is called the index variable (control variable or loop counter).
M is called the initial value.
N is called the end value (test value or final value).

29
Concepts of Computer Programming Allied Consultants

I counter.
The logic of this structure is pictured in Figure 7.

2) DO WHILE loop:

It uses a condition to control the loop.


The decision criterion (condition) is placed before the statements (instructions)
to be repeated.
The loop will usually have the form
Repeat while condition
[Module]
[End of loop.]
In this structure, statements may not be executed at all.
The logic of this structure is pictured in Figure 6.8.

3) DO UNTIL loop:

It uses a condition to control the loop.


The decision criterion (condition) is placed at the end of statements.
The loop will usually have the form
[Module]
Repeat until condition
[End of loop.]
In this structure, statements are always executed at least once.
The logic of this structure is pictured in Figure 6.9.

30
Concepts of Computer Programming Allied Consultants

k <----- M

Yes
K>N

No K <----- M Yes
K>N
K <----- K + 1
Module
(body of loop)
No

Module
(body of loop)
k <----- k + I

Figure 7 A DO FOR Control Structure

IModule Module
(body of loop) (body of loop)

True False
Condition Condition

True
False

Figure 6.9 A DO UNTIL


Figure 6.8 A DO WHILE
Control Structure
Control Structure

31
Concepts of Computer Programming Allied Consultants

9) Example 4:
An array DATA of numerical values is in memory. We want to find the location
LOC and the value MAX of the largest element of DATA.

Start

k <----- 1
LOC <----- 1
MAX <----- DATA[1]

K <----- K + 1

Yes print
K>N
LOC, MAX

No
Stop
No
MAX < DATA[K]

Yes
LOC <----- K
MAX <----- DATA[K]

3.3 Pseudocode

• Pseudocode represents program logic in program like statements written in plain


English.

• Pseudocode was designed as an alternative to flowcharts.

• Because there are no syntax guidelines for formulating Pseudocode statements,


Pseudocode can be easily converted to program code.

• Figure 10 is an example of Pseudocode as it might be written for the problem in


32
Concepts of Computer Programming Allied Consultants

Figure 4.

Begin
Read overdue billing file.
DO WHILE not end of file
If bill more than 30 days overdue
THEN
Calculate late payment fees.
Update billing file.
Print new bill.
ELSE
Print payment reminder.
END-if
Read overdue billing file.
End

Figure 10 Pseudocodes For the Program in Figure 4

33
Concepts of Computer Programming Allied Consultants

3.4 Concepts and Principles of Programming


• A computer program is made up of a sequence of instructions, or statements.
• There are five classifications of instructions.
1. Input/Output
2. Computation
3. Control (Decision and/or Branch)
4. Data transfer and assignment
5. Format

• Input/output instructions direct the computer to “read from” or “write to” a peripheral
device.

• Computation instructions perform arithmetic operations.

• Control instructions can alter the sequence of a program’s execution.

• Data transfer and assignment instructions permit data to be transferred internally. A


variable name in a program refers to the contents of a particular RAM location.

• Format instructions describe how data are to be entered to or output from RAM.

3.5 The Program Development Steps


• Writing a program is a project in itself and follows these seven steps:
1. Describe the problem.
2. Analyze the problem.
3. Design the general logic of the program.
4. Design the detailed logic of the program.
5. Code the program.
6. Compile, test and debug the program.

34
Concepts of Computer Programming Allied Consultants

7. Document the program.


• Step1. Describe the problem
Identify exactly what needs to be done.
• Step2. Analyze the problem
Break the problem into its basic components for analysis.
Remember to “divide and conquer.”
A good starting is to analyze the output, input, processing, and file-interaction
components.
• Step3. Design the general logic of the program
The general design of the program is oriented primarily to the major processing
activities and the relationships between these activities (see Figures 1 and 4).
By first completing a general program design, investigate alternative design
approaches, then choosing the best one.
• Step4. Design the detailed logic of the program
In the detailed design you will produce a graphic representation of the program
logic that includes all processing activities and their relationships, calculations, data
manipulations, logic operations, and all input/output.
• Step5. Code the program
Coding a program involves actually writing the instructions in a programming
language that tells the computer how to operate.
• Step6. Compile, test and debug the program
A language translator program converts the program code into machine language.
The program should be tested to ensure that it is correct and contains no errors.
Three types of program errors that may be encountered during testing are:
∗ Syntax errors
∗ Run-time errors
∗ Logic errors
The syntax of a programming language is the set of rules and conventions to be

35
Concepts of Computer Programming Allied Consultants

followed when writing a program; these rules are similar to the grammatical rules of
the English language.
When these rules are violated, a syntax error occurs.
All syntax errors must be found and corrected before a program will execute.
If invalid data were entered, a run-time error occurs and execution of the program
is stopped.
For example, if the programs expect numerical data and alphabetical data were
entered instead, a poorly designed program would “crash,” i.e., stop executing.
A properly written program identifies the problem, prompts the user with an error
message, and permits the data to be reentered.
A logic error will not stop the execution of the program; however, the results will
not be accurate.
For example, the problem is to calculate the number of apples by adding 2 apples
plus 4 apples. The formula should be 2 + 4 = 6. But what if the wrong symbol is
entered, for example, 2 x 4? The answer “8” is correct for the formula as entered, but
not the problem to be solved.
The process of finding any type of error and correcting it is called debugging.
• Step7. Document the program
Documentation is the text or graphics that provides specific instructions about, or
records the purpose or function of, a particular step or instruction in a program.
Each step throughout the programming process should be documented.
At a minimum, the documentation package for each program should include a
program description, a structure chart, a flowchart, a program listing (with internal
comments), and an interactive session (I/O when the program is run).
There are two reasons to document the program development process.
Documentation leaves a clear record for someone else to understand what was
done.
Documenting the steps as they are developed forces a reexamination.

36
Concepts of Computer Programming Allied Consultants

PART II

37
Concepts of Computer Programming Allied Consultants

1. Algorithms and Computers


1.1 Basic Concepts
Digital computers have become a very powerful tool for problem solving nowadays.
The computer is able to carry out arithmetical and logical operations at a very high
speed. But the computer cannot think, so it depends on the human mind to supply it
with the necessary instructions to solve the problem. The set of steps required to
solve a problem is called an algorithm. Problem solving means designing a set of
steps, which when applied to some available data (Input Data) produce a specific
solution (Output) as shown in Fig 1.1. Any algorithm should be converted to a
program using a programming language before being executed by computer.

Input Data Output Data

Algorithm
(Program)

Fig 1.1

The program and the data are stored in the computer memory .The memory may be
thought of as a large group of boxes, each can be given a name by which we can
refer to its contents. The memory locations (names) that are reserved for holding
input data and output data are called input variables and output variables
respectively. So, from now on we are going to call the input data the input variables
and the output data the output variables.

38
Concepts of Computer Programming Allied Consultants

1.2 Steps of Designing an Algorithm

1.2.1 Problem Definition


Problem Definition is the first step we start with when we wish to solve a problem. It
is defining the output variables and the input variables clearly and precisely.
Output variables are the variables that hold the solution of the problem.
Input Variables are the variables whose values are available either from the
problem phrasing or by giving them their values at the execution time (reading
them). A variable is read if its value changes from one execution of the algorithm to
another.

1.2.2 Developing the Algorithm


When a programmer is going to write an algorithm he/she has to represent the
familiar concepts of the problem such as salary, student grades, phone numbers, etc.
as variables of particular names and types.
The variable type identifies the legal operations to be performed using that variable.
The variables are either numeric or alphanumeric:
Numeric variables hold numbers; they can be added using (+), subtracted using
(-), multiplied using (* or X), divided using (/ or ÷), read, printed (written), and
compared.
Alphanumeric variables hold characters; they can be read, printed and
compared.
The outcome of this phase is what is called Data Table.
The data table is a declaration for all the variables to be used in the algorithm.
The variable is declared by specifying its category, name, and role.

Categories of Variables
a) Input Variables
b) Output Variables
c) Input/Output Variables
39
Concepts of Computer Programming Allied Consultants

d) Program Variables

1. Input variables and Output variables have been discussed earlier in this chapter.
2. Input/Output variables are the variables that hold values to the program as input
and hold different values at the end of the program as Output.
3. Program variables are the variables used by the programmer to help him/her in
solving the problem but they are neither input nor output.
4. The role of a variable is a brief description of what it is used for in the algorithm.

After developing the data table of the algorithm, the programmer has to resolve
the solution of the problem into steps keeping the following in mind:
1- The steps are executed in order.
2- The algorithm does what we tell it to do not what we want it to do.
3- Each variable should be declared in the data table.
4- Each step should perform only one operation.
5- Each variable should be given a value before being printed or used in
calculations.
6- The variable is given its value by a 'Read' step if its value changes from one
execution to another.
7- The variable is given its value by a replacement (assignment) step if its initial
value or method of calculation is known from the phrasing of the problem or does
not change from one execution to another.

Examples of Replacement Steps


Move 3 to X (The variable X has the value 3)
Store 3 * X in Y (The variable Y has the value of 3 * X)
Z=X+Y (The variable Z has the value of X + Y)
A→Z+3 (The variable A has the value- of Z + 3)

40
Concepts of Computer Programming Allied Consultants

8- All the program variables are given values by replacement.


9- The alphanumeric values (not variables) are enclosed between quotes (address =
'2 El Falaky Street'), where " address " is an alphanumeric variable.
10- The algorithm should have one and only one start point, and one and only one
end point.
11- The algorithm should be finite, i.e., there must be no possibility that it could
continue forever without reaching a solution.
12- Starting at the start point should lead to the end point under any condition.

1.2.3 Tracing the Algorithm


After developing the algorithm we should test its correctness by using. Different sets
of input data with a known output. If the output of the algorithm is as expected this
means that it is correct. If this is not the case, even with one set, the algorithm should
be revised.

41
Concepts of Computer Programming Allied Consultants

1.3 Methods of Presenting an Algorithm


Written a1gorithm, an algorithm may be presented as a sequence of steps with serial
numbers. These numbered steps may be written in ordinary English or any other
language (Pseudocode).

Program Flowchart, which is the graphical representation of the algorithm. The


following symbols are used to draw a program flowchart.

Example 1.1
Write an algorithm and draw a flowchart to calculate and print the average of two
numbers.

The input of this problem is two numbers; let us call them "Numl", "Num2". The
output of the problem is the average of the two numbers; let us call it "Av". But, as
we know, the average is calculated by dividing the sum of the two numbers by 2. So,
we should introduce a new variable to hold the sum of the two numbers. Let us call
the new variable "Sum". The variable "Sum" is neither an input variable nor an
output variable; but it is used to help us calculate the average; so it is categorized as
a program variable.
Data Table
Input Variables
Numl: The lst number to be used.
Num2: The 2nd number to be used.

Output Variable
Av: The average of the two numbers.
Program Variable
Sum: The sum of the two numbers
Algorithm: Written form
1-Read Numl, Num2
42
Concepts of Computer Programming Allied Consultants

2-Sum = Numl + Num2


3-Av = Sum/2
4-Write Av
5-End

Start

Read
Num1, Num2

Sum = Num1+Num2

Av = Sum/2

Print Av

End

Fig. 1.2
Flowchart of Example 1.1

43
Concepts of Computer Programming Allied Consultants

R
The read block may be drawn as → Num1, Num2

W Av
The print block may be drawn as →

Example 1.2
Write an algorithm and draw a flowchart to compute the time and cost of an auto-trip
using the following formulas
1- Time = Distance / Speed.
2- Gallons of gas used = Distance / kms per gallon.
3- Cost of the trip = gallons used X cost per gallon.
Provided that the cost per gallon is L.E. 20.

Data Table
Input Variables
Dist: Distance of the trip
Speed: Speed of the car
Kpg: Kilometers per gallon
Cpg: Cost per gallon
Output Variables
Time: Time of the trip
Cost: Cost of the trip
Program Variable
Galused: gallons of gas used.

44
Concepts of Computer Programming Allied Consultants

Algorithm: Written form


1- Read Dist, Speed
2- Time = Dist/Speed
3- Cpg = 20
4- Read Kpg
5-Galused = Dist/Kpg
6- Cost = Galused * Cpg
7- Write Time, Cost
8- End

45
Concepts of Computer Programming Allied Consultants

Start

R
Dist, Speed

Time = Dist/Speed

Cpg = 20

R
Kpg

Galused = Dist/Kpg

Cost = Galused * Cpg

W
Time, Cost

End

Fig. 1.3
Flowchart of Example 1.2
46
Concepts of Computer Programming Allied Consultants

Example 1.3

Write an algorithm and draw a flowchart to read the basic salary and
the overtime hours of an employee and compute the employee's net
salary as follows:

Net salary = Gross salary - Taxes


Gross salary = Basic salary + Payment from overtime
Taxes = Basic salary * Tax rate
Provided that the rate of overtime is L.E 5 I hour and the tax rate is
10%.

Data Table
Input Variables
Basic: Basic salary
Ovh: Overtime hours
Taxr: Tax rate
Pph: Payment per hour

Output Variables
Net: Net salary

Program Variable
Gross: Gross salary
Taxes: Taxes

Algorithm: Written form


1- Read Basic, Ovh
2- Taxr = 0.1
3- Taxes = Basic * Taxr
4- Pph = 5
5- Gross = Basic + Ovh * Pph
6- Net = Gross -Taxes
7- Write Net
8-End

47
Concepts of Computer Programming Allied Consultants

Start

R Basic, Ovh

Taxr = 0.1

Taxes = Basic * Taxr

Pph = 5

Gross = Basic + Ovh * Pph

Net = Gross - Taxes

W
Net

End

Fig. 1.4
Flowchart of Example 1.3

48
Concepts of Computer Programming Allied Consultants

Example 1.4

A System of linear equations of the form:


alx + bly = cl
a2x + b2y = c2

Can be solved using the equations:


x = (clb2 -c2bl )/(alb2 -a2bl) and y = (c2al -cla2)/(alb2- a2bl)

Draw a flowchart and write an algorithm to read a1, a2, b1, b2, c1, and
c2 and find the solutions x and y.
Start

Data Table R a1, b1, c1, a2, b2, c2


Input Variables
al: x-coefficient of the first equation
b1: y-coefficient of the first equation
cl: Free-coefficient of the first equation x = (c1b2-c2b1)/(a1b2-a2b1)
a2: x-coefficient of the second equation
b2: y-coefficient of the second equation
c2: Free-coefficient of the second equation
y = (c2a1-c1a2)/(a1b2-a2b1)
Output Variables
x, y: The solutions of the equation

Algorithm: Written form W


1- Read al, bl, cl, a2, b2, c2 x, y
2- x = (clb2 -c2bl)/ (alb2 -a2bl)
3- y = (c2al -cla2)/ (alb2- a2bl)
4- write x, y
5- End End

Fig. 1.5
Flowchart of Example 1.4

49
Concepts of Computer Programming Allied Consultants

Problems
1.1 Write an algorithm and draw a flowchart to calculate and print the sum and
average of three numbers.

1.2 Write an algorithm and draw a flowchart to read a distance in millimeters and
print it in meters, centimeters, and millimeters.

1.3 At the beginning of a journey the reading on a car's odometer is S kilometers


and the fuel tank is full. After the Journey, the reading is F kilometers and it
takes L liters to fill the tank. Write an algorithm and draw a flowchart to
calculate and print the rate of fuel consumption in Km/liter.

1.4 A farmer has a field B meters wide, L meters long. The field yields C cubic
meters grain per Fadden (I Fadden = 4000 square meters). The farmer has a number
of cylindrical grain silos, R meters in radius, H meters in height in which he stores
the harvest. Write an algorithm and draw a flowchart that calculates and prints the
number of the used silos.

1.5 A magnetic tape is L meters long, 800 bytes/cm recording density, R cm/sec
reading speed, and 25 millimeters gap between records. Write an algorithm and
draw a flowchart which outputs:

a) The amount of information that can be stored on the tape when the record size is
512 bytes.

b) The time taken to read the entire tape.

50
Concepts of Computer Programming Allied Consultants

2 Algorithms with Decisions


2.1 Basic Concepts
The algorithms of Chapter 1 have involved only a sequence of reading,
calculating, and printing steps. The algorithm started at the beginning, and the
steps were executed step by step to the end without skipping any step. An
increase in the problem solving power can be obtained if we are able to perform
some tests (data comparison) and depending on the result of such tests one part of
the algorithm or another is decided to be executed or not.

2.2 Tests and Operators


The test is a question having only one answer which is either true (T) or false
(F). We may use yes (Y) or no (N) in place of true and false respectively. In
making tests (comparisons) the following relational operators are used:

Operator Meaning
= Equal
>= Greater than or equal
<= Less than or equal
<>or ≠ Not equal
> Greater than
< Less than

The general form of a question is: datal operator data2, such as:
Salary >= 2000
Name <> 'Ahmed'

The two operands (datal and data2) should be of the same type.

A question may be also called a condition, because its answer is the


condition of executing a specific segment of the algorithm. To make a
correct decision, the following points should be kept in mind:

1- The step at which the question is going to be asked (decision step) should be
determined precisely. Do not ask the question before or after the proper step.

2- The question (condition) should be formulated correctly by selecting the exact


relational operator and the correct variables and values to be compared. All the
values to be used in the question should be given their correct values before being
used.
51
Concepts of Computer Programming Allied Consultants

3- Determine correctly and precisely, the segment (the steps) to be executed if the
condition is true, and the segment to be executed if the condition is false.

4- In written algorithms, if the segment to be executed consists of more than one


step, its beginning and its end should be marked. There is no formal method for
marking a segment, but we can use one of the following methods:

a) Enclosing the segment in a left brace (curl bracket)

3- Decision step

step # 1
→ Segment
step # n

4- The step following the decision step

b) Enclosing the segment between two braces

3- Decision step

{step # 1
step # n }

4- The step following the decision step

c) Numbering the steps in the segment as a subdivision of the decision


step.

3- Decision step

3.1 Step # 1
3.n Step # n

4- The step following the decision step

2.3 Single Decision Step (One-Way Decision)


If at a point of the algorithm we are going to make a test, and if the answer of the
test is “Y” a predetermined segment will be executed and if the answer is “N”
nothing will be done; such decision step is called a single decision step or one way
decision. A graphical representation for the single decision step is shown in Fig
2.1. In written algorithms, the single decision step takes the form:
If condition then segment
The segment that follows ‘then’ will execute only if the condition is true.
52
Concepts of Computer Programming Allied Consultants

Fig. 2.1
Flowchart of a Single Decision Step

Example 2.1
Write an algorithm and draw a flowchart that reads two numbers and print the largest.

Data Table
Input variables
A: 1st number to be used
B: 2nd number to be used

Output variables
Large: The largest of A, B

Algorithm: Written form


1- Read A, B
2- Large = A
3- If B > Large then Large = B
4- Write Large
End

53
Concepts of Computer Programming Allied Consultants

Start

Read A , B

Large = A

B > Large

N Large = B

Write Large

End

Fig. 2.2
Flowchart of Example 2.1

54
Concepts of Computer Programming Allied Consultants

2.4 Double Decision Step (Two-Way Decision)


If we make a test and according to the result we are going to select one of the two
segments to be executed if the result is “Y” and the other if the result is “N”, the
decision step is called a double decision step or a two-way decision. A graphical
representation for the double decision step is shown in fig 2.3. In written
algorithms, the double decision step takes the form:

If condition then segment1 else segment2


Segment1 will execute only if the condition is true; otherwise, segment2 will execute.

False True
IF
condition

Instruction(s) Instruction(s)

IF condition, THEN instruction(s),


ELSE instruction(s) (2 Optrions)

Fig. 2.3
Flowchart of Double Decision Step

Example 2.2

Write an algorithm and draw a flowchart to compute and print the gross salary of an
employee, given the number of hours worked and the employee’s hourly rate. Deduct a tax
amount of 7% of the gross salary if the employee’s salary exceeds 400 pounds and a tax
amount of 4% otherwise.
Data Table
Input Variables
Hours: Number of hours worked
HWR: Hourly wage rate
HTR: Higher tax rate (Initialized to 0.07)

55
Concepts of Computer Programming Allied Consultants

LTR: Lower tax rate (Initialized to 0.04)

Output Variables
Net: Employee’s net salary
Gross: Employee’s gross salary

Program Variables
Tax: Tax deductions

Algorithm: Written form


1. Read Hours, HWR
2. HTR = 0.07
3. LTR = 0.04
4. Gross = Hours * HWR
5. If Gross > 400 then tax = Gross * HTR else Tax = Gross * LTR
6. Net = Gross – Tax
7. Write Gross, Net
8. End

56
Concepts of Computer Programming Allied Consultants

Start

Read Hours,
HWR

HTR = 0.07
LTR = 0.04

Gross = Hours * HWR

N Gross > 400 ? Y

Tax = Gross * LTR Tax = Gross * HTR

Net = Gross - Tax

Write Large

End

Fig. 2.4
Flowchart of Example 2.2

57
Concepts of Computer Programming Allied Consultants

Example 2.3

Write an algorithm and draw a flowchart to read the name and score of a student
and assign a letter grade to the student according to the following grading scheme:

Score Grade Rate of appreciation


90 .. 100 A Outstanding
80 .. 89 B Very Good
70 .. 79 C Good
60 .. 69 D Pass
0 .. 59 F Fail

The algorithm should print the student's name, grade, and rate of appreciation.

Data Table
Input Variables
Sc: Student's Score
Name: Student's name

Output variables
Name: Student's Name
Grd: Student's Grade
Rate: Rate of appreciation

Algorithm: Written form


1- Read Name
2- Read Sc
3- If Sc >= 90 then
{ Grd = ‘A’
Rate = ‘Outstanding’} else
If Sc >= 80 then
{ Grd = ‘B’
Rate = ‘Very Good’} else
If Sc >= 70 then
{ Grd = ‘C’
Rate = ‘Good’ } else
If Sc >= 60 then
{Grd = ‘D’
Rate = ‘Pass’} else
{Grd = ‘F’
Rate = ‘Fail’}
4- Write Name, Grd, Rate
5- End

58
Concepts of Computer Programming Allied Consultants

Start

Read Name, SC

N SC >= 90 ? Y

Grade = 'A'
N Sc >= 80 ? Y

N Sc >= 70 ? Y Grade = 'B' Rate =


'Outstanding'

Sc >= 60 ?
N Y Grade = 'C'
Rate = 'Very Good'

Grade = 'F' Grade = 'D'


Rate = 'Good'

Rate = 'Fail' Rate = 'Pass'

Write Name,
Grade ,
Rate

End

Fig. 2.5
Flowchart of Example 2.3

59
Concepts of Computer Programming Allied Consultants

Example 2.4

Write an algorithm and draw a flowchart to compute and print the gross salary of
an employee, given the number of hours worked per week and the employee's
hourly rate. The employee is paid at the hourly rate for the first 35 hours.
Thereafter, overtime is paid at 1.5 times the hourly rate for the next 25 hours, and 2
times the hourly rate for a further 10 hours. The employee is not allowed to work
more than 70 hours per week.

Data Table
Input Variables
Hours: Number of hours worked
Rate: Hourly wage rate

Output Variable
Wage: Employee's weekly wage

Program Variable
Diff: Temporary variable

Algorithm: Written form


1- Read Hours, Rate
2- If Hours <= 35 then Wage = Hours * Rate
Else If Hours <= 60 then
{Diff= Hours -35
Wage = Rate * 35 + 1.5 * Rate * Diff}
Else {Diff = Hours -60
If Diff > 10 then Diff = 10
Wage = Rate * 35 + 1.5 * Rate * 25 + 2 * Rate * Diff}
3- Write Wage
4- End.

60
Concepts of Computer Programming Allied Consultants

Start

Read Hours,
Rate

N Hours <= 35 ? Y

Wage = Rate * Hours


N Hours <= 60 ? Y

Diff = Hours - 60 Diff = Hours - 35

Wage = Rate * 35 + 1.5 * Rate * Diff


Diff > 10 Y

Diff = 10

Wage = Rate * 35 + 1.5 * Rate * 25 + 2 * Rate * Diff

Write Wage

End

Fig. 2.6
Flowchart of Example 2.4

61
Concepts of Computer Programming Allied Consultants

Problems
2.1 Write an algorithm and draw a flowchart to solve example 1.4 taking in
consideration that division by zero is not allowed.

2.2 Write an algorithm and draw a flowchart to read three numbers and print the
largest.

2.3 Write an algorithm and draw a flowchart to read three numbers and print a
message telling whether the first number is equal to, greater than, or less than the
second number.

2.4 Write an algorithm and draw a flowchart to read a student name and three
scores. The student's average is based on his/her two best scores. Print the student's
name, scores and average as follows:

Amr Aly 100 68 77 88.5

2.5 Write an algorithm and draw a flowchart to read the three sides of a triangle
and print a message to show that whether it is a right triangle or not.

2.6 A salesman receives a commission of 10% on all sales if he has sold at least
L.E. 5000 worth of merchandise, but only 8% if his sales are below L.E. 5000.
Write an algorithm and draw a flowchart to read the amount of sales of a salesman
and print his commission.

2.7 A salesman receives a commission on the following basis:

Sales Commission
L.E. 0 to 500 2%
Over 500 to L.E. 5000 5%
Over L.E. 5000 7%

Write an algorithm, and draw a flowchart to read the amount of sales of a salesman
and print his commission.

2.8 A certain metal is graded according to the results of three tests. These tests
determine whether the metal satisfies the following specifications:

a- Carbon content is below 0.67


b- Rockwell hardness is not less than 50.
c- Tensile strength is greater than 70,000 psi.
The metal is graded 10 if it passes all three tests, 9 if it passes only tests 1 and 2. It
is graded 8 if it passes only test I, and 7 if it passes none of the tests.

Write an algorithm and draw a flowchart to read the three test parameters and
determine the grade of the metal.

62
Concepts of Computer Programming Allied Consultants

3 Algorithms with Loops


3.1 Basic Concepts
In all the algorithms that have been discussed so far each step has been executed
once. In real life problems we have to repeat one or more steps of the algorithm.
Suppose, for example, we wished to read two pairs of numbers and calculate the
sum and the average for each pair. Simply, we can write an algorithm for reading
one pair of numbers and calculating its sun and average then writing the same steps
once more. But it seems boring to use the same approach if we wished to read
hundred pairs of numbers, not just two. In general, if we wished a part of an
algorithm to be executed more than once we should use an algorithm with a loop.
Thus, loops are used when we want to repeat a segment (one or more steps) in an
algorithm any number of times.

3.2 Aspects of a Correct LOOP Structure


To ensure that a loop will be executed correctly there are some points that should
be kept in mind and specified thoroughly before constructing the loop.

3.2.1 Loop Body


Which is the step(s) to be repeated. Incorrect loop body results in repeating a
segment that should not be repeated or not repeating a segment that should be
repeated.

3.2.2 Control Variable(s)

Any loop should be finite; there must be no possibility that it could continue
forever. There must be a condition at which a loop should terminate. The
variable(s) according to which we know that the termination condition is reached
or not is (are) called the control variable(s). Three main operations should be
performed on the control variable(s) as explained below. Failing to correctly do one
or more of these operations may result in uncontrolled execution of the loop. These
operations are:

Initializing, the control variable(s) should be given initial value(s) before the loop
is entered.

Testing, the control variable(s) should be tested before / after (according to the
termination condition(s)) each execution of the loop body. Testing the control
variable(s) tells us whether the termination condition(s) is reached or not.

Updating, the control variable(s) should be updated (given new value(s)) after each
execution of the loop body (part of the loop body).

3.2.3 Termination Condition


There are three loop termination conditions that may be used individually or in
combination to terminate a loop. These conditions are:

63
Concepts of Computer Programming Allied Consultants

A specific number of loop body repetitions, this termination condition is used if


the number of the loop body executions is known in advance. In this case exiting
the loop is aided by a technique called counting. A variable, used as a counter, is
assigned an initial value before entering the loop. After each execution of the loop
body the value of the counter is increased/decreased by a constant value (step). The
counter is then tested to determine whether it has reached its final value; if this is
not the case, the loop is executed once more until the exit condition has been
reached. Then processing continues outside the loop. The following are two
examples of counted loops.

Example 3.1

Write an algorithm and draw a flowchart to read ten pairs of numbers and calculate
and print the average of each pair.

Data Table
Input Variables
XI, X2: Pair of numbers

Output Variable
Av: the average of the pair of numbers

Program Variables
Sum: The sum of the pair of numbers
C: Counter

Algorithm: Written form


1- C = 1
2- Do the following from C = 1 to 10
{ read XI, X2
Sum = XI +X2
Av = Sum/2
Write Av
Increment C by 1}
3- End

In this algorithm we noticed that in each execution of the loop body the new values
of “XI”, “X2”, “Sum”, and “Av” overwrite the old values.

The step (C = C+l) increments the old value of “C” by one and stores the result in
“C” as a new value. The variable “C” is used as a counter and a control variable in
the same time. It is initialized in step I, tested in step II and updated in step III.

64
Concepts of Computer Programming Allied Consultants

Start

C=1

C > 10 ? Y

End
Read X1, X2

sum = X1 + X2

Av = sum / 2

Write Av

C=C+1

Fig.3.1
Flowchart of Example 3.1

65
Concepts of Computer Programming Allied Consultants

Example 3.2

Develop an algorithm and draw a flowchart for a program to compute and print the
sum of the odd numbers between 1 & 999 inclusive.

To solve this example a technique called accumulating is used. A variable


(accumulator) is used to accumulate the values of the odd numbers between 1 &
999. The accumulator is initialized by zero, then each time we get an odd number
the value of this number is added to the accumulator.

Data Table
Input Variables
Firstn: The first number in the set
Lastn: The last number in the set

Output Variable
Sum: Accumulated sum of all the odd numbers

Program Variable
Odd: The current odd number

Algorithm: Written form


1- Firstn = 1
2- Lastn = 999
3- Odd = Firstn
4- Sum = 0
5- Do the following from Odd = Firstn to Lastn
{Sum = Sum + Odd
Odd = Odd + 2}
6- Write Sum
7- End

66
Concepts of Computer Programming Allied Consultants

Start

First = 1
Last = 999

Odd = Firstn

Sum = 0

Odd > Lastn ? Y

N
Write Sum

Sum = Sum +Odd

End

Odd = Odd + 2

Fig.3.2
Flowchart of Example 3.2

Computed Value, in some problems the number of loop body repetitions is not at
hand, but the loop executes until a specific value is reached. The program always
generates this value and it is considered as a part of the solution. We always rely on
this value to terminate the loop. In this case the loop in executed once, then the
control variable is tested to see whether it has reached the termination value or not.
If it is not, the loop is executed again, and so on. When using the computed value
as an exit condition, the loop is executed at least once because the control variable
is tested at the end of the loop. In general, a computed value is used an exit
condition when one or more repetitions of the loop body are expected.

67
Concepts of Computer Programming Allied Consultants

Example 3.3

At present, the annual salaries of the employees A & B are L.E 2400, L.E 3000 respectively. The
annual increments of A & B are 12 % & 10 % respectively. Write an algorithm and draw a
flowchart to calculate and print the number of years required for the salary of A to exceed the
salary of B.

In this problem we have a loop in which the annual salaries of A & B are calculated and the
number of years is counted. Each loop execution represents a year. The number of loop body
executions is unknown, but we rely on the computed values of the salaries of A & B to terminate
the loop.

Data Table
Input Variables
As: The salary of A
Bs: The salary of B
AIA: Annual increment of A's salary
AIB: Annual increment of B's salary

Output Variable
Ny: Number of years required for the salary of A to exceed the salary of B

Algorithm: Written form


1- As = 2400
2- Bs = 3000
3- AIA = 0.12
4- AIB = 0.1
5- Ny = 0
6- Do the following
{As = As * (I +AIA)
Bs = Bs * (I +AIB)
Ny = Ny + 1}
Until As > Bs
7- Write Ny
8- End

Exercise

What is the control variable of example 3.3? Where is it initialized, tested, and
updated?

68
Concepts of Computer Programming Allied Consultants

Start

As = 2400
Bs = 3000
AIA = 0.12
AIB = 0.1
Ny = 0

As = As * (1 + AIA)

Bs = Bs * (1 + AIB)

Ny = Ny +1

As > Bs Y

Write Ny

End

Fig.3.3
Flowchart of Example 3.3

Example 3.4
Draw a flowchart to calculate and print the infinite series :

X2 X3 X4
y = 1+x+ + + +…………………………
2! 3! 4!

Xi
The stopping criterion is <= 0.001, provided that x is positive.
i!
To calculate a series we should detect either the general form of the series or the
relation between each term and its predecessor or its successor. Solving the
example using the general form will be discussed in the next chapter (example 4.2).
But now let us solve the example using the other method.

69
Concepts of Computer Programming Allied Consultants

We can rewrite the series as follows:

1* ( X ) X * ( X ) X 2 * ( X ) X 3 *(X )
Y = 1+ + + + +………………………….
(1) 1 * (2) 1 * 2 * (3) 1 * 2 * 3 * (4)

Let the first term be T0 , the second term be T1 , and so on.

Let T 0 = 1 and i = 0

X
at T1 i=i+1=1 and T1 = T0 *
i

X
at T2 i=i+1=2 and T2 = T1 *
i

X
at T3 i= i+1 =3 and T3 = T2 *
i

X
at Tn i=i+1=n and Tn = Tn −1 *
i
Data Table
Input Variable
X: The variable for which the series is calculated

Output Variable
Y: The sum of calculated terms (The value of the series)

Program Variables
T: The calculated term
i: Denominator multiplier

70
Concepts of Computer Programming Allied Consultants

Start

i=0
T=1
Y=0

Read X

Y=Y+T

N T <= 0.001 ? Y

i=i+1 Write Y

End
T = T * (X / Y)

Fig.3.4
Flowchart of Example 3.4

Exercise
Write an algorithm to solve the previous example.

Sentinel Value, in some problems we have neither the number of loop body
repetitions nor a computed value to terminate the loop. In this case the loop is
controlled at the input phase. This means that we specify a specific value that when
read the loop terminates. This value is called the sentinel value.
The sentinel value is not a part of the solution, i.e., the loop terminates immediately
after reading the sentinel value. So the control variable should be tested before
entering the loop, because the sentinel value may be entered as the first input. So,
in case of using a sentinel value the loop body may or may not be executed. In
general, a sentinel value is to be used as an exit condition if zero or more
repetitions of the loop body are expected. The sentinel value should be different
from any valid input value.

71
Concepts of Computer Programming Allied Consultants

Example 3.5

Write an algorithm and draw a flowchart to read the names and sales of a group of
salesmen and output the average sales of the group. The number of the salesmen is
unknown, but the algorithm should terminate when 'xyz' is read as name.

In this example we do not know the exact number of the salesmen. Also, we do not
have to calculate a value to help us terminate the loop. So we have to use a sentinel
value as an exit condition. The value 'xyz' is chosen because it is an invalid name.

Data Table
Input Variables
Name: The name of the current salesman.
Sales: The sales of the current salesman.

Output Variable
Ave: The average sales of the group.

Program Variables
Tsale: Total sales of the group.
n: The number of the salesmen.

Algorithm: Written form


1- Tsale = 0
2- n = 0
3- Read name
4- Do the following while Name < > ‘xyz’

{Read Sales
Tsale = Tsale + Sales
n=n+1
Read name}
5- If n <> 0 then
{Ave = Tsale/n
Write Ave}
Else Write “No Salesmen”
6- End

72
Concepts of Computer Programming Allied Consultants

Start

n= 0
Tsale = 0

Read Name

N Name = 'xyz' Y

Read Sales n <> 0


N Y

Write 'No
Tsale = Tsale + Sales Ave = Tsale / n
Salesmen'

n= n+1 Write Ave

End

Fig.3.5
Flowchart of Example 3.5

Example 3.6

Employees at ABC Company are to receive a year-end bonus. The amount of the
bonus depends on the employees’ monthly pay, position code, and the number of
years with the company. Each employee is assigned a bonus based on the following
rules:

Position Code Bonus


1 One month pay
2 Two months' pay, maximum of 300
3 One and a half month's pay

73
Concepts of Computer Programming Allied Consultants

• Employees with more than 10 years experience are to receive an addition


L.E. 100.
• Employees with fewer than 2 years experience are to receive half of the
usual bonus.

Write an algorithm to read the data of a group of employees, where each employee
has a name, monthly pay, position code, and number of years worked with the
ABC Company. The output of the algorithm is the name and bonus of each
employee. The number of the employees is unknown, but the algorithm should
terminate when 'xyz' is read as name.

Data Table
Input Variables
Name: The name of the current employee.
Pay: The monthly payment of the current employee.
Code: The code of the current employee.
Exp: The years of experience of the current employee.

Output Variable
Bonus: The bonus of the current employee.

Algorithm: Written form


1- Read Name
2- Do the following while Name < > “xyz”
2.1 Read Pay, Code, Exp
2.2 If Code = 1 then Bonus = Pay
Else If Code = 2 then
{Bonus = 2 * Pay
If Bonus > 300 then Bonus = 300}
Else Bonus = 1.5 * Pay
2.3 If Exp < 2 then Bonus = 0.5 * Bonus
Else If Exp > 10 Then Bonus = Bonus + 100
2.4 Write Name, Bonus
2.5 Read Name
3- End

Exercise
Draw the flowchart of the previous example.

74
Concepts of Computer Programming Allied Consultants

Problems

3.1 Explain briefly the aspects of a correct loop structure.

3.2 What is the importance of initializing, testing, and updating the control
variable(s) of a loop?

3.3 Draw a flowchart and write an algorithm to read a number n and calculate and
print its factorial as n! = n * n-l * n-2 * …………..*2*1

3.4 Draw a flowchart and write an algorithm to read two numbers X & Y and
calculate and print XY, provided that X is an integer.

3.5 Draw a flowchart and write an algorithm to read a number and calculate and
print its integer part.

3.6 Draw a flowchart and write an algorithm that reads a set of non-zero numbers
and calculates and prints the largest number. The algorithm should terminate if zero
is read.

3.7 Modify example 3.5 to terminate if "XYZ" is read as input or the number of
salesmen reaches 50.

75
Concepts of Computer Programming Allied Consultants

45 I
4 Subprograms
4.1 Basic Concepts
In writing an algorithm we may face one or more of the following situations:

1- Part of the algorithm is identical to a part of a previously written algorithm.


2- A segment of the algorithm may be repeated in the same algorithm.
3- A very long and complicated problem where it is boring and confusing to think
of it as a whole.

If there is a technique that allows us to use a previously written algorithm without


rewriting it, we can easily solve problems 1 and 2. If we used the same technique to
break down a long and complicated problem by dividing it into simple sub
problems, and writing algorithms for solving each of the sub problems and using
the smaller algorithms to solve the main problem, this would help us to solve
problem 3. In fact, we can do all of this by us subprograms (Modules).

4.2 What is a module?


A module is an algorithm that is designed to perform a specific task; it may be used
to save time and effort, because it is written once and can be used by different
algorithms (Case 1), or be used more than once by the same algorithm (Case 2). It
also saves time and effort when solving a complicated problem by breaking down
the main problem into independent tasks and assigning each task to a member of a
team working on solving the problem, then the main algorithm is built up of these
subprograms (Case 3). Now let us have an example and solve it twice, once by
using the traditional method the other by using subprograms.

Example 4.1

Write an algorithm and draw a flowchart that reads two numbers X1 and X2 and
calculates and prints their factorials.
1- Traditional Method

Data Table
Input Variables
X1: First number to be processed.
X2: Second number to be processed.

Output Variables
F1: Factorial of Xl.
F2: Factorial of X2.

Program Variable
I: Counter.

76
Concepts of Computer Programming Allied Consultants

Algorithm: Written form


1- F1 = 1
2- I = 1
3- Read XI, X2
4- Do the following from I = 1 to X1
{FI=Fl*I
I = I +1}
5- I = 1
6- F2 = 1
7- Do the following from I = 1 to X2
{F2 = F2*I
I= I + 1}
8- Write F 1, F2
9- End

77
Concepts of Computer Programming Allied Consultants

Start

F1 = 1
i=1

Read X1, X2

N i > X1 ? Y

F2 = 1
i=1
F1 = F1 * i

N i > X2 ?
i=i+1 Y

F2 = F2 * i

Write F1 , F2

i=i+1

End

Fig.4.1
Flowchart of Example 4.1
(Method 1)

2- Using a Subprogram

1-Module Fact (A, F)

Data Table
Input Variable
A: Number to calculate its factorial.

Output Variable
F: Factorial of A.

78
Concepts of Computer Programming Allied Consultants

Program Variable
I: Counter

Algorithm: Written form


1- F = 1
2- I = 1
3- Do the following from I = 1 to A
{F = F*I
I = I+1}
3- End

2-Main

Data Table
Input Variables
X1: First number to be processed.
X2: Second number to be processed.
Output variables
Fl: Factorial of Xl.
F2: Factorial of X2.

Algorithm: Written form


1- Read XI, X2
2- Call fact (X1, F1)
3- Call fact (X2, F2)
4- Write Fl, F2
5- End

79
Concepts of Computer Programming Allied Consultants

Start Start
Main Fact (A , F)

F1 = 1
Read X1, X2
i=1

Fact (X1, F1)

i>A?
Y
N

Fact (X2, F2)


End
F=F*i

Write F1 , F2

i=i+1

End

Fig.4.2
Flowchart of Example 4.1
(Method 2)
Now let us explain tile difference between solution #1 and solution #2. From the
phrasing of the problem we have found that we are going to calculate the factorial
twice, i.e., the steps of calculating the factorial are going to be repeated twice in the
algorithm. This was done in solution # 1. In solution #2, we have decided to design
a module that calculates the factorial and use (Call) it twice in the algorithm. In
other words, we can write or flowchart the module once and call it twice.
Therefore, solution #2 is more logical and efficient way of solving the problem.

4.3 Module Structure


To call a module, we should have a module name. So we gave it the name “Fact”,
as a meaningful name, but any other name is also valid. Suppose that we are a team
and we have assigned the task of designing the module to one of the team. We
should not bother ourselves with the way he is going to calculate the factorial. On
the other hand, he should not bother himself with the way we are going to use the
module. We may use the module to calculate and print the factorial of a read
number, or we may calculate the factorial of a calculated number and use its
factorial in further calculations, i.e., we are not going to print the factorial. In
addition, the module designer should not bother himself with the number of times
we are going to call the module or the number of algorithms that are going to use
the module. But in all cases, there must be a method of passing data between the
main algorithm and the module.

80
Concepts of Computer Programming Allied Consultants

We are going to give the module a value through a variable name and receive the
factorial of this value through another variable name. The variables used in passing
data are called the parameters of the module. The parameters of a module are
listed between parentheses after the name of the module. They are its input
variables and output variables. So, the module designer has informed the rest of the
team that the module called “Fact” has two parameters, the first parameter is the
input and the second is the output (the factorial) and we should abide by the order
when calling the module. But we should not care about the names he has given to
the parameters.

4.4 Module Call


The header “Fact (A, F)” means that the module is called “Fact” and it has two
parameters (A, F). The data table declares what the input variable is and what the
output variable is. The list (A, F) is called the formal parameter list. It is a list of
the names of the input and output variables as used in the module body and as
declared in the data table. The program variables of the module should not appear
in the formal parameter list. In our example the module calculates the factorial of
the input variable “A” and stores it in the output variable “F”.

The module is written as if the variable “A” was having a value although it was
not. This is because the module does not execute by itself, but it should be called
by a main algorithm or by another module. The caller is responsible for providing
the module with the actual values to be manipulated through what is called the
actual parameter list. The actual parameter list is the list of variables used by a
module (the caller) in the step of calling (invoking) another module (the invoked).
In our example, the steps of calling the module are:

Call Fact (X1, Fl) Fact (X1, F1)

Call Fact (X2, F2) Fact (X2, F2)

The call step uses the invoked module name followed by the actual parameter list
enclosed between parentheses. It informs the algorithm to execute the invoked
module using each variable of the actual parameter list in place of the
corresponding variable of the formal parameter list. This means that both the
formal parameter list and the actual parameter list should have the same number of
variables with the same type in one-to-one correspondence.

In the shown example the step “Call Fact (X1, F1)” informs the algorithm to
execute the module “Fact” using “X1” in place of the variable “A” and “F1” in
place of the variable “F”. This results in calculating the factorial of “X1” and
storing the result in “Fl”.

81
Concepts of Computer Programming Allied Consultants

Example 4.2
Write a structured algorithm and draw a structured flowchart to calculate the series:

x2 x3 x4
y = l+ x + + + +……………………..
2! 3! 4!

Provided that x is positive and the stopping criterion is

xi
<= 0.001
i!

Now we are going to solve the problem using the general form of the given series.
We can rewrite the series as:

x 0 x1 x 2 x 3
y= + + + +…………………………
0! 1! 2! 3!

We note that the power of the numerator and the denominator of any term are
related together. The relation is that the denominator of a term is the factorial of the
2
power of the numerator. For example, the term having x as a numerator has 2! as
3
denominator and the numerator x has the denominator 3! and so on. In general,
i
the numerator x should be divided by the denominator i! to calculate a term. The
series is the sum of the terms calculated starting from i = 0 to infinity. So the
general form of the series is:


xi
Y= ∑
i = 0 i!

Where ∑ means summation.

To solve the problem using the general form we have to calculate one term at a
time and accumulate the calculated terms in a variable until the stopping condition
x0
is reached starting calculations from . So we are going to use a variable say “i”,
0!
initialize it by zero, then it is going to be used to calculate x 0 and 0!, then the
variable will be incremented by 1 to calculate the second term, and so on. This
means that we need a module to calculate x i and another module to calculate i!.
The latter has been already used in example 4.1.

Module pwr (x, y, p)


Data Table
Input Variables
X: Number to be processed.
Y: Power of X.
82
Concepts of Computer Programming Allied Consultants

Output Variable
P: X raised to the power Y.

Program Variable
I: Counter

Algorithm: Written form


1- P= 1
2- I = 1
3- Do the following from I = 1 to Y
{P = P*X
I = I+1}
4- End

Module Calc (A, S)


Data Table
Input Variable
A: Number to be processed.
Output Variable
S: The value of the series.
Program Variables
T: Term
K: Counter
P1, F1: Temporary Variables.

Algorithm: Written form


1- S = 0
2- K = 0
3- Do the following
{Call pwr (A, K, P1)
Call Fact (K, F1)
T = Pl/Fl
S=S+T
K=K+l}
Until T <= 0.001
4- End

Main
Data Table
Input Variable
X: Number to be processed.
Output Variable
Y: The value of the series.
Algorithm: Written form
1- Read X
2- Call Calc (X, Y)
3- Write Y
4- End

83
Concepts of Computer Programming Allied Consultants

Start Calc (A, S) Start


Main

S=0
Read X
K=0

Calc (X, Y) Pwr (A, K , P1)

Write Y Fact (K, F1)

End
T = P1 / F1
N

Start
Pwr (X , Y , P)

S=S+T

P=1

K = K +1

i > Y?
Y
N

T <= 0.001 ?
Y
End
P=P*X

End

i=i+1

Fig.4.3
Flowchart of Example 4.2

84
Concepts of Computer Programming Allied Consultants

Problems
4.1 Write a module that accepts a number and returns its integer part.

4.2 Draw the flowchart of problem 4.1

4.3 Write a module and draw its flowchart to accept two numbers and exchange
their values.

4.4 Write a structured algorithm and draw a structured flowchart to calculate the
series:

x3 x5 x7
y=x- + - +………………………………….
3! 5! 7!

Provided that the stopping criterion is

xi
| | <= 0.001
i!

85
Concepts of Computer Programming Allied Consultants

5 Arrays (Subscripted Variables)


5.1 Basic Concepts
In designing algorithms we should maintain the efficiency of the algorithm. One
criterion of efficiency is that the size of algorithm is not affected by the size of
data. For example, if we wish to write an algorithm to read five scores, calculate
their average and print it out, we may write it using one of two methods:

Method (A)
1- Sum = 0
2- Read Scl
3- Sum = Sum + Scl
4- Read Sc2
5- Sum = Sum + Sc2
6- Read Sc3
7- Sum = Sum + Sc3
8- Read Sc4
9- Sum = Sum + Sc4
10- Read Sc5
11- Sum = Sum + Sc5
12- Av = Sum/5
13- Write Av

Method (B)
1-Sum = 0
2- I = 1
3- Do the following from I = 1 to 5
{Read Sc
Sum = Sum + Sc
I= I + 1}
4- Av = Sum/5
5- Write Av

If the number of scores were 10 not only 5, the size of the algorithm using method
(A) would be nearly doubled. But using method (B) would not affect the size of the
algorithm, as we would simply change the 5 in step 3 to 10, i.e., the size of the
algorithm using method (B) is independent of the size of data.

• The Need To Store Data


Now, let us go further and expand our algorithm to calculate the number of
students having scores greater than the average. In this case, even method (B)
cannot be used because at the end of the loop only the last score is saved while the
others are overwritten, each score by its successor. So, we cannot compare each
score to the average. Then, method (A) seems to be inevitable as we have the
average and all the scores at hand. The proposed extension of the solution using
method (A) is as follows:

86
Concepts of Computer Programming Allied Consultants

1- Sum = 0
2- Read Sc1
3- Sum = Sum + Scl
4- Read Sc2
5- Sum = Sum + Sc2
6- Read Sc3
7- Sum = Sum + Sc3
8- Read Sc4
9- Sum = Sum + Sc4
10- Read Sc5
11- Sum = Sum + Sc5
12- Av = Sum/5
13- Write Av
14- Above = 0
15- If Scl > Av then Above = Above +1
16- If Sc2 > Av then Above = Above + 1
17- If Sc3 > Av then Above = Above + 1
18- If Sc4 > Av then Above = Above + 1
19- If Sc5 > Av then Above = Above + 1
20- Write Above

From the proposed solution, it is obvious that steps 15 to 19 are approximately the
same and the order of using the variables is not obligatory, i.e., any two steps may
be exchanged without affecting the solution. This means that the variables
Sc1...Sc5 are not used in a systematic way, although they are of the same type,
related together, and processed in the same way. A systematic way means that
instead of writing the steps repeatedly we can use a loop as far as all the steps
perform the same operation (comparing a score to the average). But what prevents
us from using a loop is that each step compares a different variable to the average.
To overcome this situation when dealing with a group of data items of the same
type and related together, we should use an array.

5.2 What is an Array?


An array is a collection of elements of the same type having one name, each
element can be referenced using a number, attached to the name, called index. The
index represents the location of the element in the array. In each element we can
store a value of the same type of the element. Fig 5.1 shows an array called “X”
having five elements with indexes 1,2, 3,4, and 5.

X1 X2 X3 X4 X5
X

Fig 5.1
The item X1 means the element #1 in the array “X”, X2 means the element #2 in the
array “X”, and so on. The array name associated with an index can be dealt with as
a variable, i.e., can be read, written, assigned a value, and used in calculations.
Assume the following segment:

87
Concepts of Computer Programming Allied Consultants

1- X1 = 7
2- X2 = 3
3- X3 = X1 + X2
4- X4 = X3/2
5- X5 = X4* 3

After the execution of the previous segment, the array ”X” will contain values as
shown in Fig 5.2.

X1 X2 X3 X4 X5

X 7 3 10 5 15

Fig 5.2

In general, if we use a variable index, “K” for example, “Xk” is the Kth element of
the array “X”. In this case, we can use the array in a systematic way by changing
the value of the index “K”. To print the array “X” shown in fig 5.2, in a systematic
way using a loop; the following steps are used:

1- K = 1
2- Do the following from K= 1 to 5
{Print Xk
K = K+l}
3- End

The output of the previous segment is: 7 3 10 5 15 as when K = 1 the lst element is
printed, when K = 2 the 2nd element is printed and so on. A complete solution for
our example using an array with a variable index could be as follows:

Data Table
Input Variables
Sc: Array of scores.
N: Number of scores.

Output Variables
Av: Average of the scores.
Above: Number of scores exceeding the average.

Program Variables
i: Index of the array.
Sum: Sum of scores.

Algorithm: Written form


1- N = 5
2- Sum = 0
3- Above = 0
4- i=1

88
Concepts of Computer Programming Allied Consultants

5- Do the following from i = 1 to N


{Read Sci
Sum = Sum + Sci
i = i+l }
6- Av = Sum/N
7- i = 1
8- Do the following from i = 1 to N
{If SCi > Av then Above = Above + 1
i = i+l }
9- Write Av, Above
10- End

It is clear that the efficiency of the algorithm is maintained by using an array. The
size of the algorithm is not affected if the size of data is increased, e.g., if the
number of students were 20, only the 5 in step 1 would be changed to 20 keeping
the size of the algorithm unaffected.

Example 5.1
You are given 100 students’ names and their corresponding scores for the last exam
of a computer course. Write an algorithm to calculate the average of these scores
and assign a letter grade for each student according to the following rule:

If the score of a student is within 10 points (above or below) of the average, give
the student a grade of “B”. If the score is more than 10 points higher than the
average give the student a grade of “A”. If the score is more than 10 points lower
than the average give the student a grade of “F”. The algorithm should display the
name, score, and grade of each student and the average of the scores.

Data Table
Input Variables
N: Number of students (initialized to 100).
Sc: Array of N scores.
Names: Array of N names.

Output Variables
Grade: The grade of the current student.
Av: Average of the N scores.

Program Variables
i: Index of the array.
Sum: Sum of scores.
Diff: The difference between the score of a student and the average.

Algorithm: Written form

1- N = 100
2- Sum = 0
3- i = 1
4- Do the following from i = 1 to N
89
Concepts of Computer Programming Allied Consultants

{Read Sci
Sum = Sum + Sci
Read Namesi
i = i+l}
5- Av = Sum/N
6- i=1
7- Do the following from i = 1 to N
{Diff = Sci -Av
If Diff < -10 then Grade = “F” else
If Diff > 10 then Grade = “A” else
Grade = “B”
i = i+1
Write Namesi, Sci, Grade}
Write “Class average = “, Av
9- End

Example 5.2
Given an array of length N, write two modules to calculate:

a- The sum of the elements of the array.


b- The maximum element.

Module getsum (A, N, S)

Data Table
Input Variables
N: Number of elements.
A: Array of length N.

Output Variable
S: The sum of the elements of A.

Program Variable
i: Index of the array.

Algorithm: Written form


1- S = 0
2- i = 1
3- Do the following from i = 1 to N
{Sum = Sum+Ai
I = i+l }
4- End

Module getmax (A, N, M)

Data Table
Input Variables
N: Number of elements.
A: Array of length N.
90
Concepts of Computer Programming Allied Consultants

Output Variable
M: The maximum element of A.

Program Variable
i: Index of the array.

Algorithm: Written form


1- M=A1
2- i = 2
3- Do the following from i = 2 to N
{If Ai > M then M=Ai
i = i+l }
4- End

5.3 Array Operations


As an array is a variable that collects a group of values together in a way that
allows us to deal with them in a systematic way, we can perform many systematic
operations using an array. The operations that could be performed using an array
include searching an array for a specific element and sorting an array in ascending
/descending order.

5.3.1 Searching
Searching is one of the most frequently used array operations. It means seeking a
specific element in the array to see whether it exists in the array or not. There are
many search techniques; each of which has its advantages and disadvantages.
Selecting a search technique depends on the nature of the stored data (sorted or
unsorted) and its amount (the size of data) as well. Two of the most common
search techniques are the sequential search and the binary search.

5.3.1.1 Sequential Search (Linear Search)


The typical search is that given an element “X” and an array “A” find whether or
not “X” is present in the array.

When looking for “X” in the array “A” we scan the array sequentially, element by
element starting from the first element. Each time we locate an element of “A” we
compare it to “X” if they are equals this means that “X” exists in the array and
searching is stopped. If they are not, we advance to the next element. If the array is
entirely scanned without finding “X” this means that “X” does not exist in the
array.

Example
Write a module to search all array for a specific number. The module should return
the location of the element in the array if it exists and return –1 otherwise; given
that the array holds N numbers and its minimum index is 1.

91
Concepts of Computer Programming Allied Consultants

Module seqsearch (A, N, X, Loc)

Data Table
Input Variables
A: Array of N elements.
N: The number of elements of the array.
X: The number to be sought.

Output Variable
Loc: the location of X in the array if it exists, (-1) if it does not exist.

Program Variables
I: index of the array.
Found: Existence indicator (1 exists, 0 does not exist).

Algorithm: Written form


1- I = 0
2- Found = 0
3- Do the following
{I = I+1
If AI = X then Found = 1}
Until (Found =1) or (I = N)
4- If Found = 1 then Loc = I else Loc = -1
5- End

5.3.1.2 Binary Search


Problem, given an element “X” and an array, “A” which is sorted in ascending
order, find whether or not “X” is present in the array?

The problem of searching an ordered list such as a dictionary or a telephone


directory occurs frequently in computing. Before discussing the computer solution
to such problems, let us draw upon the non-computer solution. For this purpose let
us think of the way we use to look up a number in the telephone directory. Let us
for example look up the number of Mr. “Sami”; one way to find this number is to
start at page 1 of the directory a progress through page by page until we find the
number or reach the end of the directory if the name does not exist. Our experience
tells us that this method, sequential search, is time consuming to a great extent and
that instead we use totally different approach to look up the name. The usual
approach is based mainly on our information about the directory. We know that the
directory ordered alphabetically in ascending order. So, we do not have to continue
searching to judge the non-existence of the name when we reach a name the
follows “Sami” in the alphabetical order (e.g., “Samia” or “Samir”). In addition we
do not have to start searching from page 1 as we know that “Sami” is located
somewhere near the last third of the directory. To conclude, all what we are trying
to do is to minimize the size of the data to be searched in order to minimize the
search time.

92
Concepts of Computer Programming Allied Consultants

Now, let us describe the search process using a new search approach. Actually, we
do not know in advance the exact location of the first name that follows Sami; so,
we can open the directory at a page near the last third of the directory to split the
directory into two parts. Then we examine the name at the top of the first page of
the second part. If the name follows “Sami” in alphabetical order this means that
the searched name “Sami” does not exist in the second part; so, we can omit the
second part from the search process. If this is not the case, i.e., if the name at the
top of the first page of the second part precedes “Sami”, we can omit the first part
from the search process. Now, we have only one part to be searched, as we are sure
that the searched name does not exist in the omitted part. The same approach can
be applied to the part to be searched. Each time we apply the technique we can
omit a part from the search process. In other words, each time we apply the
approach we reduce the set of data to be searched. We keep applying this technique
until we find the name or we do not find it.

To program the previously described technique, called the binary search, we should
perform it in a systematic way. What we need is a method that allows us to quickly
eliminate large portions of data and systematically home in on the relevant area.
The choice of the splitting point is arbitrary in the sense that correctness (the
algorithm gives the right solution) does not depend on it; but it does influence the
algorithm's effectiveness (the average number of comparisons). The optimal
solution is to choose it at the middle, because this eliminates half of the data in any
case.

Assume that we have a set of data with the first index “F”, and the last index “L”.
The middle index “M” is always the integer part of (F + L/2). If the element we are
seeking is not at “M”, it is either in the lower order half which starts at “F" and
ends at (M-1) or in the higher order half, which starts at (M + I) and ends at “L”.
As an illustration see fig 5.3.

If not here

F M-1 M M+1 L

Then

Either in this half Or in this half

Fig. 5.3
We can establish the relevant half according to the result of comparing the value to
be sought with the value at “M” If the two values are not the same, this comparison
will eliminate half of the data from further search; the problem is half size of the
original problem. If we are going to eliminate the higher order half, the set to be
searched starts at “F” and ends at (M -1). In other words, we move “L” to the
93
Concepts of Computer Programming Allied Consultants

location (M -1). Now we have a reduced set that starts at “F” and ends at “L”
(where L = M-l). But if we are going to eliminate the lower order half; we will
have a reduced set that starts at “F” (where F = M + 1) and ends at “L”. We can
continue to apply this method until we find the element we are seeking or “F” and
“L” crossover as a result of moving one of them toward the other each time. The
crossover means that we are going to search in previously eliminated parts; and this
means that the element does not exist.

Now let us write the module "Binsearch" that performs the binary search algorithm.
This module assumes that we have the module Intg (n, I), which is the solution of
problem 4.1.

Module Binsearch {A, N, X, Loc)

Data Table
Input Variables
A: Array of N elements.
N: The number of elements of the array.
X: The number to be sought.

Output Variable
Loc: The location of X in the array if it exists and ( N + 1 ) if it does not exist.

Program variables
First: The lower index of the set to be searched.
Last: The upper index of the set to be searched.
Mid: The index of the middle element of the set.
Found: existence indication (1 Exists & 0 Does not exist).

Algorithm: Written form


1- First = 1
2- Last = N
3- Found = 0
4- Do the following
{Mid = (First + Last) / 2
Mid = Intg (Mid, Mid)
If X = AMid then Found = 1
Else If X > AMid then First = Mid + 1
Else Last = Mid -1}
Until (Found = 1) or (First > Last)
5- If Found = 1 then Loc = Mid
Else Loc = N + 1
6- End

94
Concepts of Computer Programming Allied Consultants

5.3.2 Sorting
Sorting in general, is rearranging a set of data in either ascending or descending
order. We always deal with sorted data in telephone directories, dictionaries, class
lists, warehouses, and almost everywhere that stored data has to be searched and
retrieved. There are many sorting algorithms each of them may be optimal in some
cases, and some of them have advantages over the others.

It is therefore a suitable subject to give an idea about the performance analysis of


algorithms. In this text, the only criterion of performance to be discussed is the
number of comparisons. Two sorting algorithms, selection sort and bubble sort,
well be discussed assuming an array “A” of length 8, and sorting in ascending
order.
5.3.2.1 Selection Sorting
Consider the following unsorted array:

A1 A2 A3 ……………………. A8
25 40 20 10 17 50 6 48

It is required to develop an algorithm to order its elements as follows:

A1 A2 A3 ……………………. A8
6 10 17 20 25 40 48 50

The basic idea of the algorithm is to:

1- Select the smallest element of the array (n elements)


2- Store its index in a variable (m)
3- Exchange Am with the top of the n elements
4- Exclude the previous top
5- Then repeat these steps with the remaining (n - 1) elements, then with (n - 2)
elements, until the largest is left at the bottom location.

The result of this method is as follows:

Initial array 25 40 20 10 17 50 6 48
1st iteration 6 40 20 10 17 50 25 48
2nd iteration 6 10 20 40 17 50 25 48
3rd iteration 6 10 17 40 20 50 25 48
4th iteration 6 10 17 20 40 50 25 48
5th iteration 6 10 17 20 25 50 40 48
6th iteration 6 10 17 20 25 40 50 48
7th iteration 6 10 17 20 25 40 48 50

* The swapped elements are underlined

95
Concepts of Computer Programming Allied Consultants

Now let us write the required algorithm

Module Selectsort (A, n)

Data Table
Input Variables
A: Unsorted array.
n: The number of elements of A.

Output Variable
A: Sorted array.

Program Variables
top: Index of the element at the top and the counter of the outer loop
m: Index of the minimum element
J: Index of the compared elements and the counter of the inner loop
X: Intermediate variable for exchange.

Algorithm: Written form


1- top = 1
2- Do the following from top = 1 to n -1
2.1 m = top
2.2 J = top + 1
2.3 Do the following from J = top + 1 to n
{If AJ < Am then m = j
J = J+l}
2.4 X = Atop
2.5 Atop = Am
2.6 Am = X
2.7 top = top + 1
3- End

Remarks on design

1. When analyzing the selection sort to calculate the number of comparisons “C”
we find that in the first execution of the inner loop (n - l) comparisons are made, in
the second execution (n - 2), then (n - 3) and finally (1) comparison is made.
Therefore, the total number of comparison is:
C = (n - l) + (n - 2) + (n - 3)+………….. + 1 = n (n - l) / 2

In the previous example, C = 8 (8 - 1) / 2 = 28 comparisons.

2. If it is established that the set is sorted after the Kth iteration where
K < (n - l), the algorithm will not terminate; but it will continue till the end of the
outer loop. In this case the top will be exchanged with itself. As an illustration try
to trace the following set of data
50 10 40 20 25 17 48 6

3. This algorithm is suitable for sorting small sets of data.

96
Concepts of Computer Programming Allied Consultants

5.3.2.2 Bubble Sorting


Consider the following set of data:

A1 A2 A3 ……………………. A8
44 55 12 42 94 6 67 18

The basic idea of this algorithm is to increase the order of the data in the array
through repeated passes until the array is sorted. This can be achieved by applying
the following steps:

1.Compare each two adjacent elements starting at the end of the array, i.e.,
compare An with An-1, then An-1 with An-2, and finally Atop+l with Atop.
2. If the two compared elements are not in order exchange them.
3. Exclude the previous top.
4. Repeat these steps with the remaining (n - l) elements, then With (n - 2) elements
until the array is sorted.

Steps 1 and 2 result in increasing the order in the array, and moving the minimum
element to the top of the array. If we view the array to be in a vertical, instead of a
horizontal position, we can say that the minimum element is bubbled up to the top.
The result of this method is as follows:

Initial I=1 I=2 I=3 I=4 I=5 I=6 I=7


44 6 6 6 6 6 6 6
55 44 12 12 12 12 12 12
12 55 44 18 18 18 18 18
42 12 55 44 42 42 42 42
94 42 18 55 44 44 44 44
6 94 42 42 55 55 55 55
67 18 94 67 67 67 67 67
18 67 67 94 94 94 94 94

The required algorithm is as follows:


Module bsort (A, n)

Data Table
Input Variables
A: Unsorted array
n: Number of elements of A

Output Variable
A: Sorted array.

Program Variables
top: Index of the top element of the unsorted set.
j: Index of the compared elements.
X: Intermediate variable for exchange

97
Concepts of Computer Programming Allied Consultants

Algorithm: Written form


1- top = 1
2- Do the following while top <= (n - 1)
2.1 j = n

2.2 Do the following from j = n to top+1


if Aj-1 > Aj then
{ X = Aj
Aj = Aj-l
Aj-1 = X }
j = j-l

2.3 top = top + 1


3- End

This algorithm easily lends itself to an improvement. The given example shows
that the last three passes have no effect on the order of the items because the items
have been already sorted. An obvious technique for improving this algorithm is to
remember whether or not any exchange operations have taken place during a pass.
A last pass without further exchange operations is necessary to determine that the
algorithm is actually terminated.

The improved algorithm

Module bubblesort (A, n)

Data Table
Input Variables
A: Unsorted array
n: Number of elements of A.

Output Variable
A: Sorted array.

Program Variables
top: Index of the top element of the unsorted set.
J: Index of the compared elements.
X: Intermediate variable for exchange.
Xchng: Exchange indicator (equals 1 if an exchange takes place, and equals 0
otherwise).

Algorithm: Written form


1- top = 1
2- Xchng = 1
3- Do the following while ( top <= n -1) and (Xchng = I)
3.1 Xchng = 0
3.2 j = n

98
Concepts of Computer Programming Allied Consultants

3.3 Do the following from j = n to top + 1


If Aj-1 > Aj then
{X = Aj
Aj = Aj-1
Aj-1 = X
Xchng = 1}
j=j-l
3.4 top = top + 1
4- End

The output of the improved algorithm

Initial Top = 1 Top = 2 Top = 3 Top = 4 Top =


5
Xchng = 1 Xchng = 1 Xchng = 1 Xchng = 1 Xchng = 0
44 6 6 6 6 6
55 44 12 12 12 12
12 55 44 18 18 18
42 12 55 44 42 42
94 42 18 55 44 44
6 94 42 42 55 55
67 18 94 67 67 67
18 67 67 94 94 94

Remarks on design

1- The analysis of the bubble sorting algorithm is more difficult. The minimum
number of comparisons if the array is already sorted is (n - 1). The maximum
number of comparisons occurs when (n - 1) passes are gone through. In this case
the number of comparisons is n(n -1)/ 2, the same as the selection sorting.

2. If the algorithm terminates after the Kth iteration because it is proved that the
array is sorted, the number of comparisons “C” is computed as follows:
2
C = ( n -1 ) + ( n - 2 ) +………………. + ( n - K) = ( 2NK - K - K ) / 2

Where K < ( n -1 )

In the previous example, C = (2*8*5 - 5 - 25) / 2 = 25 comparisons


This algorithm is suitable for sorting data in which a small percentage of elements
are out of order.

Example 5.3
Whenever a meal is sold in Charlies Eatery, the cost of the order and a
corresponding meal code (1 = breakfast, 2 = lunch, 3 = dinner) are stored in two
parallel arrays (one for the cost and the other for the corresponding code). At the
end of the day, Carlie would like to obtain the day's total sales, the maximum meal
cost, the average cost of each meal, and a list of each meal sorted on cost in
ascending order.

99
Concepts of Computer Programming Allied Consultants

If it is known that the maximum expected number of meals is 750( 250 of each
meal) and the last entry of the cost array is 0 if the number of meals does not reach
its maximum (750), write a structured algorithm to produce the required
information.

In solving this problem we are going to use the two modules of example 5.2
and the selection-sorting module as well. In addition, we well write any other
modules as required.

Module separate (AM, AC, N, B, C, x)

Data Table
Input Variables
N: Maximum number of meals.
AM: Array of meal costs.
AC: Array of meal codes. .
C: Code of the meal to be separated.

Output Variables
B: Array of length 250 to hold the costs of a specific meal.
x: The actual number of costs stored in B.
Program Variable
i: Index of the arrays AM and AC.

Algorithm: Written form


1- x = 0
2- i = 1
3- Do the following while (i <= N) and (AMi <> 0)
{ If ACi = C then
{x = x + l
Bx = AMi }
i=i+l}
4- End

Module disarray (A, N)


Data Table
Input Variables
N: Actual number of stored costs.
A: Array of length 250.

Program Variable
i: Index of the array.

Algorithm: Written form


1- i = 1
2- Do the following from i = 1 to N
{ Write Ai
i=i+l}
3- End

100
Concepts of Computer Programming Allied Consultants

Module calculate (AM, N, Title, Av)

Data Table
Input Variables
N: Number of sold meals.
AM: Array of length 250 that holds N meal costs.
Title: Name of the meal to be processed.

Output Variables
AM: Array of meal costs sorted in ascending order.
Av: The average meal cost.

Program Variable
i: Index of the array.
S: Sum of the useful elements of AM

Algorithm: Written form


1- Call getsum (AM, N, S)
2- Av = S/N
3- Write “The average cost of“, Title, “ = “, Av
4- Call selectsort (AM, N)
5- Write “The sorted”, Title, “meals”
6- Call disparray (AM, N)
7- End

Main

Data Table
Input Variables
N: Maximum number of meals (initialized to 750).
Costs: Array of length 750 to hold meal costs.
Codes: Array of length 750 to hold meal codes.

Output Variables
Total: Total sales.
Maxmeal: Maximum meal cost.
Break: Array of length 250 to hold breakfast costs.
Lunch: Array of length 250 to hold lunch costs.
Dinner: Array of length 250 to hold dinner costs.
Vbreak: Average breakfast cost.
Vlunch: Average lunch cost.
Vdinner: Average dinner cost.

Program Variables
Nb: Number of sold breakfast meals.
Nl: Number of sold lunch meals.
Nd: Number of sold dinner meals.

101
Concepts of Computer Programming Allied Consultants

Algorithm: Written form


1- N = 750
2- Call getsum (Costs, N, Total)
3- Call getmax (Costs, N, Maxmeal)
4- Write “The total sales = “, Total
5- Write “The maximum meal cost = “, Maxmeal
6- Call separate (Costs, Codes, N, Break, 1, Nb )
7- Call separate (Costs, Codes, N, Lunch, 2, Nl )
8- Call separate (Costs, Codes, N, Dinner, 3, Nd )
9- Call calculate (Break, Nb, “breakfast”, Vbreak)
10- Call calculate (Lunch, Nl, “lunch”, Vlunch)
11- Call calculate (Dinner, Nd, “dinner”, Vdinner)
12- End

102
Concepts of Computer Programming Allied Consultants

Problems
5.1 Write a module to rearrange the elements of an array of length N, such that they
appear in reverse order.

5.2 Given a set of n students' examinations marks (in the range 1 to 20), write a
structured algorithm to calculate:

n ( xi − x)
a) The standard deviation of the set as sd = ∑ i =1 n
where x is the

average of the set


b) The number of students obtained each possible mark

c) The most frequently obtained mark(s)

Provided that you have a module Sqrt(x, s) that calculates the square root of “x”
and stores it in “s”

5.3 Trace the following set of numbers for the values 12, 34 using binary search:

2 5 7 8 10 12 15 20 21 27 33
40 45

5.4 Trace both the selection sort and the bubble sort algorithms using the following
set of data and determine the number of comparisons in each case.

9 8 10 7 12 12 20 27 25 30 6

103
Concepts of Computer Programming Allied Consultants

6 Recursion
6.1 How Modules Work Together
In some of the problems we have already discussed, we have split the problem to a
number of modules. The modules were called in the body of the main module to
arrive at a solution. Now let us explain how modules work together. Assume that
we have a module “Main” that calls a module “inner”, which in turn calls a module
“innermost” as follows:

Main Module

{ Start of Main
|
|
inner
{ Start of inner
|
|
innermost
{ Start of innermost
|
|
} End of innermost
|
|
} End of inner
|
|
} End of Main
1- “Main” executes until it encounters a call to “inner”. At this point module
“Main” suspends execution.

2- With “Main” suspended, module “inner” starts execution until a call to module
“innermost” is encountered. At this point “inner” also suspends execution in
addition to “Main”.

3- With both “Main” and “inner” suspended, module “innermost” starts execution
and continues until its end. At this point the result (output variables) of “innermost”
is passed to “inner”.

4- At the step that immediately follows “innermost”, module “inner” resumes


execution (“Main” is still suspended), and continues until its end. At this point the
result of "inner" is passed to Main. The result of “inner” does not necessarily
contain the result of “innermost”.

5- At the step immediately following “inner”, module “Main” resumes execution


until it terminates.
104
Concepts of Computer Programming Allied Consultants

6.2 Recursive Problems


What we have already explained is the necessary information required to explain
the ideas of recursion and recursive modules. A problem is said to be recursive, i.e.,
can be solved recursively, if it has the following characteristics:

1- It can be split to sub problems.

2- At a specific case (called the base case) the problem has a direct solution without
splitting.

3- One or more of the sub problems are similar to the original problem but closer to
the base case.

For example, the problem of calculating X n has a recursive solution as it has the
previously stated characteristics. The problem can be written in the form:

1 n=0
n
X =
X * X n −1 n>0

1- The problem can be split into sub problems (X multiplied by X n −1 ).

2- The problem has a base case (where n = 0 X n = 1 directly).

2- The sub problem X n −1 is similar to the original problem X n and is closer to


the base case( n-1 is closer to 0 than n).

Now the problem X n −1 can be solved with the same way as the original problem:

1 (n – 1) = 0
n −1
X =
X * X ( n −1) −1 (n – 1) > 0

As an example, the following steps represent the recursive solution of calculating


54

1- 5 4 = 5 * 5 3

But we cannot multiply because we still have 5 3

2- 5 3 = 5 * 5 2
54 = 5 * 5 * 52
The problem is not solved yet because the 52

3- 5 2 = 5 * 51
5 4 = 5 * 5 * 5 * 51
105
Concepts of Computer Programming Allied Consultants

51 can also be split

4- 51 = 5 * 5 0

Now we have 5 multiplied by the result of the base case that equals 1( 5 0 = 1).

5 4 = 5 * 5 * 5 * 5 * 1 = 625

From what we have already explained we find that a recursive problem is the
problem that we can solve terms of itself. If we try to write a module to solve a
recursive problem with the same concept, i.e., the module uses itself to solve the
problem; this means that we are writing a recursive module.

6.3 Recursive Modules


A recursive module is the module that calls itself. This feature enables a module to
be repeated with different parameters until it reaches the base case.
The following module pwr(x, y, p) recursively calculates x y and returns the result
in p.

Module pwr(x, y, p)

Input Variables
x, y: Two integer numbers

Output Variable
y
p: x raised to the power y ( x )

Program Variable

r: Intermediate Variable

Algorithm: Written form

1- If y = 0 then p = 1
else
{Call pwr(x, y-l, r)
p = x * r}
2- End

Hand-tracing an algorithm gives us an idea about how that algorithm works. A


recursive module can be also hand-traced. How to do this is illustrated in the
following figure using the previous procedure with x = 5 and y = 3.

106
Concepts of Computer Programming Allied Consultants

Call (5, 3, p)

125 x=5 y=3


y = 0 false
call pwr(5, 2,
r)

x=5 y=2
25 y = 0 false
call pwr(5, 1,
r)

x=5 y=1
5 y = 0 false
call pwr(5, 0,
r)

x=5 y=0
1 y=0 true
p=1

Example 6.1

Write a recursive module that prints an array of length N in reverse order.


Test the algorithm using an array of length 4.

Assume that we have an array “A” with elements A1 , A2 ,….. , An .


It is required to print it in the order An , An −1 , ……., A2 , A1 .

The base case of this problem is dealing with an array of length 1, i.e., contains
only one element. The solution of the base case is to print that element. If this is not
the case, we print the last element and then print the rest of the may from 1 to N - l
in reverse order.

Module revprint (A, N)

Data Table
Input Variables
A: Array of integer values
N: Number of elements in A

107
Concepts of Computer Programming Allied Consultants

Algorithm: Written form


1- If N = 1 then print A1 else
{print An
revprint (A, N-l) }
2- End

To test the algorithm assume the call revprint(X, 4), the following sequence.of calls
and prints will be performed:

Call revprint with parameters X, 4


Print X 4
Call revprint with parameters X, 3
Print X 3
Call revprint with parameters X, 2
Print X 2
Call revprint with parameters X, 1
Print X 1
End fourth call
End third call
End second call
End first call

X 4 , X 3 , X 2 , X 1 are printed.

Example 6.2

Write a recursive module that calculates n! (n factorial).

1 if n = 0
We all know that n! =
n * (n – 1)! if n > 0
Module fact (N, f)

Data Table
Input Variable
N: Positive integer

Output Variable
f: N factorial

Program Variable
t: Temporary variable

Algorithm: Written form


1- If N = 0 then f = 1 else
{ Call fact ( N - l, t )
f=N*t}
108
Concepts of Computer Programming Allied Consultants

2- End
Example 6.3

Given that the fibonacci sequence of the numbers from 1 to 10 is 1, 1, 2, 3, 5, 8, 13,


21, 34, 55. Write a recursive module to compute the Nth fibonacci number.
From the given sequence the fibonacci sequence can be defined as follows:

1 n=1&n=2
fib(n)=
fib(n – 1) * fib( n – 2) n>2

Module fibo (n, fib)

Data Table
Input Variable
n: Integer number

Output Variable
fib: The Nth fibonacci number

Program Variables
t1, t2: Intermediate variables

Algorithm: Written form


1- If n < 2 then fib = 1 else
{Call fibo (n-l, t1)
Call fibo (n-2, t2)
fib = t1 + t2 }
2- End

From the previous examples we can see that recursion may be used as an
alternative to looping. However, recursive solutions are less efficient in terms of
execution time and storage than an iterative one. But it enables us to provide a
simple and straightforward solution to a problem. There are many problems,
beyond the scope of this text that would be very difficult to solve without recursion
(see Dale, 1985 and Wirth, 1986).

109
Concepts of Computer Programming Allied Consultants

Problems
6.1 Trace example 6.2 for n = 5

6.2 Trace example 6.3 for n = 7

6.3 Modify the revprint algorithm to print the array in normal order.

6.4 Write a recursive module to calculate the sum of the elements of an array of
length N.

6.5 Write a recursive module to perform the binary search algorithm. Assume that
you have an array “A” of length N sorted in ascending order.

110
Concepts of Computer Programming Allied Consultants

Appendix A

111
Concepts of Computer Programming Allied Consultants

Digital Number Systems


Many number systems are in use in digital technology. The most common are the decimal,
binary, octal, and hexadecimal systems. The decimal system is clearly the most familiar to us
because it is a tool that we use every day. Examining some of its characteristics will help us to
better understand the other systems.

Decimal System:

The decimal system is composed of 10 numerals or symbols. These 10 symbols are


0,1,2,3,4,5,6,7,8,9; using these symbols as digits of a number, we can express any quantity. The
decimal system, also called the base-10 system, because it has 10 digits, has evolved naturally as
a result of the fact that man has 10 fingers. In fact, the word "digit" is the Latin word for "finger".
The decimal system is a positional-value system in which the value of a digit depends on its
position. For example, consider the decimal number 453. We know that the digit 4 actually
represents 4 hundreds, the 5 represents 5 tens, and the 3 represents 3 units. In essence, the 4
carries the most weight of the three digits; it is referred to as the Most Significant Digit (MSD).
The 3 carries the least weight and is called the Least Significant Digit (LSD).

Consider another example, 27.35. This number is actually equal to two tens plus seven units plus
three tenths plus five hundredths, or 2 x 10 + 7 x 1 + 3 x 0.1 + 5 x 0.01. The decimal point is used
to separate the integer and fractional parts of the number.

The various positions relative to the decimal point carry weights that can be expressed as powers
of 10. This is illustrated in figure A.1, where the number 2745.214 is represented. The decimal
point separates the positive powers of 10 from the negative powers. The number 2745.214 if thus
equal to:
(2 x 10 +3) + (7 x 10 + 2) + (4 x 10 +1) + (5 x 100) + (2 x 10-1) + (1 x 10-2) + (4 x 10-3)
Positional Values
(Weights)

…...107 106 105 104 103 102 101 100 10-1 10-2 10-3 10-4 10-5 10-6 10-7 10-8

0 0 0 0 2 7 4 5 . 2 1 4 0 0 0 0 0

MSD Decimal Point LSD

Figure A.1: Decimal Position values as powers of 10


In general, any number is simply the sum of the products of each digit value times its positional
value.

112
Concepts of Computer Programming Allied Consultants

Binary System:

Unfortunately, the decimal number system does not lend itself to convenient implementation in
digital systems. For example, it is very difficult to design electronic equipment so that it can work
with 10 different voltage levels (each one representing one decimal character, 0-9). On the other
hand, it is very easy to design simple, accurate electronic circuits that operate with only two
voltage levels. For this reason, almost all digital systems use binary number system (base-2) as
the basic number system of its operations, although other systems are often used in conjunction
with binary.

In the binary system there are only two symbols or possible digit values, 0 and 1. Even so, this
base-2 system can be used to represent any quantity that can be represented in decimal or other
number systems. In general though, it will take a greater number of binary digits to express a
given quantity.

All the statements made earlier concerning the decimal system are equally applicable to the
binary system. The binary system is also a positional-value system, wherein each binary digit has
its own value or weight expressed as powers of 2. This is illustrated in figure A.2. Here, places to
the left of the binary point (counterpart of the decimal point) are positive powers of 2 and places
to the right are negative powers of 2. The number 1011.101 is shown represented in the figure. To
find its equivalent in the decimal system we simply take the sum of the products of each digit
value (0 or 1) times its positional value.

1011.1012 = (1 x 23) + (0 x 22) + (1 x 21) + (1 x 20) + (1 x 2-1) + (0 x 2-2) + (1 x 2-3)


= 8 + 0 + 2 + 1 + 0.5 + 0 + 0.125
= 11.62510

Positional Values
(weights)

…….. 27 26 25 24 23 22 21 20 2-1 2-2 2-3 2-4 2-5 2-6 2-7 2-8…..

0 0 0 0 1 0 1 1 •1 0 1 0 0 0 0 0

MSB Binary Point LSB

Figure A.2 : Binary Position values as powers of 2

Notice in the preceding operation that subscripts (2 and 10) were used to indicate the base in
which the particular number in expressed. This convention is used to avoid confusion whenever
more than one number system is being employed.

113
Concepts of Computer Programming Allied Consultants

In the binary system, the term binary digit is often abbreviated to the term bit, which we will use
henceforth. Thus, in the number expressed in the figure A.2 there are 4 bits to the right of the
binary point, representing the fractional part. The Most Significant Bit (MSB) is the leftmost bit
(largest weight). The Least Significant Bit (LSB) is the rightmost bit (smallest weight).
These are indicated in figure A.2.

Number Systems and Codes

In digital systems numerical information is usually represented in the binary number system (or
another related binary code). The binary system was introduced in Chapter 1, where its
similarities to the decimal system were pointed out. Several other systems for representing
numerical data are also important in digital systems, notably the octal (base-8), hexadecimal
(base-16), binary-coded-decimal (BCD), and excess-3 representations. The various number
systems, their relationships, and arithmetic operations will be studied in this chapter.

Binary – to – Decimal Conversions

As explained earlier, the binary number system is a positional system where each binary digit
(bit) carries a certain weight based on its position relative to the binary point. Any binary number
can be converted to its decimal equivalent simply by summing together the weights of the various
positions in the binary number that contain a 1.
For example:
1 1 0 1 1 (Binary)

24 23 22 21 20 = 16 + 8 + 2 + 1
= 2710 (Decimal)

The same method is used for binary numbers that contain a fractional part:
101.101 = 22 + 20 + 2-1 + 2-3
= 4 + 1 + 0.5 + 0.125
= 5.62510

Exercise:

Convert the following numbers:


A. 1001102
B. 243.312510
C. 0.1100012

Answers: A. 3810
B. 11110011.01012
C. 0.76562510

114
Concepts of Computer Programming Allied Consultants

Decimal-to-Binary Conversions:

There are several ways to convert a decimal number to its equivalent binary-system
representation. A method that is convenient for small numbers is the reverse of the process
described previously to convert binary to decimal. The decimal number is simply expressed as a
sum of powers of 2 and then 1s and 0s are written in the appropriate bit positions.

For example:

1310 = 8 + 4 + 1 = 2 3 + 22 + 0 + 20
=1 1 0 12

Another example:

25.37510 = 16 + 8 + 1 + 0.25 + 0.125


= 24 + 23+ 0 + 0 + 20 + 0 + 2-2 + 2-3
=1 1 0 0 1.0 1 12

For larger decimal numbers, the above method is laborious. A more convenient method entails
separate conversion of the integer and fractional parts. For example, take the decimal number
25.375, which was converted above. The first step is to convert the integer portion, 25. This
conversion is accomplished by repeatedly dividing 25 by 2 and writing down the remainders after
each division until a quotient of zero is obtained:

25/2 = 12 + remainder of 1
12/2 = 6 + remainder of 0
6/2 = 3 + remainder of 0
3/2 = 1 + remainder of 1
1/2 = 0 + remainder of 1
MSB LSB

1 1 0 0 12

The desired binary conversion is obtained by writing down the remainders as shown above.
Note that the first remainder is LSB and the last remainder is the MSB.

The fractional part of the number (0.375) is converted to binary by repeatedly multiplying it by 2
and recording any carries in the integer position:

0.375 x 2 = 0.75 = 0.75 + carry of 0


0.75 x 2 = 1.50 = 0.50 + carry of 1
0.50 x 2 = 1.00 = 0.00 + carry of 1
0.37510 = .0 1 12

115
Concepts of Computer Programming Allied Consultants

Note that the repeated multiplications continue until the product of exactly 1.00 is reached, since
further multiplication results in all zeros. Notice here that the first carry is written in the first
position to the right of the binary point.
Finally, the complete conversion for 25.375 can be written as the combination of integer and
fraction conversions:

25.37510 = 11001.0112

Exercise:

Apply the previous method to convert the following:


632.8510

Answer:

1001111000.110112

116