Sma 191 Computer Programming
Sma 191 Computer Programming
KENYATTA UNIVERSITY
A MODULE FOR:
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
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
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
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
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
SUBTOPICS
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
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 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.
4. Familiarize themselves with the new emerging technologies in order to put them to
optimal use.
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.
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
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
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.
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
This topic introduces the generations of computer programming and an overview of selected
computer programming languages
LECTURE OBJECTIVES
SUBTOPICS
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.
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.
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.
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.
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
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.
Data Division: The variables 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.
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.
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
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.
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:
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
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
Polymorphism
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
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.
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.
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:
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.
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
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
SUBTOPICS
The following are the factors considered by computer programmers when evaluating
programming languages:
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:
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.
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
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.
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
affect writability. The following features contribute towards the writability of a programming
language:
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.
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.
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.
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
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.
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
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.
This refers to the corporate entity that controls the evolution of a language and its associated
development environment.
Example:
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
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
SUBTOPICS
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
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.
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.
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.
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).
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.
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?”
Example: Consider the problem: "calculate the month end closing balance for an account."
The process is take the starting balance, subtract all the debits and adds all the credits for the
period and then you arrive at closing balance. The key point for procedural programming is
identification and articulation of the process or steps that must be followed.
In general terms, POP is a methodology for modelling the real world or the problem being
solved, by determining the steps and the order of those steps that must be followed in order to
reach a desired outcome or specific program state.
The general structure of a POP program is as shown in the figure (i) below:
Main Program
Function 4 Function 5
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 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.
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.
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 general organization of data and functions in an OOP program is as shown below:
OBJECT W OBJECT X
Data Data
Functions
Data
OBJECT Y
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.
Inheritance: The ability to create a new class by adding to or overriding parts of an existing
class. The objects of the new class acquire the properties of objects of another class. This
concept supports the concept of hierarchical classification (i.e. each derived class shares
common characteristics with the class from which it is derived). The inheritance concept
provides the idea of re-usability (i.e. additional features can be added to an existing class
without modifying it).
Class Hierarchy: This refers to a set of classes and their interrelationships. It helps to picture
class hierarchies to be having super-class (parent class) at the top and the subclass (child
classes) below.
Polymorphism: The ability to take more than one form. It can also be defined as the ability
to use the same syntax for objects of different types.
Example:
e.g.: 3 + 5 = 8,
ii) For two words generates a third string through concatenation of the wo
strings. e.g.:
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.
Data Abstraction: refers to the act of representing essential features without including the
background details or explanations.
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
This concept enables the building of systems that directly model or simulate their real-world
counter-parts.
4.5 ACTIVITIES
1) Describe the difference between Proprietary Software and Free Open Source Software
5: PROGRAMMING METHODOLOGY
LECTURE OBJECTIVES
SUBTOPICS
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.
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
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.
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
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,
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:
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 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:
Besides these symbols other symbols are used to develop a flowchart depending on the
nature of the program to be represented using a flowchart
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.
<0 >0
=0
Write within standard symbols briefly. As necessary, you can use the annotation symbol
to describe data or computational steps more clearly.
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.
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
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
Sum = Sum + X
Count = Count + 1
Step 5: Decision Point i.e. establishing whether the Count value is equal to 35
b) flowchart
Start
Count = 0
Sum = 0
Read X
Sum = Sum + X
Count = Count + 1
NO
Is
Count
YES
Output Sum
Stop
Example 2
Solution:
START
READ A, B
YES NO IS
YES YES
IS IS
B> A> A>
STOP
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.
5.5 ACTIVITIES
2) Explain the situations in which the flowcharts are found to be suitable tools
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
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
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
SUBTOPICS
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.
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 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
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.
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
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.
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 5: From the New Dialog box click Files option, then:
Step 6: Write the source program on the blank window that opens, and click the Save
icon on completion.
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.
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
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
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
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) Describe the difference between Proprietary Software and Free Open Source Software
2)
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
SUBTOPICS
7.1 IDENTIFIERS
7. 2 VARIABLES
A variable is a location in the computer memory in which a value can be stored and retrieved.
Different variables occupy different memory sizes as dictated by their size. See table (i)
below:
The following program can be used to determine the sizes of the respective variables:
Example 1
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
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:
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)
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:
Example 6:
//This program demonstrates the assignment of values to variables
#include<iostream.h>
int main ( )
{
unsigned short Width = 10, Length;
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:
#include<iostream.h>
int main ( )
Length = 50;
return 0;
7.3 CONSTANTS
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.
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;
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):
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:
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.
To define a constant, the keyword #define is written followed by the constant name, and the
value as shown below:
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.
The keyword const provides a more advantageous way of defining constants, unlike the
#define keyword. Eg
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.
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
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
The Green, Blue, Yellow and Orange colours will take the values 50, 51, 52, and 150
respectively.
7.4 ACTIVITIES
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
SUBTOPICS
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
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
The program is executed from code line to the next in a sequential manner
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
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:
int main ( )
{
if (x == 100)
cout <<”x is 100”;
else
cout<<”x is not 100”;
return 0;
}
if (expression1)
{
if (expression2)
Committed to Creativity, Excellence and Self – Reliance Page 66
of 94
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.
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;
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
Equals ==
Not equals !=
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:
default:
cout << “ value of x unknown”;
return 0;
}
#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;
}
#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;
}
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
False
Action 3
Exit
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
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.
#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 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
#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 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:
{
statement 1;
}
statement 2;
#include<iostream.h>
int main ( )
{
int n;
for (n > 0; n = 10; n ++ )
{
cout << n << “ , ”;
}
cout << “FIRE !”;
return 0;
}
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- FIRE !
- 10, 9, 8, 7, 6, 5, 4
- Count down Aborted!
- 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- FIRE !
Committed to Creativity, Excellence and Self – Reliance Page 74
of 94
- 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
1) Describe the difference between Proprietary Software and Free Open Source Software
2)
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
SUBTOPICS
Introduction to arrays
Declaration of arrays
Initialization of arrays
Multidimensional arrays
Accessing objects of arrays
Example 1:
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:
Explanation:
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
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
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
int studentMarks [7] = {75, 60, 80, 68, 78, 82, 71};
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.
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
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
Example 6
#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;
}
9.5 ACTIVITIES
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
SUBTOPICS
Introduction to functions
Declaration of functions
Definition of functions
Arguments of a function
Return values of a function
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.
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.
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.
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.
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.
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
2. mathematical expressions
3. logical expressions
4. all other functions that return a value.
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
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
SUBTOPICS
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.
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:
Example 1:
class fruit
{
private:
int quantity;
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.
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.
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:
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.
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:
The general format of defining a member function outside the class definition is as follows:
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;
}
The return type of the functions is void because they do not return any value. Member
functions have the following special characteristics:
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);
Note: It is only the small functions that are defined inside the class definition.
#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;
}
};
EXPLANATION:
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.
object mango
quantity : 115
price : 246.5
object apple
quantity : 10
price : 300
11.6 ACTIVITIES
1)
REFERENCES
Baragurusammy F. (2006). Object – Oriented with C++. Third edition. Tata McGraw Hill
Jesse Liberty. (2005) sams Teach Yourself C++ in 24 Hours. Pearson Group
Yedidyah L. Moshe J.A , Aaron M.T. Data structures Using C and C++
Tyler McMaster (2009). The difference between Object – Oriented Programming and