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 WELLDESIGNED PROGRAM? 2
1.3 COMPUTER PROGRAMS 2
1.4 STRUCTURED PROGRAM DESIGN: DIVIDE AND CONQUER 3
1.5 GOALS OF STRUCTURED PROGRAMMING : 4
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
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
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.
2
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
6
Concepts of Computer Programming Allied Consultants
Natural
Very
highlevel
languages
Application generators
Fourthgeneration language
Fourth
Productionoriented Useroriented
generation
Objectoriented
Highlevel
languages
Problemoriented
Third
generation
Procedureoriented
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 Lowlevel
languages
First
Machine
generation
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
languagetranslator 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 “machineoriented” and requires thorough knowledge of computer
9
Concepts of Computer Programming Allied Consultants
hardware.
2) Quite hard to learn and slow to write.
10
Concepts of Computer Programming Allied Consultants
11
Concepts of Computer Programming Allied Consultants
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 Thirdgeneration languages (3GLs) fall into three categories:
1) Procedureoriented languages,
2) Problemoriented languages, and
3) Objectoriented languages.
• ProcedureOriented 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 thirdgeneration languages include LISP, LOGO, FORTH, Prolog, and
Modula2.
1 Business Languages
12
Concepts of Computer Programming Allied Consultants
2 Scientific Languages
Theses algebraic formulatype 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 lowlevel and highlevel languages.
Like assembly language, C gives programmers extensive control over
computer hardware, but because C uses Englishlike statements, which are
easy to read, it is often classified as a highlevel language.
C also incorporates sophisticated control and data structures, which make
it a powerful but concise language.
C is relatively machineindependent: 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 AllPurpose Symbolic Instruction Code) was
developed at Dartmouth College in 1965 to provide students with an easy
tolearn, interactive language on a timesharing 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 Windowsbased 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 topdown design to students.
Figure 17 illustrates a Pascal program that computes gross pay for hourly
wage earners.
• Other ProcedureOriented Languages
LISP
A listprocessing 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
FORTH
FORTH (1971) is used for device control applications, arcade games, and
robotics.
Modula2
Modula2 (1981) enables selfcontained modules to be combined in a
program.
• ProblemOriented Languages
1) A problemoriented language is designed to address a particular application
area or to solve a particular set of problems.
2) Problemoriented languages do not require the programming detail of procedure
oriented ones.
3) The emphasis of problemoriented languages is more on input and the desired
output than on the procedures or mathematics involved.
4) Problemoriented 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
• ObjectOriented 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 procedureoriented languages, the emphasis is on what is done (the action).
In objectoriented languages, the emphasis is on the object of the action, thus
the object orientation.
An objectoriented 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 objectoriented language does is allow a programmer to build
program with preassembled 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
17
Concepts of Computer Programming Allied Consultants
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 fourthgeneration 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 programmersupplied information and
actually generate program code.
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
• Programming languages are classifieds into two different types: procedural and
nonprocedural.
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.
22
Concepts of Computer Programming Allied Consultants
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
23
Concepts of Computer Programming Allied Consultants
Call Printer
Predefined compute (document or
earnings report)
process routine
Read a
Online storage
record
Input/output
Terminal point
(end or begin Input Data
procedure)
Connector A A
Log
Manual number
of last
process check
Annotation Employee
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
25
Concepts of Computer Programming Allied Consultants
Instruction 1
Instruction 2
Instruction 3
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).
condition
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=GD
IF P is Positive,
P < G  D
then print a check
N T
P>0
Print
Check
1) DO FOR loop:
29
Concepts of Computer Programming Allied Consultants
I counter.
The logic of this structure is pictured in Figure 7.
2) DO WHILE loop:
3) DO UNTIL loop:
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
IModule Module
(body of loop) (body of loop)
True False
Condition Condition
True
False
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
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.
ENDif
Read overdue billing file.
End
33
Concepts of Computer Programming Allied Consultants
• Input/output instructions direct the computer to “read from” or “write to” a peripheral
device.
• Format instructions describe how data are to be entered to or output from RAM.
34
Concepts of Computer Programming Allied Consultants
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 runtime 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
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
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.
40
Concepts of Computer Programming Allied Consultants
41
Concepts of Computer Programming Allied Consultants
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
1Read Numl, Num2
42
Concepts of Computer Programming Allied Consultants
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 autotrip
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
45
Concepts of Computer Programming Allied Consultants
Start
R
Dist, Speed
Time = Dist/Speed
Cpg = 20
R
Kpg
Galused = Dist/Kpg
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:
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
47
Concepts of Computer Programming Allied Consultants
Start
R Basic, Ovh
Taxr = 0.1
Pph = 5
W
Net
End
Fig. 1.4
Flowchart of Example 1.3
48
Concepts of Computer Programming Allied Consultants
Example 1.4
Draw a flowchart and write an algorithm to read a1, a2, b1, b2, c1, and
c2 and find the solutions x and y.
Start
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.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.
50
Concepts of Computer Programming Allied Consultants
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.
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.
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.
3 Decision step
step # 1
→ Segment
step # n
3 Decision step
{step # 1
step # n }
3 Decision step
3.1 Step # 1
3.n Step # n
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
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
False True
IF
condition
Instruction(s) Instruction(s)
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
Output Variables
Net: Employee’s net salary
Gross: Employee’s gross salary
Program Variables
Tax: Tax deductions
56
Concepts of Computer Programming Allied Consultants
Start
Read Hours,
HWR
HTR = 0.07
LTR = 0.04
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:
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
58
Concepts of Computer Programming Allied Consultants
Start
Read Name, SC
N SC >= 90 ? Y
Grade = 'A'
N Sc >= 80 ? Y
Sc >= 60 ?
N Y Grade = 'C'
Rate = 'Very Good'
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
60
Concepts of Computer Programming Allied Consultants
Start
Read Hours,
Rate
N Hours <= 35 ? Y
Diff = 10
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:
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.
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:
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
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).
63
Concepts of Computer Programming Allied Consultants
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
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.
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
66
Concepts of Computer Programming Allied Consultants
Start
First = 1
Last = 999
Odd = Firstn
Sum = 0
N
Write Sum
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
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
1* ( X ) X * ( X ) X 2 * ( X ) X 3 *(X )
Y = 1+ + + + +………………………….
(1) 1 * (2) 1 * 2 * (3) 1 * 2 * 3 * (4)
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.
{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
Write 'No
Tsale = Tsale + Sales Ave = Tsale / n
Salesmen'
End
Fig.3.5
Flowchart of Example 3.5
Example 3.6
Employees at ABC Company are to receive a yearend 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:
73
Concepts of Computer Programming Allied Consultants
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.
Exercise
Draw the flowchart of the previous example.
74
Concepts of Computer Programming Allied Consultants
Problems
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 * nl * n2 * …………..*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 nonzero 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:
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
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
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
2Main
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.
79
Concepts of Computer Programming Allied Consultants
Start Start
Main Fact (A , F)
F1 = 1
Read X1, X2
i=1
i>A?
Y
N
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.
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.
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:
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 onetoone 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!
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!
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.
Output Variable
P: X raised to the power Y.
Program Variable
I: Counter
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
S=0
Read X
K=0
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.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!
xi
  <= 0.001
i!
85
Concepts of Computer Programming Allied Consultants
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)
1Sum = 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.
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.
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.
88
Concepts of Computer Programming Allied Consultants
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.
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:
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.
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.
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.
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
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).
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 (M1) 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 M1 M M+1 L
Then
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 = Ml). 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.
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).
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.
A1 A2 A3 ……………………. A8
25 40 20 10 17 50 6 48
A1 A2 A3 ……………………. A8
6 10 17 20 25 40 48 50
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
95
Concepts of Computer Programming Allied Consultants
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.
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
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
96
Concepts of Computer Programming Allied Consultants
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 An1, then An1 with An2, 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:
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
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.
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).
98
Concepts of Computer Programming Allied Consultants
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 )
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 selectionsorting module as well. In addition, we well write any other
modules as required.
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.
Program Variable
i: Index of the array.
100
Concepts of Computer Programming Allied Consultants
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
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
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
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”.
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
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
1 5 4 = 5 * 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
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.
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
1 If y = 0 then p = 1
else
{Call pwr(x, yl, r)
p = x * r}
2 End
106
Concepts of Computer Programming Allied Consultants
Call (5, 3, p)
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
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.
Data Table
Input Variables
A: Array of integer values
N: Number of elements in A
107
Concepts of Computer Programming Allied Consultants
To test the algorithm assume the call revprint(X, 4), the following sequence.of calls
and prints will be performed:
X 4 , X 3 , X 2 , X 1 are printed.
Example 6.2
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
2 End
Example 6.3
1 n=1&n=2
fib(n)=
fib(n – 1) * fib( n – 2) n>2
Data Table
Input Variable
n: Integer number
Output Variable
fib: The Nth fibonacci number
Program Variables
t1, t2: Intermediate variables
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.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
Decimal System:
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 101) + (1 x 102) + (4 x 103)
Positional Values
(Weights)
…...107 106 105 104 103 102 101 100 101 102 103 104 105 106 107 108
0 0 0 0 2 7 4 5 . 2 1 4 0 0 0 0 0
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, 09). 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 (base2) 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
base2 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 positionalvalue 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.
Positional Values
(weights)
0 0 0 0 1 0 1 1 •1 0 1 0 0 0 0 0
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.
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 (base8), hexadecimal
(base16), binarycodeddecimal (BCD), and excess3 representations. The various number
systems, their relationships, and arithmetic operations will be studied in this chapter.
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 + 21 + 23
= 4 + 1 + 0.5 + 0.125
= 5.62510
Exercise:
Answers: A. 3810
B. 11110011.01012
C. 0.76562510
114
Concepts of Computer Programming Allied Consultants
DecimaltoBinary Conversions:
There are several ways to convert a decimal number to its equivalent binarysystem
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:
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:
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:
Answer:
1001111000.110112
116
Molto più che documenti.
Scopri tutto ciò che Scribd ha da offrire, inclusi libri e audiolibri dei maggiori editori.
Annulla in qualsiasi momento.