Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

BMS 201: Computer Programming / Object Oriented Programming

Basic concepts of programming


A program is a concise, systematic, step by step set of instructions that a computer obeys in order to solve a
given problem. The act of logically sequencing and assembling these instructions is known as programming. A
single program addresses a particular problem e.g. one may develop a program to calculate and assign grades
to students, compute an employees pay, or update some data stored in a file. Programs are written in given a
programming language, e.g. Basic, COBOL, FORTRAN, C++, Java etc.
Software is a collection of programs and their associated documentation. The art and science of developing
programs is called software development. Programmers and software developers create and maintain
programs. In the world today there are millions of programs (nowadays popular known as Apps) that can
perform a variety of tasks. The social media such as Facebook and Whatsup that we enjoy and are addicted to
are simply large programs.
DUTIES OF A COMPUTER PROGRAMMER
1. Trains software users within an organization
2. Advises the management about software-related matters
3. Maintains updated documentations and records about the corporate software
4. Evaluates and modifies the existing software
5. Designs and develops computer programs in a business organization
6. Handle users program relating to a particular program – user support

Over the years programming has evolved significantly.


Machine language – first generation programming languages
A computer is designed to execute only one language – the machine language. Machine language programs
are written at the most basic level of computer operation. In machine language instructions are coded as a
series of 1s and 0s. This is the first generation language. A machine code language is immediately executable,
i.e. requires no translation .e.g. the instruction that causes the content of memory a location 100 to be brought
to the ALU may be represented in its full binary form as 0001010000001100100. Those instructions constitute a
tiny program. It must be borne in mind that machine code yields no documentation of what is being done and
therefore it is cumbersome and debugging becomes very difficult.

Assembly Languages – second generation programming languages


Writing programs in machine code made programming to be almost impossible and therefore the language
was modified to constitute statements that are nearer to human than to machine. The output of this
development led to assembly language, which is the second-generation language. Rather than the
cumbersome series of 1s and 0s assembler language use easily recognized symbols known as mnemonics to

1
represent instructions e.g. mnemonic MUL may represent multiply. The primitive assembler language offered
the programmer only a Mnemonics representation of the operators e.g. SUB instead of 11000110 for subtract
and a decimal representation of the operand e.g. 102 instead of 00000000000001100110 for the operand part.
Thus a full instruction would be SUB102. A program known as assembler translates the mnemonics and
symbols to machine code and assigns absolute storage locations to the symbolic variables.
Assembly language like machine codes are unique to a particular machine i.e. they are still machine dependent
hence a program written for one machine will note run in a different machine.

High level languages


These on the other hand are machine independent and can run on a variety of computers. They however
require to be translated to machine understandable language i.e. machine code before the computer can
understand them. Compilers and interpreters are used to translate high level languages into machine codes.
There are three major high level languages
 Procedural languages.
 Non – procedural languages
 Natural languages
Structured or Procedural languages - Third generation programming languages
Procedural languages greatly changed programming concept by introducing English like statements in
programming. These made programming easy, enjoyable and independent of the type of machine. Procedural
languages are problem oriented languages which use specific sequence of steps to perform tasks; they are
suitable for business and scientific applications. Moreover they and other higher level languages include in built
library of functions and procedures. They are classified according to particular application areas such as
scientific, business or multipurpose.
Scientific languages
These are algebraic formula type languages specifically designed to meet typical scientific processing
requirement such as mathematical equations, iterative processing, matrix manipulations etc. They include
 FORTRAN – Formula Translator
 APL - A programming language.

Business Oriented languages.


Business programming languages are designed to be effective tools for developing business information
systems. The strength of business oriented languages lies in their ability to store, retrieve, and manipulate
alphanumeric data. They include
 COBOL- Common business oriented language.
 PG – report program generator.

2
Multipurpose languages
Multipurpose languages are equally effective for both scientific and business applications. They are an
outgrowth of the need to simplify the programming envelopment by providing the programmer with all
programming needs of a company. They include
 BASIC – Beginners All-purpose Symbolic Instruction Code
 Pascal – Named after a French mathematician Blaise Pascal
 C
Non procedural languages - The fourth generation programming languages
These languages do not require specific sequence of steps to perform a given task. They are optimized for
database manipulation by requiring programmers to only provide what is to be done and not how to do it.
These greatly simplify programming. They included languages such as structured query language SQL, query by
example QBE and many others.

Natural languages - fifth generation programming languages


These are advanced programming languages that are not constrained by syntax, keywords or specific
programming vocabulary. Programmers can develop codes as naturally as instructing a fellow human being to
perform a given tasks. Most object oriented languages such as prolog, Java, C++, Perl, Python and others fall in
this category.

Comparison between low & high level languages

Low level languages High level languages


Low-level languages are difficult to learn and to High-level languages are easy to learn and program
program in. in.
Low-level languages are far from human languages High level languages are near to human languages
therefore difficult to understand. hence easy to understand.
Programs in low-level languages are fast in Programs in high-level languages are slow in
execution they need no or minimum translation. execution they have to be translated into machine
language.
Programs in low-level languages are difficult to Programs in high-level languages are easy to modify,
modify, maintain and debug. maintain and debug.
Low-level languages provide facility to write High-level languages do not provide much facility at
programs at hardware level. hardware level.
These languages are normally used to write These languages are normally used to write
hardware programs. application programs.

3
Machine dependent Machine independent
Does not contain library of inbuilt functions Incorporate library of inbuilt functions

Choice of programming language


When a computer application is being designed a choice of programming language has to be made. A number
of factors influence the choice.
 Type of application thus nature of business, commercial or scientific.
 Facilities required in the application – e.g. speed of execution
 Availability of the language – thus if the compiler of the language is available not.
 Availability of programmers – if the personnel proficient in the language is available
 Object program efficiency for example limitation of size of main memory.
 Development costs – the cost of developing a program using the language.
 Compatibility of the language – if the program developed from the language can run on a variety of
machines.
 Maintenance costs – how expensive is it to maintain programs in such languages.
MAJOR PROGRAMMING LANGUAGES
The following sections on individual languages give you an overview of some third-generation languages that
are in use today: FORTRAN, COBOL, BASIC, RPG, Visual Basic, C, C++, and Java.
FORTRAN
Developed by IBM and introduced in 1954, FORTRAN—which stands for FORmula TRANslator—was the first
high-level language. FORTRAN is a scientifically oriented language used primarily for engineering, math-
ematical, and scientific tasks. FORTRAN is very good at representing complex mathematical formulas. Most
experienced engineers and scientists learned FORTRAN in college, and over the years many scientific and
engineering applications have been written in FORTRAN. However C, C++, or Java have replaced FORTRAN.

COBOL: The Language of Business


In 1959, COBOL, which stands for COmmon Business-Oriented Language was introduced.
In keeping with business programming requirements, COBOL is very good for processing large, complex data
files and for producing well-formatted business reports. COBOL is English-like; even if you know nothing about
programming, you may still be able to follow a COBOL program's logic. This English-like appearance is easy to
read and understand. However it’s quiet wordy (verbose).

BASIC: The Beginner's Language


BASIC, which stands for Beginners' All-purpose Symbolic Instruction Code, was originally developed by
Dartmouth professors John Kemeny and Thomas Kurtz in 1965 to teach programming to their students. With

4
the introduction of the microcomputer in the late 1970s, the popularity of BASIC increased dramatically, owing
to its two main characteristics: First, it is easy to learn, which allowed those early microcomputer buyers to
write their own software. Second, the translator program that converts BASIC code into machine language
takes very little primary memory, allowing it to fit on those early machines, which often had no more than 16K
of memory.

RPG: Report Generation


RPG, which stands for Report Program Generator, was developed by IBM in 1965 to allow rapid creation of
reports from data stored in the computer files. A predecessor of 4GLs, it allowed the programmer to simply
describe the source data and the desired report format; then it created a program to produce the report. A
complex report could be created much more quickly with RPG than with COBOL.

Visual Basic
Microsoft introduced Visual Basic (often referred to as VB) in 1987 as its first visual development tool. It allows
the programmer to easily create complex user interfaces containing standard Windows features, such as
buttons, dialog boxes, scrollbars, and menus. Each of these features could take hundreds of lines of code to
implement

C: A Portable Language
A language created by Dennis Ritchie at Bell Labs in 1972, C produces code that approaches assembly language
in efficiency while still offering the features of a high-level language. C was originally designed to write systems
software but is now considered a general-purpose language. One of C's primary advantages is its portability:
There are C compilers for almost every combination of computer and operating system available today.

JAVA
Java, from developers at Sun Microsystems, is a popular programming language. Java is a network-friendly
programming language derived from C++ that permits a piece of software to run directly on many different
platforms. A platform consists of a combination of hardware and operating system that provides the basic
functionality of a computer. An example is the combination of some version of Microsoft's Windows operating
system and Intel's processors, often referred to as the Wintel platform.
Programmers traditionally develop a program for a specific platform. They would have to recode the program
completely for it to run on a different platform. But a programmer can write a program in Java, which operates
across platforms, and have it run anywhere. Java programs are not compiled directly into machine language,
but into an intermediate language called bytecode. This bytecode is then executed by a universal platform,

5
called the Java Virtual Machine (JVM), which sits atop a computer's regular platform. The JVM translates
compiled Java code into instructions that the platform underneath can understand. When you consider that
Java can run on many platforms, it is easy to see why it is relevant to Internet development; in fact, Java's
earliest incarnations were in Web applications. Web pages can include Java miniprograms, called applets,
which run on a Java platform included in the user's Web browser.

C#
A relatively new language, C# (pronounced "cee-sharp") is Microsoft's answer to Java. It has most of the same
advantages over C++ as does Java, but it is designed to work within Microsoft's .NET environment. The .NET
environment is designed for building, deploying, and running Web-based applications.
Many people referred to prior versions of Visual Basic as "object-oriented," because VB programs used
"objects" such as command buttons, dialog boxes, scroll-bars, and others. However, it wasn't until the current
version, VB.NET, that Visual Basic supported the concepts of inheritance and polymorphism, thus meeting the
criteria for a true object-oriented language.
PROGRAMMING METHODOLOGY
Programming can be done effectively by following a number of ways that are used to make sure the details
concerning a particular problem or situation are fully considered. When a programmer uses such methods, it
becomes clear that all the tasks involved in program code are included and thus making the objective of the
program to be achieved. Basically, a well developed program should lead to the accomplishment of the activity
or function as set in the identified problem to be solved or the specified situation being analyzed.
STEPS IN PROGRAM DEVELOPMENT
1. Generate program objectives
It involves forming a clear idea in terms of the information you want to include in the program, what
computations and the output. The programmer is guided by identifying a problem or situation faced by the
intended users and what they would require the program to do. At this stage, the programmer should think in
general terms, not in terms of some specific computer language
2. Design program
The programmer decides how the program will go about its implementation, what should the user interface be
like, how should the program be organized, how to represent the data and what methods to use during
processing. At this point, an algorithm is developed to assist in the actual programming so as to achieve the
desired results. A programmer should also be thinking generally although some of the decisions may be based
on some general characteristics of the C++ language or any other programming language in this matter.
NB: An algorithm is a logical sequence of steps that shows all the tasks or activities to be carried out by the
program or application
3. Write the program Code

6
It is the design Implementation by writing the actual code or instructions (based on the algorithm) using an
agreed programming language i.e. translating the program design into C++ language instructions. This is done
using C++’s text editor or any other editor such as notepad (though the later requires you to save your program
with the extension.cpp)
4. Compile the code
A compiler converts the source code into object code, which are instructions in machine language that can be
understood by the computer. Computers have different machine languages, only that compilers need to also
incorporate code for C++ libraries into the final program. The libraries contain standard routines. The end result
is an executable file that the computer can understand. The compiler also checks for both syntax and semantic
errors in the program and reports the errors to programmer for correction. The object code can never be
produced if the source code contains syntax errors.
5. Execute or run the program
This is the actual execution of the final code, usually preceded by the program linking 1#. Once the executable
code is complete and working, it can be invoked in future by typing its name in a ‘run’ command.
6. Test and debug the program
This involves checking whether the program or system software does what it is supposed to do. Programs may
have bugs (errors). Debugging involves the finding and fixing of program mistakes.
7. Maintenance and modification
Occasionally, changes become necessary to make to a given program. You may think of a better way to do
something in a program or add a clever feature or you may want to adapt the program to run in a different
machine. These tasks are simplified greatly if you document the program clearly and if you follow good design
practices.
8. Documentation of Software
This is the process of enlisting the details concerning the development, design, testing and the implementation
of the program application. Program documentation concerns details of the design and the development of the
program application. User manual is a documentation instructing a user on how to install and use the application
in the relevant area
MODES OF PROGRAMMING
Monolithic programming refers to the largely undisciplined and non formalized approach to the development
of a computer programs in which the programme is allowed a completely free rein. Programs produced in this
way reflect the programmer's own experience and personal interpretations.
Modular programming is the approach to programming that adopts a technique of developing suites of
related programs. The overall program is divided into parts or modules, each of which is developed separately

7
but on a coordinated basis. This enables the complete suite of programs to be prepared by the team of
programmers if appropriate and programs become available more quickly as a result.
Structured programming is an approach to writing programs that are easier to read, test, debug and modify.
The approach assists in the development of large programs through stepwise refinement and modularity.
Structured programming serves to increase programmer productivity, program reliability (readability and
execution time), program testing, program debugging and serviceability.
Macros – these are single instruction written as a part of a program that will generate many machine code
instructions. They are applications software commands which are batched to perform a certain task which is
performed frequently. When the usual task is to be performed, the invoking key to the macro is pressed and
the task is performed. They are also useful where a user defines own macros to facilitate the use of an
application package.

PROGRAMMING PARADIGMS
High level programming is the process of solving a problem in an abstract fashion, then writing that solution out
in code. The Procedure Oriented Programming (POP) and Object Oriented Programming (OOP) are basically two
different paradigms for writing code; more fundamentally, they are two different ways of thinking about and
modelling the problem's solution. The OOP deals with the elemental basic parts or building blocks of the
problem, whereas POP focuses on the steps required to produce the desired outcome.
Note: The language used for writing code does not determine if a program is Object Oriented or Procedural;
Object Orientation and Procedural, is a way of solving the problem or a way of thinking about the problem, not
the language used to write the code. It is possible to write Object Oriented Programs in C (I.e. POP language);
and a Procedural Oriented program in Java (i.e. an OOP language).
PROCEDURE ORIENTED PROGRAMMING (POP) TECHNIQUE
This is a programming paradigm where a structured method of creating programs is used. With POP, a problem
is broken up into parts and each part is then broken up into further parts, which are known as procedures and
are centrally controlled by a main program. A procedure call is used to invoke the procedure. After the sequence
is processed, flow of control proceeds right after the position where the call was made. Examples of procedure-
oriented languages are COBOL, FORTRAN, Pascal and C.
Example: Consider the problem: "calculate the month end closing balance for an account."
The process is take the starting balance, subtract all the debits and adds all the credits for the period and then
you arrive at closing balance. The key point for procedural programming is identification and articulation of the
process or steps that must be followed. In general terms, POP is a methodology for modelling the real world or
the problem being solved, by determining the steps and the order of those steps that must be followed in order
to reach a desired outcome or specific program state.
The general structure of a POP program is as shown in the figure (i) below:

8
Main Program

Function 1 Function 2 Function 3

Function 4 Function 5

POP Program Structure


The technique of hierarchical decomposition is used to specify the tasks to be completed for solving a problem.
In POP, the functions are inter-dependent as shown in figure (i) above, for instance: Function 4 depends on both
Function1 and Function2, hence any changes in Function 4 triggers modifications of Function1 and Function2. The
same applies for all other functions that are inter-dependent. In a multi-function program, the most important
data items are specified as global data in order to be accessed by all functions in the program. Each of the
functions in the program has its own local data.
The characteristics of POP technique are:
i) The emphasis is on algorithms
ii) The data moves openly around the system form one function to another
iii) The large programs are divided into smaller programs (i.e. functions)
iv) Most of the functions share global data
v) It uses the top-down approach in program design
The POP technique has the following limitations:
i) The POP does not model the real world problems very well because its functions are action-oriented,
hence the functions do not correspond to the elements of the problem.
ii) The programmers are forced to re-invent new solutions to old problems, because whenever an external
data structure is being modified, all the functions that access the data must also be revised.

OBJECT ORIENTED PROGRAMMING (OOP) TECHNIQUE


OOP is a methodology for modelling the real world (or at least the problem being solved), by decomposing the
problem into smaller discrete pieces called objects. What makes an object unique is the formal and explicit
combination these smaller pieces' behaviour with its data into a single entity. The object's behaviours are called
methods in OO terminology, while its data is called the Object's state. The OOP approach provides a way of

9
modularizing programs by creating partitioned memory area of both data and functions that can be used as
templates for creating copies of such modules on demand.
The OOP ties the data more closely to the functions that operate on it, and protects it from accidental
modification by external functions. The OOP allows the decomposition of a problem into a number of objects
and then builds data and functions around the objects.
The characteristics of OOP are as follows:
i) The emphasis is on data rather on procedure
ii) Programs are divided into objects
iii) Data is hidden and cannot be accessed by external functions
iv) Objects communicated with each other through functions
v) New data and functions can be easily added whenever necessary
vi) Functions that operate on the data of an object are tied together in the data structure
vii) Data structures are designed in such a way that they characterize the objects
viii) OOP uses the bottom-up approach in program design (i.e. the overall program development is based
upon the known characteristics of the individual modules.
The general organization of data and functions in an OOP program is as shown below:
OBJECT W OBJECT X

Data Data
Communication

Functions Functions

Functions

Data
OBJECT Y
General organization of data and functions

BASIC CONCEPTS OF OOP


Object: An entity having an interface that hides its data and sub-programs. It is a self-contained entity which has
an identity and characteristics of its own. An object may represent; a person, a place, a bank account, a table of
data or any item that the program has to handle. The programming problem is analyzed in terms of objects and
the nature of communication between them. Whenever the program is executed, the objects interact by sending
messages to one another.
Example: If a “Customer” and “Account” are two objects in a program, then the Customer object may
send a message to the Account object requesting for the account balance.

10
Class: This is a collection of objects of similar type which is used as a template to replicate a particular kind of
object. Classes are thus like cookie cutters: they are not cookies themselves, but are used to stamp out identical
cookies. Each different cookie cutter (class) produces a different shape of cookie (object). Once produced,
different cookies are independent of one another, even if they were made using the same cookie cutter.
Inheritance: The ability to create a new class by adding to or overriding parts of an existing class. The objects of
the new class acquire the properties of objects of another class. This concept supports the concept of
hierarchical classification (i.e. each derived class shares common characteristics with the class from which it is
derived). The inheritance concept provides the idea of re-usability (i.e. additional features can be added to an
existing class without modifying it).
Class Hierarchy: This refers to a set of classes and their interrelationships. It helps to picture class hierarchies to
be having super-class (parent class) at the top and the subclass (child classes) below.
Polymorphism: The ability to take more than one form. It can also be defined as the ability to use the same syntax
for objects of different types.
Example:
In some programming languages, the addition operation:
i) For two numbers generates a sum.
e.g.: 3 + 5 = 8,
ii) For two words generates a third string through concatenation of the wo
strings. e.g.:
Computer + Programming = ComputerProgramming
In OOP, polymorphism is used to describe variables which may refer at run time to objects of different classes.
A single function can be used to handle different number and different types of arguments. The usage of a
function to perform different types of tasks is referred to as overloading
Interface: This refers to a boundary across which two systems communicate. Polymorphism allows objects of
different internal structures to share the same external interface. This implies that a general class of operations
may be accessed in the same manner even though specific actions associated with each operation may differ.
Method: This refers to a procedure or routine associated with one or more classes.
Encapsulation: The ability to provide users with a well-defined interface to a set of functions in a way which hides
their internal workings. In OOP, this is the technique of keeping together data structures and the methods
(procedures) which act on them. This insulation of data from direct access by a program is known as data hiding
or information hiding.
Data Abstraction: refers to the act of representing essential features without including the background details
or explanations.

11
Private: This refers to either a variable or a method which is known only to its class. (i.e. Exclusive use in the
program.)
Public: If a method or variable is public, it is known to every part of the program. (i.e. General use in the program.)
Dynamic Binding: Refers to the linking of a procedure call to the code to be executed in response to the call. The
code associated with a given procedure call is not known until the time of the call at run-time.
Message Passing: This refers to the act of sending a message from one object to another. It involves specifying
the name of the object, the name of the function (message) and the information to be send
Example:
Employee . Salary (name)
Object Message Information
This concept enables the building of systems that directly model or simulate their real-world counter-parts.
BENEFITS OF OOP
 Redundant code can be eliminated
 The use of existing classes can be extended
 Data hiding helps in building secure programs
 It is easy to divide up the tasks of a project that is based on objects
 Possible to have multiple instances of an object to co-exist without any interference
 The data-cantered design approach enables the capturing of more details of a model in implementable
form.
 Object-oriented programs can easily be upgraded from small to large systems.
 The interface descriptions with external systems is made simple
 Programs can easily be made from the existing ones.

FLOWCHART DEVELOPMENT
The flowchart is a means of visually presenting; the flow of data through an information processing system, the
operations performed within the system and the sequence in which they are performed.
A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed in
obtaining the solution of a given problem. A well drawn flowchart can be used,
i) as a springboard for further discussion of the process
ii) to connect with other flowcharts explaining related activities
iii) to identify points where data can be usefully collected and analyzed
iv) to isolate possible problem areas
v) to communicate the process to those unfamiliar with it
vi) as a vital tool in programming of a problem
vii) As good program documentation which is needed for various purposes

12
1. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part

TYPES OF FLOW CHARTS


There are many different types of flowcharts with respect to different users, such as analysts, designers,
engineers, managers, or programmers. Flowcharts can be divided into four general types, namely:
i) Document flowcharts: showing a document flow through a system
ii) Data flowcharts: showing data flows in a system
iii) System flowcharts: showing controls at a physical or resource level
iv) Program flowchart: showing the controls in a program within a system
FLOWCHART SYMBOLS
A flowchart is drawn according to defined rules, and using standard flowchart symbols prescribed by the
American National Standard Institute (ANSI). Some of the flowchart symbols are shown below:
a) Start / Stop Symbol: this is depicted using an elliptical or a rectangle with rounded corners symbol

The word start or stop must be written inside the symbol


b) Process / Computational Symbol: This is represented using a rectangular symbol; and the type of the
process or computation is written inside the symbol

c) Input / Output Symbol: This is depicted by a parallelogram-like symbol as shown below

The type of input or output must be written inside the symbol


d) Decision Symbol: A decision – making point is represented using a diamond symbol.

13
The condition being evaluated at such a point must be written inside the symbol. Usually, the branching
points lead to several alternatives solutions paths
e) Connector Symbol: This is represented with a circular symbol, in which two parts of a program flowchart
join or connect:

f) Flow line: This is depicted by using a straight line with an arrow at the end. It shows the direction of flow
in a program.

g) Off – Page Connector: This symbol enables a programmer to connect to a flowchart that is continued
into a second or another page, and is shown using a trapezium

Besides these symbols other symbols are used to develop a flowchart depending on the nature of the program
to be represented using a flowchart
GUIDELINES FOR DRAWING A FLOWCHART
The following are some of the guidelines used during flowcharting
a. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.
b. The flowchart should be clear, neat and easy to follow. There should not be any room for ambiguity in
understanding the flowchart.
c. The usual direction of the flow of a procedure or system is from left to right or top to bottom.
d. Only one flow line should come out from a process symbol.

e. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible
answer, should leave the decision symbol.

<0 >0

14
=0

f. Only one flow line is used in conjunction with terminal symbol.

g. Write within standard symbols briefly. As necessary, you can use the annotation symbol to describe data
or computational steps more clearly.
h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow
lines. Avoid the intersection of flow lines if you want to make it more effective and better way of
communication.
i. Ensure that the flowchart has a logical start and finish.
j. It is useful to test the validity of the flowchart by passing through it with a simple test data.
FLOWCHARTING EXAMPLES
Example 1
a) Write an algorithm that can be used in calculating and outputting the sum of the first 35 natural
numbers
b) Convert the algorithm mentioned in (a) above into a flowchart
Solutions:
a) Algorithm
Step 1: Initialize the variables that include:
i) Counting Variable – this variable is for tracking the number of values entered. Let it be initialized as:
Count = 0
ii) Sum Variable – this is the variable on which the sum values are stored. Let it be initialized as: Sum
=0
Step 2: Reading of values. Let a value be represented by letter “X”
Step 3: Computing the sum; this process is represented as:
Sum = Sum + X
Step 4: Updating the counting variable; this is represented as:
Count = Count + 1
Step 5: Decision Point i.e. establishing whether the Count value is equal to 35
i) If NO, then go back to step 2 to read the next number

15
ii) If YES, go to step 6
Step 6: Output the total Sum
b) flowchart

16
c)
Start

Count = 0

Sum = 0

Read X

Sum = Sum + X

Count = Count + 1

NO
Is
Count =
35?

YES

Output Sum

Stop

17
Example 2
Draw a flowchart to find the largest of three numbers A, B and C.
Solution:

START

READ A, B C

YES NO
IS IS IS
YES B > YES
A> A>
C? B? C?

PRINT B PRINT C PRINT C PRINT A

STOP

LIMITATIONS OF USING FLOWCHARTS


1. Complex logic: sometimes, the program logic is quite complicated. In that case, flowchart becomes complex
and clumsy.
2. Modifications: if alterations are required the flowchart may require re-drawing completely.
3. Reliability: the essentials of what is done can easily be lost in the technical details of how it is done.
REVISION EXERCISE
1) State the advantages and disadvantages of using a flowchart
2) Explain the situations in which the flowcharts are found to be suitable tools
3) Write an algorithm and flowchart that can be used to:
i) Compute the product of two numbers
ii) Compute and display the sum and average of 124 numbers
iii) Determine and output the minimum of three given numbers

18
4) As a programmer, you are told to write a program for computing the sum of the first 20 positive integers.
The program is supposed to output the sum after computing
i) Write an algorithm for performing the above task
ii) Rewrite the above algorithm using the flowchart method
5) A supermarket is planning to give discounts to its customers based on the total costs of purchases made
by the customer. Discounts are given as follows:
- Total sales exceeding 5000/=, discount is 8%
- Sales greater than 3000/= and less than 5000/=, discount is 5%
- Sales greater than or equal to 1500/= and less than 3000/=, discount is 2%
- Sales less than 1500/=, no discount
Required: Develop an algorithm and draw up a flowchart for a program that can be used to control this process

19

You might also like