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

lOMoARcPSD|32867904

SMA 191 Computer Programming

computer science (Kenyatta University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)
lOMoARcPSD|32867904

KENYATTA UNIVERSITY

A MODULE FOR:

SMA 191: COMPUTER PROGRAMMING


AUTHOR

ABRAHAM MATHEKA: PhD (IT), MSc (IS), BSc(IT)Bed(Sc), Diploma (IT)


Email: mutua.abraham@ku.ac.ke

INTRODUCTION

PREFACE
The history of Computer programming can be traced back to the inventions of early
computers. Computer programming is a field that is characterized by a lot of dynamism. The
frequent changes in the programming software technologies are attributed to the ever
changing work methods in the various fields. Some of the fields where Computer
Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)
Programming is applied include Business, Education, Scientific, Military, Artificial
lOMoARcPSD|32867904

COURSE OBJECTIVES

At the end of the course, learners will be:

i) Equipped with necessary knowledge and skills in the field of Computer Programming
ii) Provided with the main concepts used in the field of Computer Programming
iii) Provided with simplified knowledge in programming in recognition of the diverse
academic background of the business students
iv) Prepared to innovate various business requirements into software application

TABLE OF CONTENTS

INTRODUCTION......................................................................................................................2
OBJECTIVES............................................................................................................................2

Committed to Creativity, Excellence and Self – Reliance Page 2 of


94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

TABLE OF CONTENTS...........................................................................................................3
1: INTRODUCTION TO COMPUTER PROGRAMMING.................................................7
1.1.1 BASIC CONCEPTS OF PROGRAMMING...........................................................8
1.2 NECCESITY OF PROGRAMMING..........................................................................8
1.3 DUTIES OF A COMPUTER PROGRAMMER.........................................................9
1.4 STAKEKOLDERS IN A CORPORATE ENVIRONMENT.......................................9
1.5 CHARACTERISTICS OF GOOD PROGRAMMING LANGUAGE.......................9
1.6 MODES OF PROGRAMMING................................................................................10
1.7 ACTIVITIES.............................................................................................................10
2: OVERVIEW OF COMPUTER PROGRAMMING LANGUAGES............................11
2.1 GENERATIONS OF PROGRAMMING LANGUAGES.........................................12
2.1.1 FIRST GENERATION LANGUAGES.............................................................12
2.1.2 SECOND GENERATION LANGUAGES........................................................12
2.1.3 THIRD GENERATION LANGUAGES............................................................12
2.1.4 FOURTH GENERATION LANGUAGES........................................................12
2.1.5 FIFTH GENERATION LANGUAGES.............................................................12
2.2 OVERVIEW OF PROGRAMMING LANGUAGES...............................................12
2.2.1 FORTRAN.............................................................................................................13
2.2.2 COBOL (1959)......................................................................................................14
2.2.3 BASIC (1964)........................................................................................................14
2.2.4 PASCAL (1971).....................................................................................................14
2.2.5 PROLOG (1972)....................................................................................................15
2.2.6 C LANGUAGE (1972)..........................................................................................16
2.2.7 ADA LANGUAGE (1983)....................................................................................16
2.2.8 C++ LANGUAGE (1983).....................................................................................17
2.2.9 HYPER TEXT MARKUP LANGUAGE..............................................................17
2.2.10 JAVA (1991).......................................................................................................18
2.2.11 PYTHON (1991)................................................................................................18
2.2.12 VISUAL BASIC (1991).....................................................................................19
2.3 ACTIVITIES.............................................................................................................19
3: PROGRAMMING LANGUAGES EVALUATION CRITERIA.................................21
3.1 INTRODUCTION EVALUATION CRITERIA..........................................................22
3.2 FACTORS FOR EVALUATION CRITERIA...............................................................22

Committed to Creativity, Excellence and Self – Reliance Page 3 of


94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

3.2.1 SUPPORTS TARGET APPLICATION DOMAIN................................................22


3.2.2 PROGRAM READABILITY................................................................................22
3.2.3 INDUSTRIAL ACCEPTANCE............................................................................23
3.2.4 OBJECT-ORIENTED SUPPORT.........................................................................23
3.2.5 PROGRAM WRITABILITY.................................................................................23
3.2.6 DEVELOPMENT ENVIRONMENT....................................................................24
3.2.7 PROGRAMM RELIABILITY:.............................................................................24
3.2.8 FULL-FEATURED LANGUAGE........................................................................24
3.2.9 SOFTWARE COST...............................................................................................25
3.2.10 SUPPORT FOR SECURE CODE.........................................................................25
3.2.11 PROGRAM PORTABILITY................................................................................25
3.2.12 SUPPORT OF WEB DEVELOPMENT...............................................................25
3.2.13 PROPRIETARY / OPEN SOURCE.....................................................................26
3.3 ACTIVITIES.............................................................................................................26
4: APPROACHES TO PROGRAMMING.......................................................................27
4.1 DEFINITIONS OF BASIC TERMS.........................................................................28
4.2 PROGRAMMING PARADIGMS.................................................................................29
4.2.1. PROCEDURE ORIENTED PROGRAMMING TECHNIQUE................................30
4.2.2. OBJECT ORIENTED PROGRAMMING TECHNIQUE.........................................31
4.3 BASIC CONCEPTS OF OOP...................................................................................32
4.4 BENEFITS OF OOP......................................................................................................34
4.5 ACTIVITIES.............................................................................................................35
5: PROGRAMMING METHODOLOGY........................................................................36
5.1 STEPS IN PROGRAM DEVELOPMENT...............................................................37
5.2 FLOWCHART DEVELOPMENT............................................................................38
5.2.1 TYPES OF FLOW CHARTS................................................................................38
5.2.2 FLOWCHART SYMBOLS...................................................................................39
5.3 DRAWING FLOWCHART GUIDELINES..............................................................40
5.4 FLOWCHARTING EXAMPLES.............................................................................41
5.4.1 LIMITATIONS OF FLOWCHARTS....................................................................43
5.5 ACTIVITIES.............................................................................................................44
6: C++ PROGAMMING LANGUAGE............................................................................45
6.1 BASICS OF C++.......................................................................................................46

Committed to Creativity, Excellence and Self – Reliance Page 4 of


94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

6.2 CHARACTERISTICS OF C++ PROGRAM............................................................46


6.3 STRUCTURE OF C++ PROGRAM.........................................................................47
6.4 CREATING C++ SOURCE FILE.............................................................................48
6.5 FEATURES OF C++ PROGRAM............................................................................48
6.6 GUIDELINES TO C++ PROGRAMMING..............................................................49
6.7 PROGRAMMING IN C++.......................................................................................50
6.8 ACTIVITIES.............................................................................................................51
7. IDENTIFIERS, VARIABLES AND CONSTANTS.....................................................52
7.1 IDENTIFIERS..........................................................................................................53
7. 2 VARIABLES............................................................................................................53
7.2.1 SIZE OF VARIABLES......................................................................................53
7.2.2 SIGNED AND UNSIGNED INTEGERS..........................................................54
2.3 DEFINITION OF VARIABLE..................................................................................54
2.4 CREATION OF VARIABLES..................................................................................55
2.5 ASSIGNING VALUES TO VARIABLES................................................................55
7.2.3 TYPEDEF..........................................................................................................56
7.3 CONSTANTS...........................................................................................................56
7.3.1 TYPES OF CONSTANTS.................................................................................56
7. 3. 2 DEFINING CONSTANTS WITH #define.....................................................57
7.3.3 DEFINING CONSTANTS WITH const............................................................57
7.3.4 ENUMERATED CONSTANTS........................................................................58
7.4 ACTIVITIES.............................................................................................................59
8: PROGRAM CONTROL STRUCTURES.....................................................................60
8.1 INTRODUCTION TO CONTROL STRUCTURES....................................................61
8.2 SEQUENCE CONTROL STRUCTURE..................................................................61
8. 2 SELECTION CONTROL STRUCTURE.....................................................................62
8.2.1 IF-ELSE STATEMENT....................................................................................62
8.2.2 SWITCH STATEMENT...................................................................................64
8. 3 LOOP STRUCTURE................................................................................................67
8.3.1 DO-WHILE CONTROL STRUCTURE............................................................67
8.3.2 WHILE CONTROL STRUCTURE...................................................................68
8.3.3 FOR CONTROL STRUCTURE........................................................................69
8.3.4 BIFURCATION STRUCTURES.......................................................................70

Committed to Creativity, Excellence and Self – Reliance Page 5 of


94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8. 4 ACTIVITIES.............................................................................................................72
9. ARRAYS IN C++.............................................................................................................73
9.1 INTRODUCTION TO ARRAYS..................................................................................74
9.2 DECLARATION OF ARRAYS................................................................................74
9.3 INITIALIZATION OF ARRAYS..............................................................................75
9.4 MULTIDIMENSIONAL ARRAYS..........................................................................76
9.5 ACTIVITIES.............................................................................................................78
10. FUNCTIONS IN C++ PROGRAM..............................................................................79
10.1 INTRODUCTION TO FUNCTIONS...........................................................................80
10.2 DECLARATION OF FUNCTIONS.........................................................................80
10.3 DEFINITION OF A FUNCTION.............................................................................81
10.4 ARGUMENTS OF A FUNCTION...........................................................................81
10.5 RETURN VALUES..................................................................................................82
10.6 ACTIVITIES.............................................................................................................82
11. CLASSES AND OBJECTS IN C++.............................................................................83
11.1 BASICS OF C++ CLASSES.................................................................................84
11.2 DECLARATION OF A CLASS............................................................................84
11.3 CREATION OF OBJECTS....................................................................................85
11.4 ACCESSING CLASS MEMBERS.......................................................................86
11.5 DEFINITION OF MEMBER FUNCTIONS.........................................................86
11.5.1 OUTSIDE CLASS DEFINITION..................................................................86
11.5.2 INSIDE CLASS DEFINITION......................................................................87
11.6 ACTIVITIES.............................................................................................................89
REFERENCES.....................................................................................................................90

Committed to Creativity, Excellence and Self – Reliance Page 6 of


94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

1: INTRODUCTION TO COMPUTER PROGRAMMING

This topic introduces the basic computer programming concepts, explains the necessity for
programming, duties of computer programmer, the stakeholders in the programming
environment and the various modes of programming

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Define basic concepts of computer programming


ii) Explain the necessity for computer programming
iii) State the duties of a computer programmer in an organization
iv) Identify various stakeholders in the computing environment
v) Describe characteristics of good programming language
vi) Explain the various modes used in computer programming

SUBTOPICS

 Basic concepts of computer programming


 Necessity for computer programming
 Duties of computer programmer
 Stakeholders in the computing environment
 Characteristics of good programming language
 Modes of computer programming
Committed to Creativity, Excellence and Self – Reliance Page 7 of
94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

1.1.1 BASIC CONCEPTS OF PROGRAMMING

There are many user applications that are done using a computer as a supporting tool to
accomplish a particular task. Any task or activity that is done using a computer is based on a
program that has been designed and written for that activity. There are other activities that
can be programmed depending on the user changing needs or due to emerging areas that
necessitates such work to be programmed

Computer is an electromechanical device that uses programs (set of instructions) to accomplish


particular task or activity. Computers can be instructed using a program or even natural
language such as English. However, to achieve that the commands or the instructions must be
translated into a form that the machine will understand, in order to perform the desired function.

A program is a set of laid down instructions that have to be coded and mounted onto a computer
in order that when executed, the expected function is performed.

Programming is the process of translating of user ideas into a representation or a form


(program) that a can be understood by the computer by use of an accepted tool or programming
language.

Programming languages are tools that facilitate the transformation and representation of the
logics or user ideas into a form that the computer can understand and hence execute the ideas or
instructions. The programming languages differ in their features and the level of the
representation of the solution to the computer hardware

Translation process continues when the computer accepts source code as input and produces
object code as output which is machine – dependent or readable code. Computer output is
further translated into machine code- the actual instructions that drive micro coded logic in the
C.P.U.

Computer programming is the act of writing special set of instructions that guide a
computer in performing pre-determined tasks. These instructions can be specified in one or
more programming languages, which include, C, C++, Java, BASIC, Ada, PROLOG,
among others. In executing the various tasks, a computer goes through a series of steps
whose purpose is to achieve.

1.2 NECCESITY OF PROGRAMMING

By learning computer programming, programmers are enabled to:


1. Gain skills on how to solve problems drawn from variety of problem domain fields.
2. Become better acquainted with different types of information systems.
3. Enhance their capacity in advising the management concerning issues related to
business information systems

Committed to Creativity, Excellence and Self – Reliance Page 8 of


94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

4. Familiarize themselves with the new emerging technologies in order to put them to
optimal use.

1.3 DUTIES OF A COMPUTER PROGRAMMER

 Trains software users within an organization


 Advises the management about software-related matters
 Maintains updated documentations and records about the corporate software
 Evaluates and modifies the existing software
 Designs and develops computer programs in a business organization

1.4 STAKEKOLDERS IN A CORPORATE ENVIRONMENT

 Computer programmer: This is the person who develops software solutions that meet
the business needs of an organization
 Systems Analyst: His main role is to oversee the development of information systems
that adequately address the business needs of an organization. The analyst collects
requirements of the proposed information system from the users and proprietors, and
captures them into a requirements specification document. In relation to the
development of information systems, she's/he's the equivalent of an architect in a
building industry.
 Proprietor / Owner: This is the person who owns the business organization. The
proprietor provides the business knowledge, initiates and funds the software
development
 Software Vendor / Consultant / Expert: This is a person who offers valuable advice
about numerous types of software.

1.5 CHARACTERISTICS OF GOOD PROGRAMMING LANGUAGE

 Simplicity – ease to learn and use that affects the readability of programs written in any
language
 Naturalness – fit in the application area for which it has been designed and provide
appropriate operators, data and control structures and the syntax to facilitate coding of
problems easily and efficiently
 Abstraction – ability to define and use complicated structures or operations in ways that
allow many details to be written
 Efficiency – efficiently translated into machine code, executed and acquire as little space in
memory as possible
 Structuredness - have the necessary features to allow users to write programs based on the
concept of structured programming
 Compactness – programmers be able to express intended operations concisely without
verbose / wordy language use
 Locality – the need not to jump around visually when programming / preparing the text of
the program, thus concentrate around the problem currently being worked on

Committed to Creativity, Excellence and Self – Reliance Page 9 of


94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

 Extensibility – allow for the extension through simple, natural and elegant mechanisms by
providing sub-program definitions and their purposes
 Suitability – language to suit its environment with respect to program applications e.g. real
time applications, batch mode processing etc

1.6 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 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.

1.7 ACTIVITIES

1. State the duties of a Computer Programmer in a corporate environment


2. State and explain the factors that necessitate software changes in a business
environment
3. Explain the relevance of computer programming to business environment
4. Mention the drivers behind the evolution that has led to the global programming
communities to move from one generation of programming languages to another
5. A Programmer was heard saying “Free Open Source Software (FOSS) will soon drive
Committedout the proprietary
to Creativity, software
Excellence and Selffrom the global software market”
– Reliance Page 10
i) Define the term FOSS of 94
ii) Discuss the above statement

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

2: OVERVIEW OF COMPUTER PROGRAMMING LANGUAGES

This topic introduces the generations of computer programming and an overview of selected
computer programming languages

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Identify various generations of computer programming language


ii) Describe characteristics features of selected programming language

SUBTOPICS

 Generations of computer programming languages


 Overview of selected computer programming languages

Committed to Creativity, Excellence and Self – Reliance Page 11


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

2.1 GENERATIONS OF PROGRAMMING LANGUAGES

Due to the dynamism of computer programming, the syntax of the programming


languages has become easier to understand and more human – readable in each of the
language generation. There are five computer language generations, namely:

2.1.1 FIRST GENERATION LANGUAGES


The First generation languages (1GLs) signify the early, primitive computer languages. These
languages consisted entirely series of Ones (1's) and Zeroes (0's), and are at times known as
machine languages because they are the actual languages that the computer understands.

2.1.2 SECOND GENERATION LANGUAGES

The second generation languages (2GLs) languages represent a step up from the first
generation languages that consisted entirely of 1's and 0's because they allow for the use of
symbolic names and are at times known as assembly languages. The code written in an
assembly language is converted into machine language in order for the execution to take
place.

2.1.3 THIRD GENERATION LANGUAGES

Third generation languages (3GLs) are computer programming language generation that
introduced new languages whose syntax was much easier to understand. This was a step
up from assembly language which only allowed for symbolic names and numbers. The
3GLs allows for the use of words and commands instead of just symbols and numbers.
The 3GLs are also known as "high level languages" and include various languages such as
C, C++, and java, among others.

2.1.4 FOURTH GENERATION LANGUAGES

The Fourth generation languages (4GLs) paved the way for syntax that is very close to
human language, closer to human language than any language of the previous generations.
Fourth generation languages are typically used to access databases. Some fourth
generation languages include Structured Query Language (SQL) and ColdFusion.

2.1.5 FIFTH GENERATION LANGUAGES


The Fifth generation languages (5GLs) are currently being used for artificial intelligence and
neural networks. A neural network is a form of artificial intelligence that attempts to imitate
how the human mind works. The following are some of most popularly used programming
languages:

2.2 OVERVIEW OF PROGRAMMING LANGUAGES

Committed to Creativity, Excellence and Self – Reliance Page 12


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

This section discusses the basic characteristics of selected programming languages especially
on the basis of the areas of applications in which the resulting software is put into use so as to
support the operations of a specific business organization

2.2.1 FORTRAN

FORTRAN is a short form of FORmula TRANslator. This was the first major language to
be developed. FORTRAN was designed by International Business Machines (IBM) for
scientific computing.

FORTRAN I (1957)

The components were very simple, and provided the programmer with low-level access to
the computers innards. It included the IF, DO, and GOTO statements, which were a major
step forward when it was released. Data-types in use by today's languages got their start in
FORTRAN. These included the logical variables (TRUE or FALSE), and numerical
variables (integer, real, and double-precision numbers). The first FORTRAN compiler was
a milestone in the history of computing. At the time of its development, computers had
very small memories (on the order of 15KB, it was common then to count memory
capacities in bits), were slow, and had very primitive operating systems, if they had them
at all. The pioneers of FORTRAN produced the first successful High Level Language
(HLL) which is still widely used, and an optimizing compiler that produced very efficient
code. FORTRAN was very portable and was adopted by the scientific and military
communities, where it was used extensively in the Space Program and military projects.

FORTRAN II & III (1958)

Adding the capability for separate compilation of program modules, FORTRAN II was a
significant improvement. Although it was never released, FORTRAN III made it possible
to use assembly language code right in the middle of FORTRAN code. Note: Attachment
of such assembly code can be more efficient, but the advantages of an HLL such as
portability and ease of use are lost.

FORTRAN IV (1961)

Due to the fact that FORTRAN III was never implemented, it caused the version in use to
jump from FORTRAN II to FORTRAN IV when it was released in 1961. This FORTRAN
version improved a significant number of features and eliminated some machine-
dependant language irregularities. A FORTRAN II to FORTRAN IV translator was used to
retain backward compatibility with earlier FORTRAN programs.

FORTRAN (1966)

The new ASA standard was published in 1966, and was known accordingly as FORTRAN
(66). This was a very important step that made it worthwhile for vendors to produce
FORTRAN systems for every new computer, making FORTRAN an even more popular

Committed to Creativity, Excellence and Self – Reliance Page 13


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

High Level Language. Although the original development of the standard began in 1962, it
was still be the first HLL standard in the world after four years later.

2.2.2 COBOL (1959)

COBOL is a short form of COmmon Business-Oriented Language. Although FORTRAN


was good at handling numbers, it was not so good at handling input and output, which
mattered to most business computing. When business computing began to take off in
1959, COBOL was developed to fill the need that FORTRAN could not. The only data
types provided for in this language were numbers and strings of text. It allowed for these
to be grouped into arrays and records so that data could be tracked and organized better.
COBOL statements have a very English-like grammar, making it quite easy to learn,
especially for the business men for which it was designed. A COBOL program normally
consists of four divisions, namely:

 Identification Division: This section specifies the program’s author, owner,


date etc.

 Environment Division: Purpose of this division is to make programs more


portable by forcing the programmer to enumerate all resources and facilities
that the program would require in one place.

 Data Division: The variables used in the program are declared in this section

 Procedure Division: The functions to be used in the program are declared in


this section.

The language is very often employed along with a database, and most implementations
include extensive database support. COBOL's support for complicated calculations is
modest.

2.2.3 BASIC (1964)

The Beginners All-purpose Symbolic Instruction Code (BASIC) was designed to be an


easy first language for programming beginners, especially those who weren't "computer-
science" oriented. Though the first version was compiled, most Basic systems were
interpreted. Original Basic had a simple syntax that included a line number for every
source line. Control structure mostly consisted of: GOTO and GOSUB statements and
Simple conditional and bounded loop constructs. Original Basic provided for numeric,
string, and array data types, but no structures or objects. Basic has enjoyed steady
popularity and usage since about 1965, and has evolved greatly since then. Basic was and
still is loosely typed, and has poor support for enforcing program portability.

Committed to Creativity, Excellence and Self – Reliance Page 14


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

2.2.4 PASCAL (1971)

It was first published in 1971 and I was meant to be used mainly as a good teaching tool.
Pascal features strong type checking, simple I/O facilities, a good set of primitive data
types, arrays, fixed and variant records, conventional control structures, and simple
dynamic memory management. Pascal requires discipline from the programmer: all types,
data, and subroutines in a Pascal program must be declared prior to use. Everything is
lexically scoped, to allow for maximum compile-time type checking. The language has
good support for programmer-defined data types and subtypes, which are also subject to
strong checking. Structure of a Pascal block is somewhat rigid; elements must appear in a
certain order preceded by their identifying keyword: labels, constants, types, variables and
functions, then body code.

The choice of features and the limited external interface facilities helped make Pascal very
portable. However, didn't include strings, only arrays of characters, and very small
complement of built-in utility functions. These omissions led developers of Pascal
language implementations to add extensions to help programmers accomplish real work.
Unfortunately, every vendor's extensions were more-or-less proprietary, hence the Pascal
language lost some of its portability. Amazingly, while it is very strict in most ways,
Pascal still supports a 'goto' statement. Pascal does not support object-oriented
programming, persistence, or multi-tasking

During the 1970s and 1980s, Pascal became fairly widely used, especially in the early
days of the IBM PC and the Macintosh. A great many students of computing in the 80s cut
their teeth on Pascal programs. Both free and commercial Pascal compilers exist. The
most popular commercial compiler, and online language implementation, is "Turbo
Pascal" from Borland. Pascal is normally compiled, either to machine or virtual machine
byte codes of some sort. Source-level

Pascal interpreters also exist, and translators from Pascal to other languages. One of the
most interesting aspects of Pascal is its relative poverty of features. Compared to its rough
contemporary PL/I, Pascal is a tiny language. This contrast helped frame a debate that has
raged in computer science circles ever since: should languages be kept small and simple
(with complex facilities provided by external libraries), or should they be made large and
complex to provide all features that programmers require. Many later block-structured and
object-oriented language designers would be forced to choose one of these two camps.
Oberon, for example, is small and spare, depending on libraries for advanced features.
Perl, in contract, is complex and loads many useful features in the language itself. Recent
languages like Java adopt a compromise position: keep the language simple, but
standardize the supporting libraries to prevent incompatible implementations. In most
programming areas, Pascal has been superseded by newer, object-oriented languages, such
as C, C++, and Java.

2.2.5 PROLOG (1972)

Committed to Creativity, Excellence and Self – Reliance Page 15


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

PROLOG stands for PROgramming in LOGic; and it is applicable in computer science area
that is concerned with languages and systems for logical inference, proof techniques and very
high level programming systems. A prolog program can accomplish amazing things with a
short amount of code. A typical prolog program consists of a set of facts and a set of rules that
specify how to satisfy goals related to those facts. Prolog supports a small but rich variety of
data types that include numbers, strings, symbols, lists and composite objects that are
analogous to records

By attempting to answer the questions, the prolog system examines facts, invokes rules and
may manipulate data or perform computations. The programmer does not directly control the
execution sequence of the prolog system as it seeks to satisfy a goal, although the
programmer can exert some influence, in this sense prolog must be considered a declarative
language and not a procedural one.

Prolog is among one of the computer programming systems to employ the logical formalism
of unification. It also utilizes recursive goal seeking with backtracking and forward chaining
– which are common Artificial Intelligence (AI) techniques. Unfortunately, the unification
and backtracking can be computationally expensive; and that early prolog implementations
were very slow. The logic programming such as the prolog has been proposed as the basis for
the 5th generation computing: a vision of massively parallel computers providing for true
Artificial Intelligence

2.2.6 C LANGUAGE (1972)

This language has a good support for systems programming and has a fair arithmetic support,
simple data structures, subroutines, conventional flow control structures, simple but useful
input – output (I/O) facilities and a powerful macro pre-processor. The C language was
developed for the Unix Operating System that was being created around the time. Although
there is no direct link between C and Pascal, all of the features that made Pascal so popular
were included in C along with CASE statements. The C language was made fast and
powerful at the expense of being hard to read. Nonetheless, the improvements it had over the
Pascal started a major wave of change from former Pascal users

The C is a powerful language for writing tight, fast and highly tuned code in a language far
more portable than the assembly language. C is low level enough to write Graphical User
Interface (GUI) libraries. Primitive data types supported in the modern C are: several sizes of
integers, characters, pointers and arrays. The American National Standards Institute (ANSI) C
standard, created in 1990 defines better data type handling and subroutine declarations for C.
The C language became extremely popular in academic and industrial computing from the
late 1970s through to early 1990s; where even today it still enjoys a huge user community.
The influence of C and UNIX on each other and the pair of them on the rest of computing
cannot be underestimated. C also had a profound impact on the World Wide Web (WWW), as
the first web servers and web clients were all written in C.

2.2.7 ADA LANGUAGE (1983)

Committed to Creativity, Excellence and Self – Reliance Page 16


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

The Ada language was originally designed with the intentions to support large scale
programming and to promote software reliability. The language has many Object – oriented
programming features that include: nested procedures, nested packages, strong typing, multi-
tasking, generics, exception handling and abstract data types

Ada is fairly a complex language that has a conventional but very rich Pascal – like syntax,
with many specialized features. The best aspects of Ada are:

 It supports for generics or templates


 It supports for task synchronization
 It has a very good exception handling

The worst features of Ada language are: It has complex syntax and poor performance of the
code generated by most early compilers. The primitive data types supported by the Ada
include: a variety of numeric types, Booleans, characters, references and enumerated
symbols. With its emphasis on program safety and type enforcement it is strictly applied both
within and between modules. Ada is very strictly standardized and well documented as a
language. Ada compilers undergo stringent validation with an official test suite

2.2.8 C++ LANGUAGE (1983)

The C++ is a fairly complicated Object-Oriented (OO) language derived from C. The C++
language was first released out in 1983 although it was finally standardized by the ISO
and ANSI in 1997. The syntax of C++ is a lot like C, with various extensions and extra
keywords needed to support classes, inheritance and other OO features. The C++ was
originally developed as an extension to C, but quickly evolved into its own language.
Despite some of the flaws it has inherited from C, C++ is a very popular language for
application development on UNIX systems.

The C++ programming language offers a very broad range of OOP features, such as:

 Multiple inheritance

 Strong typing

 Dynamic memory management

 Polymorphism

 Exception handling and overloading

Some newer C++ systems also offer run-time type identification and separate namespaces.
Because of this, C++ is one of the most mature and certainly the most widely-
implemented object-oriented language. However, it is missing some features that are
considered obligatory in a new OOP language design, such as: concurrency, persistence,
automatic garbage collection, and reflection. C++ also supports the usual features
expected of an application language: a variety of data types including strings, arrays and

Committed to Creativity, Excellence and Self – Reliance Page 17


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

structures, full I/O facilities, data pointers and type conversion. The C++ Standard
Template Library (STL) offers a set of collection and abstract data type facilities.

2.2.9 HYPER TEXT MARKUP LANGUAGE

The Hyper Text Markup Language (HTML) is the core language of the World Wide Web
and is used to define the structure and layout of web documents by using various tags and
attributes. Although a fundamental language of the web, HTML is a static language -
content created with it does not change. HTML is used to specify the way web pages look,
not how they function.

2.2.10 JAVA (1991)

This is a powerful and flexible language that can be used to create applets that run inside
web pages. An applet is a program that is executed from within another program. Applets
created by Java can be used for many tasks such as displaying graphics, getting input from
the user, and playing sounds. Java is often confused with Javascript, but they are two
different languages. According to its designers, Java was intended to be:

 Object – Oriented, Robust and Secure

 Fairly architecture neutral and Portable

 High-performance: Its performance is poor, but new JVM implementations that


employ just-in-time compilation are helping to improve Java's speed.

 Dynamic: Java is fairly dynamic, but not as much so as other interpreted languages
like LISP or Perl.

Java security is better than many other embeddable languages, but still has significant
problems to overcome, both in its security model and in various implementations. The
fundamental structural component of a Java program is the class. All data and methods in
Java are associated with some class, there is no 'global' data or functions as in C++.

JavaScript Language

This language was developed to provide dynamic and interactive content on web pages.
With Javascript it is possible to communicate with HTML, create animations, create
calculators, validate forms, and more. Unlike Java language, which can be used to develop
entirely standalone applications, JavaScript works primarily with Web pages. JavaScript
has object-oriented features. The syntax of JavaScript is similar to that of C or Java, but
simpler and not as rich. In Javascript, any variable can contain data of any type, and
conversion is mostly automatic. The language definition includes extensive facilities for
controlling and manipulating parts of web pages. The present versions of Javascript
include a complicated security model for restricting the hostile capabilities of scripts
embedded in web pages.

Committed to Creativity, Excellence and Self – Reliance Page 18


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

2.2.11 PYTHON (1991)

This language is an extension of object-oriented language and is intended to be: Highly


effective, Easy to use, Extensible, and provide for very simple and statement-oriented
syntax. Python supports a good set of primitive and composite data types: integers, floats,
complex numbers, strings, lists, and associative arrays (dictionaries). Data values are
typed, but strong type checking is not enforced. Python supports a conventional set of
flow-control constructs: if-then, while and for loops. Python supports subroutines,
independent modules, and object classes.

2.2.12 VISUAL BASIC (1991)

As a language, Visual Basic has evolved enormously since its commercial introduction in
1991 by Microsoft. VB is an advanced structured dialect of Basic that is intended for
application development. The "Visual" in the name Visual Basic does not really refer to
the language, but to the development environment. The VB integrated development
environment that Microsoft distributes has extensive facilities for on-screen design of
graphical user interfaces: dialog boxes, window interfaces, menus, etc. It also provides a
rich but complicated interface for code management and debugging. Graphical User
Interface (GUI) programs are easy to write in Visual Basic, and the development
environment provides copious support for coding the necessary event handling
subroutines.

The syntax of Visual Basic is similar to that of other modern Basic dialects, but with many
additional features. The following primitive data types are supported: integers, reals,
strings, booleans, currency, dates, and object references. Variables may be declared, but
need not be. Composite data types include arrays and user-defined records. Control
structures include various conditional and iteration constructs, and rudimentary error
handling mechanisms. Memory management in Basic is automatic. Visual Basic is
nominally an interpreted language, but newer implementations include native code
compilers. During execution, Visual Basic programs are normally supported by a run-time
library. The popularity of Visual Basic is derived partly from its extensibility. New
components, especially GUI elements, can be added to the language run-time system and
transparently used by application developers.

2.3 ACTIVITIES

1) Describe the reasons behind the C++ language stating some of the similarities and
differences between it and the C language
Committed to Creativity,
2) State Excellence
the factors and Self
behind the– Reliance Page 19
popularity of each of the following programming
of 94
languages: Ada; Java; Python; BASIC; FORTRAN; COBOL
3) Explain why it is advisable for a Computer Programmer to be proficient in several
programming languagesDownloaded by Liffer Mongare (mongarewyclif2@gmail.com)
lOMoARcPSD|32867904

Committed to Creativity, Excellence and Self – Reliance Page 20


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

3: PROGRAMMING LANGUAGES EVALUATION CRITERIA

This topic discusses the programming language evaluation criteria and elaborates on various
factors that are considered in the process of evaluating a given programming language,
computer software or an information system

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Describe the steps followed for programming language evaluation


ii) Explain the various factors used for programming language evaluation

SUBTOPICS

 Introduction to evaluation criteria


 Factors for evaluation criteria

Committed to Creativity, Excellence and Self – Reliance Page 21


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

3.1 INTRODUCTION EVALUATION CRITERIA

Whenever solving a problem that requires development of a software solution, the


programmers are faced with a challenging task of justifying their programming language of
choice in coming up with the solution. The following are the steps followed in selecting a
programming language from a list of several other languages in any given situation:

 Appoint the technical team of software evaluators


 Conduct a preliminary study
 Identify the important language features to be considered
 Weight each of the features to be considered in the criteria
 Compile a list of candidate programming languages
 Evaluate each of the languages as per the agreed selection criteria.
 Rank the languages and select the overall best if found to be the most suitable as per the
prevailing situation.

3.2 FACTORS FOR EVALUATION CRITERIA

The following are the factors considered by computer programmers when evaluating
programming languages:

3.2.1 SUPPORTS TARGET APPLICATION DOMAIN

This is sometimes also referred to as “problem domain,” and is included to assess how well a
programming language supports programming for specific applications.

Examples:

 FORTRAN’s support for scientific programming


 COBOL’s support for business data processing
 RPG’s support for report generation

3.2.2 PROGRAM READABILITY

This feature refers to the ease with which programs written in a given programming language
can be can be read and understood. Readability is an important measure of the quality of
programs and programming languages. The learning curve associated with each language or
IDE differs greatly between languages.

The following characteristics contribute to the readability of a programming language:

Committed to Creativity, Excellence and Self – Reliance Page 22


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

 Overall simplicity: A language that has a large number of basic components is more
difficult to learn than one with a small number of basic components

 Data types and structures: The presence of adequate facilities for defining data types
and data structures in a language is very significant in enhancing the readability.

 Syntax considerations: The syntax (i.e. language rules) of a programming language has
great effect on the readability of computer programs. In addition to ease of learning, the
language must be characterized by concise syntax and straightforward semantics

 Control statements: These are statements that control the execution of computer
programs e.g. a program that can be read from top to bottom is much easier to
understand than another that requires the reader o jump from one statement to some
non-adjacent statement in order to follow the execution order. The most obvious recent
example is the steep increase in the learning curve from Visual Basic 6 to Visual
Basic.Net. Basic concepts include the sequence, selection, and iteration control
structures, as well as arrays, procedures, basic input /output, and file manipulation

3.2.3 INDUSTRIAL ACCEPTANCE

The industrial acceptance refers to the popularity of a programming language in the wider
corporate environment. Industrial acceptance can also be referred to as industrial relevance of
a programming language, which can be assessed based on current and projected usage at
other companies, as well as the number of current and projected positions among other
languages.

3.2.4 OBJECT-ORIENTED SUPPORT

This is an assessment on how well a programming language supports basic object-oriented


(OO) concepts like abstraction, polymorphism, inheritance, and encapsulation. The evaluator
should consider that some languages that are touted as being object-oriented are merely
object-based, meaning that they fail to provide support for all of the OO features listed above.

3.2.5 PROGRAM WRITABILITY

This is a measure of how easily a programming language can be used to create programs for a
chosen problem domain. Most of the programming characteristics that affect readability also

Committed to Creativity, Excellence and Self – Reliance Page 23


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

affect writability. The following features contribute towards the writability of a programming
language:

 Expressivity: This refers to the ease of a programming language to use convenient


methods to specify computations that efficiently executed. Example: In C++ language,
the notation count++ can be used instead of count = count + 1
 Simplicity: This characteristic implies that a programmer can design a solution to a
complex problem after learning only a simple set of primitive constructs.
 Abstraction: This is the ability to define and use complicated structures (or operations)
in ways that allow many of the details to be ignored. The programming languages can
support two distinct categories of abstraction, namely: process and data. Example: The
use of a subprogram to implement a function that is required several times. Note:
without the use of the subprogram, the function code would have to be replicated in all
places where it is needed. Thus the program would be much longer and more tedious to
write.

3.2.6 DEVELOPMENT ENVIRONMENT

This is a programmer’s virtual workbench, and can improve or inhibit the productivity of
computer programmers. The development environments range from simple text editors and
command-line compilers to fully interactive and integrated development environments (IDE).
An IDE should be easy to use so that the programmers can concentrate on becoming more
knowledgeable on programming concepts rather than the environment itself.

This criterion is considered to be a very important part of the IDE, when assessing a
programming language, hence the programmers should evaluate the debugging facilities that
accompany the languages, i.e., the existence of adequate diagnostic aids. The programming
environments should contain extensive tools for tracing and debugging errors. The error
diagnostics should be clear and meaningful, and the language should be robust as well as
graceful in failure.

3.2.7 PROGRAMM RELIABILITY:

A program is said to be reliable if it performs its specifications under all conditions. The
characteristics that contribute towards this are:

i) Type checking: This refers to simply testing for typing errors in a program, either
during program translation or execution time.
ii) Exception handling: this refers to the ability of a program to intercept run-time
errors, take corrective measures and then proceed with execution.
iii) Aliasing: This feature refers to the ability of having two or more distinct referencing
methods, or names for the same memory cell.

3.2.8 FULL-FEATURED LANGUAGE

Committed to Creativity, Excellence and Self – Reliance Page 24


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

Also known as scripting in which the Programmers must choose between full-featured and
less complex languages depending on the organization’s needs and their expertise. Some
programmers prefer scripting languages like Python because they offer sufficient richness to
cover most of the requirements for most novice programmers, while reducing the complexity
of the development environment and avoiding many other implementation issues. Full-
featured languages, however, offer a more complete set of language features that an
experienced programmer may want to address.

3.2.9 SOFTWARE COST

Any software application which is commercially available has a price tag and has to be
purchased from the vendor by the proprietor. The cost of acquiring software varies depending
on the application needs of a company. Other costs associated with software include:

 Training programmers
 Writing programs
 Translating and executing the programs
 Implementing and maintaining the programs

3.2.10 SUPPORT FOR SECURE CODE

This can be used to assess two important factors, namely:

 Considering whether the programming language offers features like strong type
checking and array bounds checking, while avoiding features like variants and pointers
in unsafe mode. A programming language should have a safe, statically checked type
system, no explicit pointers, and no undetectable un-initialized variables.
 The inclusion of security related features like Java’s sandbox, which is intended to limit
the memory addresses that a Java program can access.

3.2.11 PROGRAM PORTABILITY

This refers to the dependence of a programming language on a particular operating system


platform. This also refers to the ease with which programs can be moved from one hardware
and software platforms to others. Portability is strongly influenced by the degree of
standardization of the language.

Example: Programming languages such as; Visual Basic, C++ e.tc, depend on the Windows
operating system. Other languages, such as Java, are platform independent, and development
environments for Java can be found for a variety of operating systems. This may be of
concern to many programmers who may or may not prefer to be bound to a specific operating
system. The system requirements of a programming language often play a major role in the
selection process. This includes hardware as well as operating system requirements. The
amount of hard disk space needed to install the software, the operating system required, and
the amount of memory to run the software all factor into the decision.
Committed to Creativity, Excellence and Self – Reliance Page 25
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

3.2.12 SUPPORT OF WEB DEVELOPMENT

This pertains to the level of web development support that a particular language provides.
This is not limited to scripting languages, but includes web development technologies
(e.g.ASP.Net) that provide a high level of support for web development but at the same time
utilize full-featured languages.

3.2.13 PROPRIETARY / OPEN SOURCE

This refers to the corporate entity that controls the evolution of a language and its associated
development environment.

Example:

 Microsoft is responsible for additions, deletions, or modifications in any of the


languages supported by Net framework (i.e. Windows Operating System).
 Sun Systems is responsible for the ongoing evolution of the Java language.
 On the opposite end of the spectrum, PHP is an open source language and can be easily
modified by any member of the open source community.

3.3 ACTIVITIES

1) The adopters of various software technologies can be categorized into innovators and
imitators
a) Distinguish the two types of the software adopters
b) Describe the general trend followed in adoption of any given software solution
2) The business players in the Kenya’s Banking, Insurance and Mobile Phone Sectors
have been adopting powerful software technologies in the efforts of enhancing their
business operations. However, the clients have found themselves, at times, being
denied the valuable services due to faults related to the newly implemented software
technologies. State and explain the software issues that are lead to such messy
business situation.
3) Ufanisi SofTech Co. Ltd has few IT personnel that are not well informed about the
1) Describe
emergingthesoftware
difference between Proprietary
technologies. Software
The company andbeen
has Free losing
Open Source
lots ofSoftware
business
opportunities due to manual handling its corporate data. In a recent meeting of the
2) Company’s senior managers, the board agreed unanimously to search for a Database
Software solution in order to optimize the use of its corporate information resource.
Committed to Creativity, Excellence and Self – Reliance Page 26
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

4: APPROACHES TO PROGRAMMING

This topic introduces various approaches to computer programming concepts; and explains
various programming paradigms that includes POP, OOP, the basic concepts of OOP and its
benefits

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Define basic terms used in approaches to programming


ii) Describe various computer programming paradigms
iii) Explain the basic concepts of OOP paradigm
iv) State the benefits of using OOP paradigm

SUBTOPICS

 Definition of basic terms


 Computer programming Paradigms
 Procedure Oriented Programming (POP) technique
 Object Oriented Programming (OOP) technique
 Basic concepts of OOP
 Benefits of OOP
Committed to Creativity, Excellence and Self – Reliance Page 27
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

4.1 DEFINITIONS OF BASIC TERMS

 Source code: This is the original actual text used by a programmer to write a computer
program. This text is then translated into an appropriate form (Object code) that a
computer can understand.

 Object code: Refers to the program code that is in a form that is readable by a
machine

 Translator: Refers to programming language processors that convert the source


program into object code. This includes assemblers, interpreters and compilers.

 Compiler: Software tool that translates /converts the entire source program into object
code before execution. A complied program executes faster because it can be saved on
storage media although it occupies large memory space.

 Assembler: Converts/translates assembly language code into machines language code


that can be understood and executed by a computer

 Interpreter: Converts/translates single or sets of instruction one at a time before


executing them. An interpreter translates the source program every time it is required
to be executed hence it is slow with respect to execution. The resulting object code
occupies less memory as compared to a compiled object code.

 Program linking: Refers to the process of joining the object code to all other files that
are needed for program execution. The resulting file is known as executable (or
application) file.

 Data type: The specific classification of pieces of information. The amount of


different data types varies between languages. Typically, there are data types for
Committed to Creativity, Excellence and Self – Reliance Page 28
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

integers (whole numbers), floating-point numbers (numbers with a decimal part),


and single characters. To distinguish between different data types, a computer uses
special internal codes.

 Variable: A construct which stores information in a computer's memory. Every


variable has a unique name assigned to it that should give an idea about the data
that it stores, and the type of data that a variable stores. For example: Consider a
variable used to store the first letter of someone’s name. Such a variable should be
declared as a single character variable and could be named firstLetter. The value of
a variable can change all throughout a program.

 Constant: A construct used to store a value that does not change, throughout a
given program.
 Conditional feature: A segment of code that will execute or not based on certain
things. Conditionals are used to test various expressions and perform certain
operations accordingly. For example: Testing if a number input by a user is greater
than a given value.

 Array: A special type of variable that contains a list of related values. For example:
a Marks array would contain a list of student marks from different subjects.

 Loop: A segment of code that executes repeatedly based on a certain condition.


Loops are used to perform certain tasks repeatedly a certain amount of times. For
example, if you needed to print the numbers 1 to 10. You can use a loop for this
task instead of manually printing all the numbers.

 Function: A segment of code used to carry out a specific task or tasks. Functions
prevent unnecessary redundancy by having their code reused instead of the code
being retyped.

 Object: An entity which has unique characteristics. It contains its own data and
methods (functions).

Committed to Creativity, Excellence and Self – Reliance Page 29


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

 Class: In object-oriented programming, a class is a collection of similar objects.

 Algorithm: A specific set of steps for carrying out certain tasks. Algorithms are
used extensively in computer programming to arrive at a solution for a specific
problem. The process of creating an algorithm involves documenting all the
necessary steps needed to arrive at a solution and how to go about each step.

4.2 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).

Software tries to model the real world in some way, hence OOP, boils down to “what object
do I have and how do they relate to and interact with each other?” whereas. POP, boils down
to “what steps do I need to take to get the program in a certain state?”

4.2.1. PROCEDURE ORIENTED PROGRAMMING TECHNIQUE

The procedure oriented programming (POP) techniques 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.

Committed to Creativity, Excellence and Self – Reliance Page 30


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

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:

Main Program

Function 1 Function 2 Function 3

Function 4 Function 5

Figure 1: 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:

 The emphasis is on algorithms


 The data moves openly around the system form one function to another
 The large programs are divided into smaller programs (i.e. functions)
 Most of the functions share global data
 It uses the top-down approach in program design

The POP technique has the following limitations:

 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.

Committed to Creativity, Excellence and Self – Reliance Page 31


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

 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.

4.2.2. OBJECT ORIENTED PROGRAMMING TECHNIQUE

The object oriented programming (OOP) technique 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 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 following are some of the technical attributes that must be present for a program (or a
programming Language) to be considered Object Oriented:

 Inheritance
 Polymorphism
 Encapsulation and protection.

In this programming paradigm, the data types of data structures are defined by the
programmer as well as their properties and the things that can be done with them. With OOP,
programmers can also create relationships between data structures and create new data types
based on existing ones by inheriting characteristics from one data type to another.

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:

 The emphasis is on data rather on procedure


 Programs are divided into objects
 Data is hidden and cannot be accessed by external functions
 Objects communicated with each other through functions
 New data and functions can be easily added whenever necessary
 Functions that operate on the data of an object are tied together in the data structure
 Data structures are designed in such a way that they characterize the objects
 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:

Committed to Creativity, Excellence and Self – Reliance Page 32


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

OBJECT W OBJECT X

Data Data

Functions Communication Functions

Functions

Data
OBJECT Y

Figure 2: General organization of data and functions

4.3 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.

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

Committed to Creativity, Excellence and Self – Reliance Page 33


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

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.

Committed to Creativity, Excellence and Self – Reliance Page 34


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

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.

4.4 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.

4.5 ACTIVITIES

1) Distinguish between Procedure – Oriented Programming (POP) and Object – Oriented


Programming (OOP) paradigms
2) Explain how different objects communicate in the OOP program
3) State the strengths of OOP technique, clearly mentioning why OOP is likely to
Committed to Creativity, Excellence and Self – Reliance Page 35
continue being the programming paradigm of 94
of choice for many computer programmers
4) The probability of POP programs being faulty after modifications is higher than in the
case of the OOP Downloaded
programs.byExplain
Liffer Mongare (mongarewyclif2@gmail.com)
lOMoARcPSD|32867904

1) Describe the difference between Proprietary Software and Free Open Source Software

Committed to Creativity, Excellence and Self – Reliance Page 36


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

5: PROGRAMMING METHODOLOGY

This topic discusses steps in program development, flowchart development, types of


flowcharts and selected flowchart symbols. Further it explains the guidelines to drawing
flowcharts with some examples of flowcharts and then citing the limitations of using
flowcharts

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Describe the process of program development


ii) Identify various flowchart symbols
iii) Illustrate the steps used in flowchart development
iv) Apply the guidelines for drawing a flowchart
v) Generate examples of program flowcharts

SUBTOPICS

 Steps in program development


 Flowchart development
 Types of flowcharts
 Flowchart symbols
 Drawing flowchart guidelines
 Flowchart examples
 Limitations of flowcharts
Committed to Creativity, Excellence and Self – Reliance Page 37
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

5.1 STEPS IN PROGRAM DEVELOPMENT

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.

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.

Note: 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


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

Committed to Creativity, Excellence and Self – Reliance Page 38


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

This is the actual execution of the final code, usually preceded by the program linking #. 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

5.2 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,

 As springboard for further discussion of the process


 To connect with other flowcharts explaining related activities
 To identify points where data can be usefully collected and analyzed
 To isolate possible problem areas
 To communicate the process to those unfamiliar with it
 As vital tool in programming of a problem
 As good program documentation which is needed for various purposes

5.2.1 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:

 Document flowcharts: showing a document flow through a system


 Data flowcharts: showing data flows in a system
 System flowcharts: showing controls at a physical or resource level
## Combining all the object code segments from different modules and libraries functions
Committed to Creativity, Excellence and Self – Reliance Page 39
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

 Program flowchart: showing the controls in a program within a system

5.2.2 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.

Committed to Creativity, Excellence and Self – Reliance Page 40


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

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) 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.

f) Connector Symbol: This is represented with a circular symbol, in which two parts of
a program flowchart join or connect:

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

5.3 DRAWING FLOWCHART GUIDELINES

The following are some of the guidelines used during flowcharting

 In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
 The flowchart should be clear, neat and easy to follow. There should not be any room
for ambiguity in understanding the flowchart.
 The usual direction of the flow of a procedure or system is from left to right or top to
bottom.
 Only one flow line should come out from a process symbol

Or

 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.

Committed to Creativity, Excellence and Self – Reliance Page 41


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

<0 >0

=0

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

 Write within standard symbols briefly. As necessary, you can use the annotation symbol
to describe data or computational steps more clearly.

--------- This is top secret data

 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.
 Ensure that the flowchart has a logical start and finish.
 It is useful to test the validity of the flowchart by passing through it with a simple test
data.

5.4 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:

Committed to Creativity, Excellence and Self – Reliance Page 42


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

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


ii) If YES, go to step 6

Step 6: Output the total Sum

Committed to Creativity, Excellence and Self – Reliance Page 43


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

b) flowchart

Start

Count = 0

Sum = 0

Read X

Sum = Sum + X

Count = Count + 1

NO
Is
Count

YES

Output Sum

Stop

Committed to Creativity, Excellence and Self – Reliance Page 44


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

Example 2

Draw a flowchart to find the largest of three numbers A, B and C.

Solution:

START

READ A, B

YES NO IS
YES YES
IS IS
B> A> A>

PRINT B PRINT C PRINT C PRINT A

STOP

5.4.1 LIMITATIONS OF 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.

Committed to Creativity, Excellence and Self – Reliance Page 45


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

5.5 ACTIVITIES

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

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

Committed to Creativity, Excellence and Self – Reliance Page 46


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

6: C++ PROGAMMING LANGUAGE

This topic introduces the basic concepts of C++ programming language and its
characteristics. It explains structure of C++ program and how to create source file. The
features of C++ and guidelines to C++ programming are also discussed; with examples of
programs written in C++ programming language

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Define basic concepts of C++ programming language


ii) Explain the various characteristics of a good programming language
iii) Illustrate structure and creation of C++ source file
iv) Identify features of a C++ program segment
v) State guidelines to C++ programming language
vi) Generate theoretical C++ program segments

SUBTOPICS

 Basic concepts of C++ programming


 Characteristics of C++ programming
 Structure of C++ program
 Creating C++ source file
 Features of C++ program
 Guidelines to C++ programming
 Programming in C++ language
Committed to Creativity, Excellence and Self – Reliance Page 47
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

6.1 BASICS OF C++

The C++ is a programming language of many different dialects, just as each spoken has many
different dialects. In C++, dialects are not because the speakers live in the North or South; it
is because there are several different compilers. There are four major compilers: Borland C+
+, Microsoft Visual C++, Watcom C/386, and DJGPP. These compilers can be downloaded
from the internet. Each of these compilers is slightly different. Each one will support the
ANSI/ISO standard C++ functions, but each compiler will also have nonstandard functions.
Sometimes the use of nonstandard functions will cause problems when one attempts to
compile source code (the actual C++ written by a programmer) in a different compiler.

6.2 CHARACTERISTICS OF C++ PROGRAM

A C++ program is a collection of different code features that play specific roles during the
execution time of a program. The organization of these features within a program contributes
to the quality of the computer program.

 The computer program should solve the target problem.


 The implementation of the computer program should be free of errors; hence it must
work for all valid inputs and must produce the required response.
 The program should be well documented in order to assist in the understanding or use of
a program. This can be of great value not only to those charged with maintaining or
modifying a program, but also to the programmers themselves.
 The program should be maintainable because programs require a continuing process of
maintenance and modification in order to keep pace with the changing requirements and
implementation technologies. A program is made maintainable by:

a) Dividing the program into modules


b) Making sure that the program is well-documented
c) Using symbolic constants: Many programming languages permit the declaration of a
named constant, which equates a user-chosen identifier, say, CLASS_SIZE, with a
literal constant. Thus, #define CLASS_SIZE 48 will occur, in only one place, namely,
the constant declaration. This requires only one alteration to change the value class
size throughout the program.

 The Program must be Robust. This refers to the ability of a program being able to
survive various unexpected events, such as incorrect or invalid input data. The following
are some guidelines to ensure robustness:

- The input data should always be validated, hence no assumption that the data is
always correct.
Committed to Creativity, Excellence and Self – Reliance Page 48
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

- Always initialize relevant variables.


- Avoid syntactic constructs that could lead to undesirable interpretation.

 The white spaces should be used effectively. Most programming languages allow the
use of blank lines and spaces embedded within the program code to improve its
readability. Example: Statements such as x = x+1 would be better written as x = x + 1.

 The choice of identifiers for the names of modules, subprograms, types, variables, and
other elements is crucial in producing a readable program. The goal is to use meaningful
identifiers which help the reader remember the purpose of an identifier without
constantly referring to the declarations or to a variable list external to the program.

6.3 STRUCTURE OF C++ PROGRAM

A typical C++ program would contain four sections, which may be placed in separate code
files and then compiled independently or jointly. The program sections are:

1. Include files
2. Class declaration
3. Member functions definitions
4. Main function program

A C++ program is commonly organized into three separate files by: placing the class
declarations in a header file while the definitions of member functions go into another file.
This approach enables the separation of the abstract specification of the interface (i.e. class
definition) from the implementation details (i.e. member functions definition). The main
program that uses the class is placed -in a third file which “includes” the previous two files as
well as any other files required, as shown below:

Member Functions

Server
Class Definition

Client
Main Function Program

Figure 3: Client-Server file organization


Committed to Creativity, Excellence and Self – Reliance Page 49
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

The class definition including the member functions constitute the server that provides
services to the main program. The client uses the server through the public interface of the
class.

6.4 CREATING C++ SOURCE FILE

The C++ programs can be created using any text editor. Examples of the text editors include:
vi, ed, edlin, brief and notepad among others. In order for the file to recognized as a C++
program, the file’s name should have extension .cpp. The following are the steps of creating a
C++ source file (With respect to the Microsoft Visual C++ 6.0 installed in the machines-
Ground Floor Computer Laboratory):

Step 1: Click Start button

Step 2: Click All Programs

Step 3: Click Microsoft Visual C++ 6.0

Step 4: From the File menu, click New

Step 5: From the New Dialog box click Files option, then:

 Click C++ Source File


 Write the File name (NB: The filename should end with .cpp extension)
 Indicate the directory in which the file will be saved, then click OK.

Step 6: Write the source program on the blank window that opens, and click the Save
icon on completion.

Step 7: From the Build menu click the Compile option

Step 8: In case of any compilation errors:

 Double click each error type, at a time, shown in the lower window (i.e.
located close to the task bar), in order for an indicator to point at the
respective code line in which an error exists.
 Correct the error, then click the Save icon to save the changes

Step 9: From the Build menu click the Execute option in order to run the program.

6.5 FEATURES OF C++ PROGRAM

1) #include<iostream.h>: this is a compound pre-processor directive that invokes the


execution of the program by the processor for linking the input – output streaming files;
and that:-

Committed to Creativity, Excellence and Self – Reliance Page 50


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

 #Symbol: this is a signal to the pre-processor (i.e. a program that is automatically


called each time a compiler is run, in order to modify the code)
 include: this is an instruction to the pre-processor that gives direction concerning
where to find the file name.
 iostream.h : this can be read as input-output-stream.header. It enables the capturing
and outputting of data and information respectively.
 < >: Gives an indication that the filename is confined within it.

2) main ( ) :This is the master function which oversees the execution of the entire program.

3) Comments: are the additional ideas to make the program more understandable and can
be written within:-

 /*…*/: This is known as star-slash comment style and is used in a case where the
comment runs to more than one line
 //: This is known as double-slash comment style and is used in a case where the
comment fits in one line

4) Input / output commands: these are controls used to enable the user or programmer to
interact with the computer and are as follows:-

 cout: this is an object used to print a message to the screen. The word cout is
followed by redirection operator <<)
 cin: this is the input command and it is followed by >> operator and allows for input
of data by the user.

5) return 0 : this a signal to the Operating System that the main() function has successively
executed.

6) \n or \endl : this is non-printable character that tells the cout to place the cursor in a new
line

6.6 GUIDELINES TO C++ PROGRAMMING

Committed to Creativity, Excellence and Self – Reliance Page 51


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

 Ensure that the program logic design is clear and correct. Avoid starting to code before
the logic is clearly set out since good logic will reduce coding time as well as result in
programs that are to understand, error free and easily maintainable.
 Declare all variables before using them in any statements.
 Use sensible names for variables and avoid using variables names that are vague and
may make debugging difficult. This however depends on the programmer’s ingenuity.
 Use a variable name in the case that it was declared in.
 Never use keywords in uppercase.
 Terminate C++ declarations, expressions and Input / Output statements in semi colon.
 Restrict the variables names to eight characters. The compiler may truncate part of a
variable name and possibly give it the meaning of another variable
 Always save the program every time you make changes.
 Proof read the program to check for any errors or omissions
 Dry run design with some simple test data before running the code and then compare

6.7 PROGRAMMING IN C++

The C++ is a different breed of programming language. For DOS – Based C++ compilers,
there are only a few keywords; which alone are insufficient for input or output functions.
Almost all useful functions are in library files that can be accessed by including header files.
The following are some of examples of real C++ program:

Example 1: Write a C++ program that can compute the sum and average of 15 numbers

Solution:
/* This program computes and displays the sum and average of 15 numbers.
The program was authored on the Saturday 28th February 2009 */

#include<iostream.h>
int main ( )
{
// Declaration of Variables
int count=0;
float x, Sum=0, Average;
for (count=0;count<15;)
{
// Entry of the 15 numbers
cout<<"Enter the fifteen numbers \n";
cin>>x;
// The summing up process

Committed to Creativity, Excellence and Self – Reliance Page 52


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

Sum = Sum + x;
// The updating of the counting variable
count = count + 1;
}
// Computation of the average of the 15 numbers
Average = Sum/count;
// Displaying the 15 numbers
cout<<"The sum of the 15 numbers = "<<Sum<<"\n";
cout<<"The average of the 15 numbers = "<<Average<<"\n";
return 0;
}

Example 2:
Write a program for input and output operations
// This program demonstrates use of data streams cin for input and cout for output
#include<iostream.h>
int main ( )
{
int i;
cout << “Please enter an integer value:”
cin >> i;
cout << “The value you have entered is “<<i<<””;
cout << “and its double is “<<i * 2<<”\endl;
return 0;
}
The output of the above program is as follows:-
- Please enter an integer value
- 444 (for example)
- The value you entered is 444 and its double is 888

6.8 ACTIVITIES

1) State the use of the following features of C++ programming language


i) Semicolon
ii) Comment
iii) Opening and closing braces
iv) /*...*/ and // symbols
2) During the exam processing the student total marks, highest score and the average grade
are calculated. Write a C++ program that can be used compute the student’s total marks,
score and the average grade.
3) Identify the errors in the following C++ program
Committed to // This program
Creativity, computes
Excellence and Self –and displays the product of two numbers */
Reliance Page 53
#include<iostrem.h> of 94
float main ( )
float x, y, product
// Entry of theDownloaded
two numbers
by Liffer Mongare (mongarewyclif2@gmail.com)
lOMoARcPSD|32867904

1) Describe the difference between Proprietary Software and Free Open Source Software

2)

Committed to Creativity, Excellence and Self – Reliance Page 54


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

7. IDENTIFIERS, VARIABLES AND CONSTANTS

This topic introduces the concepts of identifiers, variables and constants and how they are
defined and declared in a program. It explains the creation of variables and constants and
assigning values respectively. Further it describes various types of constants

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Define the basic concepts of identifiers, variables and constants


ii) Understand size of, signed and unsigned variables
iii) Demonstrate how to create and initialize variables
iv) Describe various types of constants

SUBTOPICS

 Identifiers, variables and constants


 Size of variables and constants
 Signed and unsigned integers
 Definition of variables and constants
 Creating variables and constants
 Assigning values to variables
 Types of constants

Committed to Creativity, Excellence and Self – Reliance Page 55


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

7.1 IDENTIFIERS

An identifier is a creation of a programmer which may refer to names of variables, arrays,


classes, functions etc. the following are the rules that govern the naming of identifiers in C++
language:

 Uppercase and lowercase letters are distinct


 It is only the alphabetic characters, digits and underscores that are allowed
 The name of the identifier cannot start with a digit
 A declared keyword cannot be used as a variable name
 There is no limit on the length of the identifier’s name

Some of the keywords are:

Int, return, float, goto, double, const, public, private, if,


for, char, else, switch, void, while, typedef, do,
case, default, break, continue, struct, class, sizeof

7. 2 VARIABLES

A variable is a location in the computer memory in which a value can be stored and retrieved.

7.2.1 SIZE OF VARIABLES

Different variables occupy different memory sizes as dictated by their size. See table (i)
below:

Variable Name Usage Size in Bytes

Char Hold characters 1

short in Small integers 2

long int Very large integers 4

Int All integers 2/4

Float Decimal numbers 4

Committed to Creativity, Excellence and Self – Reliance Page 56


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

Bool Holds Boolean values 1

The following program can be used to determine the sizes of the respective variables:

Example 1

// This program determines the sizes of different variables in a computer


#include<iostream.h>
int main ( )
{
cout<<"The size of an int is:\t\t"<<sizeof(int)<<"bytes\n";
cout<<"The size of a short int is:\t"<<sizeof(short)<<"bytes\n";
cout<<"The size of a long int is:\t"<<sizeof(long)<<"bytes\n";
cout<<"The size of a bool is:\t\t"<<sizeof(bool)<<"bytes\n";
cout<<"The size of a char is:\t\t"<<sizeof(char)<<"bytes\n";
cout<<"The size of a float is:\t\t"<<sizeof(float)<<"bytes\n";
cout<<"The size of a double is:\t"<<sizeof(double)<<"bytes\n";
return 0;
}

7.2.2 SIGNED AND UNSIGNED INTEGERS

Integers can be classified into signed and unsigned integers. The signed integers are either
negative or positive integers. The short and long integers without the word “unsigned” are
assumed to be signed. The unsigned integers are taken to be positive. The following example
shows the use of unsigned short integers.

Example 2

//This program demonstrates the use of unsigned short integers


#include<iostream.h>
int main ( )
{
unsigned short Width;
unsigned short Length;
unsigned short Area;
cout<<"Enter the Width Value \n";
cin>>Width;
cout<<"Enter the Length Value \n";
cin>>Length;
Area = Width * Length;
Committed to Creativity, Excellence and Self – Reliance Page 57
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

cout<<"The Area of the rectangle is: "<<Area<<endl;


return 0;
}

2.3 DEFINITION OF VARIABLE

A variable can be defined by stating its type, followed by one or more spaces, followed by the
variable name and a semi-colon. A good variable name should:

 tell what the variables represents


 make it easy to understand the program flow

Example 3

int Age;
float price;

The Age variable can only take values of integer type whereas the price variable can store
values having fraction parts (i.e. decimals)

2.4 CREATION OF VARIABLES

It is possible to create several variables of the same type in only one statement by writing the
type and then the variable names, separated by commas and ending with a semi-colon.

Example 4:

int Quantity, Count;


float Price, Product;
The two variables Quantity and Count can only store values of integer type

2.5 ASSIGNING VALUES TO VARIABLES

A value is assigned to a variable by using the assignment operator (=).


Example 5:
float width=15;
A value of 15 of float (decimal) type is assigned to width variable.

Example 6:
//This program demonstrates the assignment of values to variables
#include<iostream.h>
int main ( )
{
unsigned short Width = 10, Length;

Committed to Creativity, Excellence and Self – Reliance Page 58


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

Length = 50;
unsigned short Area = Width * Length;
cout<<"The Width of the Rectangle:"<<Width<<endl;
cout<<"The Length of the Rectangle:"<<Length<<endl;
cout<<"The Area of the rectangle is: "<<Area<<endl;
return 0;
}

7.2.3 TYPEDEF

The typedef is used in C++ language to create an alias for a type definition. typedef is used
by writing the keyword followed by the existing type and the new name. The above Example
6 is modified by using typedef key word as shown in Example 7 below:

Example 7:

//This program demonstrates the use of typedef keyword

#include<iostream.h>

// typedef definition is done in the following code line

typedef unsigned short UNSHORT;

int main ( )

UNSHORT Width = 10, Length;

Length = 50;

UNSHORT Area = Width * Length;

cout<<"The Width of the Rectangle:"<<Width<<endl;

cout<<"The Length of the Rectangle:"<<Length<<endl;

cout<<"The Area of the rectangle is: "<<Area<<endl;

return 0;

7.3 CONSTANTS

Committed to Creativity, Excellence and Self – Reliance Page 59


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

Constants refer to fixed values that do not change during the execution of a program. C++
supports several kinds of literal constants, namely: integers, characters, floating point
numbers and strings. A constant must be initialized when created.

7.3.1 TYPES OF CONSTANTS

There are three main types of constants, namely:

1. Enumerated Constants: This is a constant that creates a set of constants with a range
of values.
2. Literal Constant: This is a value that is typed directly into the program whenever it is
needed. E.g. int MyAge = 35;

MyAge is a variable of type int, whereas 35 is a literal constant

3. Symbolic Constants: This is a constant that is represented by a name

Example 8:

Considering a case where a program has one integer variable named customers and another
named regions, the number of customers could be computed, given a known number of
regions and the average number of customers per region (eg 20):

customers = regions * 20;

NB: 20 is a literal constant. The code could be easier to read and maintain, if a symbolic
constant is used instead of the literal constant, as shown below:

customers = regions * customersPerRegion;

If a change was to be made to the number of customers in each region, then it can be done
where the constant customersPerRegion is defined without having to make a change in
every part of the program where a value is used, as it is the case with literal constants.

7. 3. 2 DEFINING CONSTANTS WITH #define

To define a constant, the keyword #define is written followed by the constant name, and the
value as shown below:

#define customersPerRegion 20;

The pre-processor puts 20 in the text whenever it sees the word customersPerRegion. Since
the pre-processor runs before the compiler, the compiler never sees the constant; hence it only
sees the value 20.

Committed to Creativity, Excellence and Self – Reliance Page 60


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

7.3.3 DEFINING CONSTANTS WITH const

The keyword const provides a more advantageous way of defining constants, unlike the
#define keyword. Eg

Const unsigned short int customersPerRegion = 20;

The advantage with this method is that the constant has a type, hence the compiler can
enforce that the constant is used according to its type.

7.3.4 ENUMERATED CONSTANTS

This type of constants creates a set of constants with a range of values. The enumerated
constants are defined by writing the keyword enum, followed by the type name, an open
brace, legal values separated by a comma, closing brace and semicolon. eg

enum COLOR {Green, Blue, Yellow, Orange}

The statement performs the following tasks:

i) It makes COLOR the name of an enumeration


ii) It makes Green, Blue, Yellow, and Orange to be symbolic constants that take the
values 0, 1, 2, and 3 respectively.

The symbolic constants can also be initialized, instead of relying on default values 0, 1, 2…
However, the symbolic constants that are left un-initialized count upward from the ones
before them. Eg

enum COLOR {Green=50, Blue, Yellow, Orange=150}

The Green, Blue, Yellow and Orange colours will take the values 50, 51, 52, and 150
respectively.

Committed to Creativity, Excellence and Self – Reliance Page 61


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

7.4 ACTIVITIES

1) State the errors in the following statements


a) Int 45 MarksScores:
b) Float Return;
c) Cout >> “the total sales is: <<”sales’
2) By using suitable examples distinguish between: literal, symbolic and enumerated
constants
3) Given the following declaration of enumerated constants, state the values assumed by
Black and Extremely Black colours
Enum COLOUR {Indigo =13, Black, Dull, Purple = 37, Extremely Black}
4) State the difference between
a) A Computer Program Editor and Word Processor
1) Describe
b) Athe difference
variable and abetween
KeywordProprietary Software and Free Open Source Software
c) A compiler and an Interpreter
2)

Committed to Creativity, Excellence and Self – Reliance Page 62


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8: PROGRAM CONTROL STRUCTURES

This topic introduces the various program control structures and elaborates on the types of
control that includes sequence, selection, loop or iteration and the bifurcation controls. It
further shows the various constructs for each type of control structure

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Explain the various types of control structures


ii) Illustrate the types of control structures
iii) Identify various constructs of the control structures
iv) Program using any of the control structure constructs

SUBTOPICS

 Introduction to control structures


 Sequence control structure
 Selection control structure
 Loop control structure
 Bifurcation of control structures

Committed to Creativity, Excellence and Self – Reliance Page 63


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8.1 INTRODUCTION TO CONTROL STRUCTURES

The program control structures are the different ways in which the nature of a program can be
designed or modelled with respect to writing down the program code or instructions. A
programmer can choose any of the programming language and design the program in any of
the three main types of control structures, namely: sequence, selection and loop or iteration
program control structures

8.2 SEQUENCE CONTROL STRUCTURE

This is a linear control structure, in which the program execution proceeds from one action to
the next one without skipping. This type of control is as illustrated in figure 4 below:

Entry

Action 1

Action 2

Action 3

Exit

Figure 4: Sequence Control Structure

The program is executed from code line to the next in a sequential manner

Committed to Creativity, Excellence and Self – Reliance Page 64


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8. 2 SELECTION CONTROL STRUCTURE

This a type of control structure in which alternative execution paths radiate from a
decision (branching) point. This type of control structure is as illustrated in figure (ii)
below:

Entry

Decisi

Action 1 Action 2

Exit

Figure 5: Selection Control Structure

Examples of selection control structures include;

8.2.1 IF-ELSE STATEMENT


The general structure of the if-else control structures is:
if (expression is true)
{
statement 1;
}
else
statement 2;

Explanation: If the expression is found to be true, the statement 1 is executed, otherwise the
statement 2 is executed when the expression is found to be false.

Example 1:

a) // This program demonstrates if – else control structure


#include<iostream.h>
Committed to Creativity, Excellence and Self – Reliance Page 65
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

int main ( )
{
if (x == 100)
cout <<”x is 100”;
else
cout<<”x is not 100”;
return 0;
}

b) // This program demonstrates if – else control structure


#include<iostream.h>
int main ( )
{
if (x > 0)
cout <<”x is positive”;
{
elseif (x < 0)
cout<<”x is negative”;
}
else
cout<<”x is zero”;
return 0;
}

c) // This program demonstrates if – else control structure


#include<iostream.h>
int main ( )
{
int x, y;
// Entry of input data
cout<<“Enter the first value: ”;
cin>>x;
cout<<“Enter the second value: ”;
cin>>y;
// Determination of the value which is greater than the other
if (x>y)
{
cout<<“ x is greater than y \n”;
}
else
cout<<“ y is greater than x \n”;
return 0;
}

The if-else statement can be deeply nested as shown below:

if (expression1)
{
if (expression2)
Committed to Creativity, Excellence and Self – Reliance Page 66
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

action1;
else
{
if (expression3)
action 2;
else
action3;
}
}
else
action4;

Explanation:

If expression1 is true and expression2 is true, then action1 is executed. If the expression 1 is
true but expression 2 is false, then if expression 3 is true, then action2 is executed. If
expression1 is true but expression2 and expression3 are false, then action3 is executed. If
expression1 is false, then action4 is executed.

8.2.2 SWITCH STATEMENT

The switch statement is applied in a case where the if-else statement may end up being too
deeply nested. The switch statements make it easy to branch on any of a number of different
values. The statement takes the following general format:

switch (expression)
{
case 1:
{
statement 1;
}
case 2:
{
statement 2;
}
.
.
.
default:
{
statement m;
}
statement n;

Committed to Creativity, Excellence and Self – Reliance Page 67


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

The switch statement evaluates the expression and compares the result to each of the
case values. This evaluation is only for equality; otherwise neither relational operators
(Table [i]) nor Boolean expressions can be used here.

Name Operator

Less than <

Greater than >

Equals ==

Less than or Equals <=

Greater than or equals >=

Not equals !=

Table 2: The relational Operators

If any of the case values is found to match the expression, the execution jumps to those
statements and continues up to the end of the switch block unless a break statement is
encountered. If there is no case value that matches the expression, the execution branches
to the optional default statement.

Example 2:

a) i) // This program demonstrates the switch control structure


#include<iostream.h>
int main ( )
{
switch (x)
case 1:
cout << “x is 1”;
break;
case 2:
cout << “x is 2”;
break;

Committed to Creativity, Excellence and Self – Reliance Page 68


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

default:
cout << “ value of x unknown”;
return 0;
}

ii) //This is an if-else equivalent of the above switch program

#include<iostream.h>
int main ( )
{
if(x ==1)
cout << “x is 1”;
}
elseif(x == 2)
cout << “x is 2”;
{
else
cout<<”value of x unknown”;
return 0;
}

b) // This program demonstrates the switch control structure

#include<iostream.h>
int main ( )
{
Unsigned short int x;
// Entry of input data
cout<<“Enter a number between 1 and 3: ”;
cin>>x;
// switch statement execution!!
switch (x)
{
case 1:
{
cout<< “The case value matches integer 1! \n”;
break;
}
case 2:
{
cout<< “The case value matches integer 2! \n”;
break;
}
case 3:
{
cout<< “The case value matches integer 3! \n”;
break;

Committed to Creativity, Excellence and Self – Reliance Page 69


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

}
default:
{
cout<< “No case value that matches any of the numbers between 1 and 3\n”;
break;
}
}
return 0;
}

The user is prompted for a number between 1 and 3. The number entered by the user is
given to the switch statement. If the number is found to match any of the case values, the
execution jumps to the respective case and executes the statement under that case. If the
number entered does not fall within the expected range, the program executes the default
statement and prints out the message “No case value that matches any of the numbers
between 1 and 3” and then exits.

8. 3 LOOP STRUCTURE

A loop is a program control structure that allows for the execution to follow conditional
structures, repetitive structures or bifurcation of controls. Loops can be nested in such a
way that one loop sits in the body of another. For every execution of the outer loop, the
inner loop is executed in full. The loop control structure is as illustrated in figure 6 below

Entry

Action 1

Decisi True Action 2


on

False
Action 3

Exit

Figure 6: Loop control structure

Examples of loop control structures include: do-while loop, while loop, for loop, bifurcation
or jump controls namely: the break instruction, the continue instruction and the goto
instruction
Committed to Creativity, Excellence and Self – Reliance Page 70
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8.3.1 DO-WHILE CONTROL STRUCTURE

The do-while control structure is an exit-controlled loop structure. The do-while loop
executes the body of the loop before its condition is tested, and ensures that the body always
executes at least one time. The do-while loop structure takes the format I: do statement
while (condition is true);

format I I: do
{
statement 1;
}
while (condition is true)
statement 2;

The control is transferred back to a particular point in the program with respect to a stated
condition.

1. Example: do – while loop

// This program concerns number echoer

#include<iostream.h>
int main ( )
{
unsigned long m;
do
{
cout << “Enter a number (0 to end):;
cin >> m;
cout << “You entered: “<< m <<”\n”;
}
while (m != 0);
return 0;
}

The output of the above program is:-

- Enter a number (0 to end):


- (say) 123456
- You entered: 123456
- Enter a number (0 to end):
- (say) 98765
- You entered: 98765 ; and so on

Committed to Creativity, Excellence and Self – Reliance Page 71


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8.3.2 WHILE CONTROL STRUCTURE

The while control structure, is an entry-controlled loop structure that checks its condition
before executing any of its statements. If the condition evaluates false, the entire body is
jumped. The while control structure takes the following

Format I: while (expression) statement

Format II: while (condition is true)


{
statement 1;
}
statement 2;

2. Example: while loop

// A program for custom countdown using the while loop

#include<iostream.h>
int main ( )
{
int n;
cout << “Enter the starting number:”;
cin >> n;
while (n > 0)
{
cout << n << “ , ”;
– – n;
}
cout << “FIRE !”;
return 0;
}

The output of the above program is:-

- Enter the starting number (e.g. 10)


- 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- FIRE !

Question: Write a program for the count up to 10.

Committed to Creativity, Excellence and Self – Reliance Page 72


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8.3.3 FOR CONTROL STRUCTURE

The for control structure is an entry-controlled loop structure and is used when an action
is to be repeated for a pre-determined number of times. The structure takes the format:

Format I: for (initialization; condition; increment) statement;

Format II: for (initial value; test value; increment)

{
statement 1;
}
statement 2;

A for loop follows the following sequence:

i) It performs the operations in the initialization


ii) Evaluates the condition
iii) If the condition is true, it executes the statement and the loop. The steps 2 and 3 are then
executed repeatedly until when the condition is found to evaluate false.
3. Example: for loop

// A program for custom count up using the for loop

#include<iostream.h>
int main ( )
{
int n;
for (n > 0; n = 10; n ++ )
{
cout << n << “ , ”;
}
cout << “FIRE !”;
return 0;
}

The output of the above program is:-

- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- FIRE !

Question: Consider and explain the following for statement

for (n = 0; i = 100; n != i; n++; i – –)

Committed to Creativity, Excellence and Self – Reliance Page 73


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8.3.4 BIFURCATION STRUCTURES


These are mainly the jump or skip control structures that are used to alter the normal or
sequential execution of the program instructions. Mainly such controls are effected in a
program using the break instruction, continue instruction and the goto instruction

8.3.4.1 BREAK INSTRUCTION


// A program for custom countdown using break instruction
#include<iostream.h>
int main ( )
{
int n;
for (n = 10; n > 0; n – – )
{
cout << n << “ , ”;
if (n = = 3)
{
cout << “Countdown Aborted !”;
break;
}
}
return 0;
}

The output of the above, jump program is:-

- 10, 9, 8, 7, 6, 5, 4
- Count down Aborted!

8.3.4.2 CONTINUE INSTRUCTION


// A program for custom countdown using continue instruction
#include<iostream.h>
int main ( )
{
for (int n = 10; n > 0; n – – )
{
if (n == 5)
continue;
cout << n << “ , ”;
}
cout << “FIRE !”;
return 0;
}

The output of the above, continue program is:-

- 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- FIRE !
Committed to Creativity, Excellence and Self – Reliance Page 74
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

8.3.4.3. GOTO INSTRUCTION


// A program for custom countdown using goto instruction
#include<iostream.h>
int main ( )
{
int n = 10;
loop:
cout << n << “ , ”;
n––;
{
if (n > 0 )
goto loop;
}
cout << “FIRE !”;
return 0;
}

The output of the above goto program is:-

- 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- FIRE !

8. 4 ACTIVITIES

1) Discuss the program control structures giving the syntax of their implementation
2) Describe fully the basic stages that are followed during program development process

3) Write a C++ program to calculate and output the total surface area of a closed
cylindrical container as given by the expression S = 2Лr2 + 2Лrh

4) Design a program to input the basic salary of a worker and compute the net pay
assuming the following conditions
 House allowance of 17% of basic salary
 Entertainment allowance of Ksh 4,000
 Medical allowance of Ksh 6,000
 Transport allowance of Ksh 3,000
 Tax of 12% of gross salary

Committed to Creativity, Excellence and Self – Reliance Page 75


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

1) Describe the difference between Proprietary Software and Free Open Source Software

2)

Committed to Creativity, Excellence and Self – Reliance Page 76


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

9. ARRAYS IN C++

This topic introduces the basic concepts of arrays as used in programming. It demonstrates
how to declare and initialize arrays. The multidimensional arrays are discussed and illustrated
in various program segments

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Define basic concepts of arrays in programming


ii) Demonstrate how to declare and initialize arrays in programming
iii) Describe declaration of multidimensional arrays
iv) Explain the various ways of accessing objects in arrays

SUBTOPICS

 Introduction to arrays
 Declaration of arrays
 Initialization of arrays
 Multidimensional arrays
 Accessing objects of arrays

Committed to Creativity, Excellence and Self – Reliance Page 77


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

9.1 INTRODUCTION TO ARRAYS

In other sciences and especially mathematics an array an arrangement of a number of items


into an ordered matrix i.e. into rows and columns which has the respective positions
described using subscripts. In computer programming, an array is a collection of memory
locations that are related by the fact that they all have the same name and type.

9.2 DECLARATION OF ARRAYS

The general format of declaring an array is as follows:

array-type array-name number-of-elements;

Example 1:

int BMS201Marks [45];

The array’s name is BMS201Marks and the array contains 45 elements of type integer.

In order to refer to a particular element in the array, the array name is specified followed by
the position number (expressed as a subscript) of the element in the array. The array elements
are counted from zero (0), thus elements of an array having n elements are counted as
follows: 0, 1, 2, 3… (n-1).

Example 2:

// This program uses an integer array


#include<iostream.h>
int main ( )
{
int arrayExample[10];
int i;
for (i=0; i<10; i++)
{
cout<< “Value for arrayExample[“<<i<<”]: ” ;
cin>>arrayExample[i];
}
for(i=0; i<10; i++)
cout<<i<<“:”<<arrayExample[i]<<endl;
return 0;
}

Committed to Creativity, Excellence and Self – Reliance Page 78


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

Explanation:

1. The array is declared in the statement int arrayExample[10]; The array

stores ten integer values

2. The first for loop counts the array elements from 0 through 9.
3. The statement cout<< “Value for arrayExample[“<<i<<”]: ” ; prompts the

user to enter an integer value. The values entered are stored in their

respective positions within the array as shown in figure(i) below:

0
1
2
3
4
5
6
7
8
9
Display of integers as entered by the user

The second for loop outputs the integer values entered by the user. The output is:
0:1
1:2
2:3
3:4
4:5
5:6
6:7
7:8
8:9
9:10

9.3 INITIALIZATION OF ARRAYS

An array can be initialized by specifying the type, name, subscript, assignment operator,
opening brace, elements (separated by commas), closing brace, and semi-colon.

Example 3

Committed to Creativity, Excellence and Self – Reliance Page 79


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

int studentMarks [7] = {75, 60, 80, 68, 78, 82, 71};

This array has seven elements of integer type.

9.4 MULTIDIMENSIONAL ARRAYS

Arrays can have more than one dimensions and each dimension is represented as a subscript
in the array. The multi-dimensional arrays can also be initialized.

Example 4: int MyArray[6][4];

This array reserves a memory space for 6 rows and 4 columns, which hold data of integer
type. The rows are numbered 0,1,2,3,4,5 whereas the columns are numbered 0,1,2,3. The first
four elements to be entered go into the row(0), and the last four elements go into row(5).

Example 5
// This program demonstrates how a multidimensional array is declared
#include<iostream.h>
int main ( )
{
int arrayExample[6][4] ={{1,2,3,4}, {1,2,3,4}, {1,2,3,4}, {1,2,3,4}, {1,2,3,4}, {1,2,3,4}};
for (int i=0; i<6; i++)
{
for (int j=0; j<4; j++)
{
cout<<"arrayExample ["<<i<<"]["<<j<<"]: "<<arrayExample[i][j]<<endl;
cin.get ( )
}
}
return 0;
}
Explanation:
 The initialized arrayExample array has 24 integer values
 The first for loop helps to read through the different rows whereas the second
 for loop helps in reading through the different columns
 The cin.get ( ) command is a function call which reads in input and expects the user to
hit the return key. This command keeps the window from closing because the program
is not done yet because it waits for the hitting of the enter key. Inclusion of that line
gives time to the programmer to see running of the program.
The output of the program is as follows:
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
Committed to Creativity, Excellence and Self – Reliance Page 80
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4

Example 6

// This program demonstrates the display of an array elements

#include<iostream.h>
int main ( )
{
int arrayExample[4][3] ={{59,78,80}, {67,56,45}, {68,78,70}, {75,60,35}};
for (int i=0; i<4; i++)
{
for (int j=0; j<3; j++)
{
cout<<"arrayExample ["<<i<<"]["<<j<<"]: "<<arrayExample[i][j]<<endl;
cin.get ( )
}
}
return 0;
}

Mark [0][0]: 59 Mark [0][1]: 78 Mark [0][2]: 80


Mark [1][0]: 67 Mark [1][1]: 56 Mark [1][2]: 45
Mark [2][0]: 68 Mark [2][1]: 78 Mark [2][2]: 70
Mark [3][0]: 75 Mark [3][1]: 60 Mark [3][2]: 35

The above computer output is equivalent to a normal array as follows:-


59, 78, 80
67, 56, 45
68, 78, 70
75, 60, 35

Committed to Creativity, Excellence and Self – Reliance Page 81


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

9.5 ACTIVITIES

1. By using a suitable C++ program segment, show how you can:-


a) Enable the entry of the elements of a 5 x 3 matrix from the keyboard
b) Display the elements of the 5 x 3 matrix on a computer screen
2. Demonstrate how you can initialize a 3 x 2 array
3. State the errors in the following program segment
/* Usage of Arrays
#includ<iostram.h>
int main ( )
{
int 6arrayExample[4][3]
for (int i=0; i>4; i++)
{
1) Describefor
the(int j=0; j<3;between
difference i++) Proprietary Software and Free Open Source Software
{
return 0
2)

Committed to Creativity, Excellence and Self – Reliance Page 82


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

10. FUNCTIONS IN C++ PROGRAM

This topic discusses the introduction to functions and explains the declaration and definition
of functions. It shows how to pass arguments to a function and how to specify the return
values of given functions

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Define the basic concept of function in programming


ii) Demonstrate how to declare a function
iii) Identify and define new functions
iv) Explain arguments of a function
v) Describe the return values based on a given fucntion

SUBTOPICS

 Introduction to functions
 Declaration of functions
 Definition of functions
 Arguments of a function
 Return values of a function

Committed to Creativity, Excellence and Self – Reliance Page 83


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

10.1 INTRODUCTION TO FUNCTIONS

A function is a block of code that performs a service. Every C++ program has at least one
function, namely; the main function. This is the function that is automatically called when a
C++ program starts.

The Operating System (OS) installed in the computer invokes the main () function to start a
C++ program whereas other functions are called from the main () function or from one
another under the control of the main () function. A C++ program is executed line by line in
the order it appears in the source code, until a function is called. Then the program branches
off to execute the function. When the function completes the execution, it returns control to
the next line in the calling function.

Functions either return a value or void (i.e. return nothing). For instance, a function that;

1. Adds two integers might return the sum, and thus would be defined as returning an
integer value
2. Prints a message has nothing to return, hence it would be declared void.

A well written function performs a specific task only and then returns. It is advisable to break
the complicated tasks into multiple functions, so that each can be called in turn. This makes
the code easier to understand and maintain.

10.2 DECLARATION OF FUNCTIONS

A function must first be declared and defined before use. This provides the function’s return
type, name, and parameters to the compiler. The declaration of a function is referred to as its
prototype. The function prototype is a statement, hence it ends with a semi-colon

Functions consist of a header and a body. The header consists of the return type, function
name and the parameters to that function. A parameter is a declaration of what type of value
will be passed in. The parameters to a function allow values to be passed into the function.

Example: int Product (int x, int y);

Return type Function name Parameters

The actual value passed in by the calling function is known as argument. The function
prototype and function definition must agree exactly about the return type, name, and
parameter list.

Example 1: Demonstration of a Function Declaration and Definition

// Demonstration about the declaration and definition of a function


#include<iostream.h>
// Declaration of a function prototype
Committed to Creativity, Excellence and Self – Reliance Page 84
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

int FindCost(int quantity, int price); this is a function prototype


int main ( )
{
int quantityOfItems;
int priceOfItems;
int costOfItems;
// Entry of values
cout<<“ Enter the quantity of items”;
cin>> quantityOfItems;
cout<<“ Enter the price of items”;
cin>> priceOfItems;
costOfItems = FindCost (quantityOfItems, priceOfItems); a function header
cout<< “\nThe total cost of all items is ”;
cout<< costOfItems;
return 0;
}
// Definition of a function !!
int FindCost(int q, int p) this is a function definition
{
return q*p;
}

Note:

1. The function name, return type and the parameter types are the same for both the
prototype and function definition
2. The parameter names in the function’s prototype are quantity and price, but the
parameter names in the function’s definition are q and p. It implies that the names in
the prototype are not used; hence their role is to serve as information to the
programmer.

10.3 DEFINITION OF A FUNCTION

A function definition guides the compiler on how the function works. There is no function
that can be called from any other function unless it has been declared. The definition of a
function consists of the header and its body. The header is exactly like the function prototype,
except that the parameters must be named and that it has a semi-colon.

A function definition must provide names for all the parameters, and its body must be
surrounded by braces. All the statements within the body must be terminated with semi-
colons. The function definition is ended with a closing brace and not with a semi-colon.

10.4 ARGUMENTS OF A FUNCTION

The arguments of a function can be of different types. All valid expressions that are legal in
C++ language qualify to be arguments of a function. These include:

1. constants
Committed to Creativity, Excellence and Self – Reliance Page 85
of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

2. mathematical expressions
3. logical expressions
4. all other functions that return a value.

Note: a function can also be used as a parameter to another function.

10.5 RETURN VALUES

In order to return a value from a function, the keyword return is written followed by the
value to be returned. The following are return statements are all legal:

1. return 5;
2. return (y > 12);
3. return (MyFunction());

The value in the second return statement will be zero if y is not greater than 12. The value
returned in this case is the value of the expression (i.e. false or true) but not the value of y.
When the return keyword is executed, the expression following return is returned as the
value of the function.

10.6 ACTIVITIES

1. By using a suitable example, distinguish between declaration and definition of a


function in C++
2. Explain the role of the main ( ) function in a C++ program
3. Different entities in a C++ program can communicate. What role do the functions
defined in such entities play to facilitate the communication?
Distinguish between the logical expressions and mathematical expressions

Committed to Creativity, Excellence and Self – Reliance Page 86


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

11. CLASSES AND OBJECTS IN C++

This topic introduces the basics of classes and objects in C++ programming. It explains the
concepts of declaring classes, creating objects of a class, accessing class members and
defining members of a function

LECTURE OBJECTIVES

At the end of this lecture the student should be able to;

i) Define basic concepts of classes and objects in programming


ii) Demonstrate how to declare a class
iii) Illustrate how to create objects of declared class
iv) Explain how to access class members
v) Define members of declared function

SUBTOPICS

 Basics of C++ classes


 Declaration of a class
 Creation of objects
 Accessing class members
 Definition of member functions

Committed to Creativity, Excellence and Self – Reliance Page 87


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

11.1 BASICS OF C++ CLASSES

A class is a collection of variables of similar type. It is a way of binding the data and its
associated functions together. A class can consist of any combination of the variable types
and also other class types. The variables in a class are known as member variables or data
members. The functions in a class manipulate the member variables and are known as
member functions or methods of the class. The member functions are as much a part of a
class as the member variables and determine what the objects of a class can do.

11.2 DECLARATION OF A CLASS

A class is declared by using the keyword class followed by an opening brace and then list the
data members and methods of that class. A class declaration ends with a semi-colon. A class
specification has two parts, namely:

a) Class declaration: This is the part that describes the type and scope of its members.
b) Class function definitions: This part describes how the functions are Implemented

class class_name
{
private:
Declarations of variables;
Declarations of functions;
public:
Declarations of variables;
Declarations of functions;
};

A class is a logical abstraction, but an object has physical existence. The access-specifier can
be:

a) Public: Allow functions or data to be accessible to other parts of the program.


b) Private: May be accessed only by other members of the class. All members of a class
are private by default.

Example 1:

class fruit
{
private:
int quantity;

Committed to Creativity, Excellence and Self – Reliance Page 88


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

float price;
public:
void getdata (int x, float y);
void putdata (void);
};

A class should be given a meaningful name, such as fruit, because it becomes a new type
identifier that is used in declaring instances of that class type. The above example has two
data members and two function members, which are private and public respectively. The data
cannot be accessed by any function that is not a member of the class fruit.

11.3 CREATION OF OBJECTS

The declaration of the class in Example 1 above does not define any objects of fruit but it
only specifies what they contain. The class name is used to create variables (objects) of that
type.

Example 2 (Creation of objects)

fruit mango, apple, lemon; // memory for mango, apple, and lemon is created. The objects
mango, apple, lemon are variables of type fruit. It is important to note that class specification
provides a template for creating objects but does not create any memory space for the objects.
The Objects can also be created by placing their names immediately after the closing brace,
shown below:

class fruit

private:

int quantity;

float price;

public:

void getdata (int x, float y);

void putdata (void);

} mango, apple, lemon;

Committed to Creativity, Excellence and Self – Reliance Page 89


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

11.4 ACCESSING CLASS MEMBERS

The format for calling a member function is as follows:


object_name.function_name (actual arguments);

Example 3: (Accessing Class Members)

mango.getdata (115, 246.5);

This is a valid statement because it assigns the values 115 to quantity and 246.5 to price of
the object mango by implementing the getdata () function. The assignments occur in the
actual function. A statement like the one shown below displays the values of the data
members, since a member function can be invoked only by using an object of the same class:
mango.putdata ( ); This statement sends a message to the mango object requesting to
display its contents.

11.5 DEFINITION OF MEMBER FUNCTIONS

A member function can be defined in two parts, namely outside the class definition or inside
the class definition as shown in the following examples below:

11.5.1 OUTSIDE CLASS DEFINITION

The general format of defining a member function outside the class definition is as follows:

return-type class-name :: function-name(argument declaration)


{
Function body
}
The membership class label (also known as, scope resolution operator) :: tells the compiler
that the function-name belongs to the class class-name. It implies that the scope of the
function is confined to the class-name specified in the header line.

Example 4
void fruit::getdata(int x, float y)
{
quantity = x;
price = y;
}
void fruit::putdata(void)
{
cout<< “quantity : “<<quantity<<endl;
cout<< “price : “<<price<<endl;
}

Committed to Creativity, Excellence and Self – Reliance Page 90


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

The return type of the functions is void because they do not return any value. Member
functions have the following special characteristics:

a) Different classes can use the same function name


b) The member functions can access private data of the class
c) Member function can call another member function without using a dot operator

11.5.2 INSIDE CLASS DEFINITION

The general format of defining a member function inside the class definition is as follows:

class fruit
{
private:
int quantity;
float price;
public:
void getdata (int x, float y);

void putdata (void) // definition inside class


{
cout<<quantity<<endl;
cout<<price<<endl;
}
};

Note: It is only the small functions that are defined inside the class definition.

Example 5: (A C++ Program with a Class)

// This program demonstrates how a class is implemented in a C++ program

#include<iostream.h>

class fruit
{
private:
int quantity;
float price;
public:
void getdata (int x, float y); // function prototype declaration
void putdata (void) // definition inside class
{
cout<< “quantity :” <<quantity<<endl;
cout<<“price :”<<price<<endl;
}
};

Committed to Creativity, Excellence and Self – Reliance Page 91


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

// member function is defined below

void fruit::getdata(int x, float y)


{
quantity = x; // these are private variables
price =y; // being used directly
}
// the main program is as coded below
int main()
{
fruit mango; // creation of mango object
cout<< “\n object mango”<<endl;

mango.getdata(115, 246.5); // calling a member function


mango.putdata(); // calling a member function

fruit apple; // creation of apple object


cout<< “\n object apple”<<endl;

apple.getdata(10, 300); // calling a member function


apple.putdata(); // calling a member function
return 0;
}

EXPLANATION:

This class (fruit) contains:

a) Two private variables, namely quantity and price


b) Two public functions, namely; getdata ( ) and putdata ( )

The member function getdata ( ) supplies values to the two variables, quantity and price, by
using the statements:
 quantity = x;
 price =y;
It therefore implies that the member functions can have direct access to private data items.
The member function putdata ( ) has been defined inside the fruit class, and its role is to
display the values of the private variables quantity and price.

The output of this program is:

object mango
quantity : 115
price : 246.5

object apple
quantity : 10
price : 300

Committed to Creativity, Excellence and Self – Reliance Page 92


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

11.6 ACTIVITIES

1. Distinguish between classes and objects as used in the Object – Oriented


Programming
2. Discuss the main concepts that make Object – Oriented Programming to be attractive
to the global computer programming community
3. Explain how the use of classes in C++ Languages enhances the security of the
programs developed in such language
4. By using suitable examples, explain how:-
a) A class can be declared in the C++ Language
b) A function can be defined inside and outside a class
c) A member function can be called

1)

Committed to Creativity, Excellence and Self – Reliance Page 93


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)


lOMoARcPSD|32867904

REFERENCES

Baragurusammy F. (2006). Object – Oriented with C++. Third edition. Tata McGraw Hill

Publishing Company Limited

James Roberge. Data Structures in C++

Jesse Liberty. (2005) sams Teach Yourself C++ in 24 Hours. Pearson Group

Mark B., Terry W. Whitney. (2009). Object – Oriented Programming: http//www.

Educ.queensu.ca/ (Accessed 25th February 2009)

Robert W. S. Concepts of Programming Languages

Yedidyah L. Moshe J.A , Aaron M.T. Data structures Using C and C++

Tyler McMaster (2009). The difference between Object – Oriented Programming and

Procedure – Oriented Programming. http//www.helium/ (Accessed 25th February 2009)

http//www.landofcode.com (Accessed 25th February 2009)

Committed to Creativity, Excellence and Self – Reliance Page 94


of 94

Downloaded by Liffer Mongare (mongarewyclif2@gmail.com)

You might also like