0% found this document useful (0 votes)
25 views

BMS 201 C++ Notes 2021

The document discusses the history and evolution of programming languages from low-level machine languages to modern high-level languages. It begins by explaining that early programs were written in machine language using 1s and 0s, which was difficult for humans. This led to the development of assembly languages that used mnemonics instead. It then discusses the creation of high-level languages like FORTRAN, COBOL, and BASIC that abstracted programming further from hardware. Modern languages like Java and C++ are classified as fifth generation languages that are very human-like. The document also provides brief descriptions of languages commonly used for scientific, business, and general purposes programming.

Uploaded by

Brian Mutua
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

BMS 201 C++ Notes 2021

The document discusses the history and evolution of programming languages from low-level machine languages to modern high-level languages. It begins by explaining that early programs were written in machine language using 1s and 0s, which was difficult for humans. This led to the development of assembly languages that used mnemonics instead. It then discusses the creation of high-level languages like FORTRAN, COBOL, and BASIC that abstracted programming further from hardware. Modern languages like Java and C++ are classified as fifth generation languages that are very human-like. The document also provides brief descriptions of languages commonly used for scientific, business, and general purposes programming.

Uploaded by

Brian Mutua
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

BMS 201: Computer Programming / Object Oriented Programming

Basic concepts of programming


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

Over the years programming has evolved significantly.


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

Assembly Languages – second generation programming languages


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

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

High level languages


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

Business Oriented languages.


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

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

Natural languages - fifth generation programming languages


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

Comparison between low & high level languages

Low level languages High level languages


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

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

Choice of programming language


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

COBOL: The Language of Business


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

BASIC: The Beginner's Language


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

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

RPG: Report Generation


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

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

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

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

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

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

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

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

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

8
Main Program

Function 1 Function 2 Function 3

Function 4 Function 5

POP Program Structure


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

OBJECT ORIENTED PROGRAMMING (OOP) TECHNIQUE


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

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

Data Data
Communication

Functions Functions

Functions

Data
OBJECT Y
General organization of data and functions

BASIC CONCEPTS OF OOP


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

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

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

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

12
vii) As good program documentation which is needed for various purposes

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

TYPES OF FLOW CHARTS


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

The word start or stop must be written inside the symbol


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

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

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

13
d) Decision Symbol: A decision – making point is represented using a diamond 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) Connector Symbol: This is represented with a circular symbol, in which two parts of a program
flowchart join or connect:

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

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

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

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

14
<0 >0

=0

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

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

15
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
b) flowchart

16
c)
Start

Count = 0

Sum = 0

Read X

Sum = Sum + X

Count = Count + 1

NO
Is
Count =

YES

Output Sum

Stop

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

START

READ A, B C

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

PRINT B PRINT C PRINT C PRINT A

STOP

LIMITATIONS OF USING FLOWCHARTS


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

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

THE C++ PROGAMMING LANGUAGE


THE BASICS OF C++
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++
runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. 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.

CHARACTERISTICS OF A GOOD 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.
1. The computer program should solve the target problem.
2. 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.
3. 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.
4. 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:
i) Dividing the program into modules

19
ii) Making sure that the program is well-documented
iii) Using symbolic constants
5. 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.
 Always initialize relevant variables.
 Avoid syntactic constructs that could lead to undesirable interpretation.
6. 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.
7. 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.
CREATING A C++ SOURCE FILE
The C++ programs can be created using any text editor. Examples of the text editors include:
i) vi
ii) ed
iii) edlin
iv) brief
v) notepad.
In order for the file to recognize 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:
i) Click C++ Source File
ii) Write the File name (NB: The filename should end with .cpp extension)
iii) 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:

20
i) 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.
ii) 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.

FEATURES OF A 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:-
i) #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)
ii) include: this is an instruction to the pre-processor that gives direction concerning where to find the
file name.
iii) iostream.h : this can be read as input-output-stream.header. It enables the capturing and outputting
of data and information respectively.
iv) < >: 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:-
i) /*…*/: This is known as star-slash comment style and is used in a case where the comment runs to
more than one line
ii) //: 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:-
i) cout: this is an object used to print a message to the screen. The word cout is followed by
redirection operator <<)
ii) 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

GUIDELINES TO GOOD C++ PROGRAMMING


1) 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.
2) Declare all variables before using them in any statements.

21
3) 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.
4) Use a variable name in the case that it was declared in.
5) Never use keywords in uppercase.
6) Terminate C++ declarations, expressions and Input / Output statements with a semi colon.
7) 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
8) Always save the program every time you make changes.
9) Proof read the program to check for any errors or omissions
10) Dry run you design with some simple test data before running the code, then compare the two.

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 and the sum and average of 2 numbers.
Solution:
/* This program computes and displays the sum and average of 2 numbers.
The program was authored on the Saturday 28th February 2016 */
#include<iostream.h>
int main ( )
{
// Declaration of Variables
Int firstnum, secondnum;
// Entry of the 2 numbers
cout<<"Enter the first number "<<"\n";
cin>>firstnum;
cout<<"Enter the second number "<<"\n";
cin>>secondnum;
// The summing up process
Sum = firstnum + secondnum;
// Computation of the average of the 2 numbers
Average = Sum/2;
// Displaying the 2 numbers

22
cout<<"The sum of the 2 numbers = "<<Sum<<"\n";
cout<<"The average of the 2 numbers = "<<Average<<"\n";
return 0;
}
REVISION EXERCISE 6
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
/* This program computes and displays the product of two numbers */
#include<iostrem.h>
float main ( )
{
float x, y, product
// Entry of the two numbers
cout<<"Enter the first number \n";
cin>>x;
cout<<"Enter the second number \n";
cin>>y
// Computation of the Product
product = x * y;
// outputting the product
cout<<"The Product of the two numbers is = "<<product<<"\endl"
Return 0;
}
}
IDENTIFIERS, VARIABLES AND CONSTANTS IN C++
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:
i. Uppercase and lowercase letters are distinct

23
ii. It is only the alphabetic characters, digits and underscores that are allowed
iii. The name of the identifier cannot start with a digit
iv. A declared keyword cannot be used as a variable name
v. 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 and many more
VARIABLES
A variable is a location in the computer memory in which a value can be stored and retrieved.
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
double Decimal numbers 4
Bool Holds Boolean values 1

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";

24
cin>>Length;
Area = Width * Length;
cout<<"The Area of the rectangle is: "<<Area<<endl;
return 0;
}
DEFINITION OF A 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:
i. tell what the variables represents
ii. 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)
CREATION OF MORE 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
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;
Length = 50;
unsigned short Area = Width * Length;

25
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;
}
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;
}

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

26
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.
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.
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.
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}

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

REVISION EXERCISE
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}

INPUT/OUTPUT IN C++
STANDARD OUTPUT (cout)
On most program environments, the standard output by default is the screen, and the C++ stream object
defined to access it is cout. For formatted output operations, cout is used together with the insertion operator,
which is written as << (i.e., two "less than" signs).
cout << "Output sentence"; // prints Output sentence on
1
screen
2
cout << 120; // prints number 120 on screen
3
cout << x; // prints the value of x on screen
Notice that the sentence in the first statement is enclosed in double quotes (") because it is a string literal,
while in the last one, x is not. The double quoting is what makes the difference; when the text is enclosed
between them, the text is printed literally; when they are not, the text is interpreted as the identifier of a
variable, and its value is printed instead. For example, these two sentences have very different results:
1 cout << "Hello"; // prints Hello
2 cout << Hello; // prints the content of variable Hello
Multiple insertion operations (<<) may be chained in a single statement:
cout << "This " << " is a " << "single C++
statement";
This last statement would print the text. This is a single C++ statement. Chaining insertions is especially useful
to mix literals and variables in a single statement:
To insert a line break, a new-line character shall be inserted at the exact position the line should be broken. In
C++, a new-line character can be specified as \n (i.e., a backslash character followed by a lowercase n). For
example:

28
cout << "First sentence.\n";
1
cout << "Second sentence.\nThird
2
sentence.";
This produces the following output:
First sentence.
Second sentence.
Third sentence.

Alternatively, the endl manipulator can also be used to break lines. For example:
cout << "First sentence." << endl;
1
cout << "Second sentence." <<
2
endl;
The endl manipulator produces a newline character, exactly as the insertion of '\n' does; but it also has an

STANDARD INPUT (cin)


In most program environments, the standard input by default is the keyboard, and the C++ stream object
defined to access it is cin. For formatted input operations, cin is used together with the extraction operator,
which is written as >> (i.e., two "greater than" signs). This operator is then followed by the variable where the
extracted data is stored. For example:
1 int age;
2 cin >> age;
The first statement declares a variable of type int called age, and the second extracts from cin a value to be
stored in it. This operation makes the program wait for input from cin; generally, this means that the program
will wait for the user to enter some sequence with the keyboard. In this case, note that the characters
introduced using the keyboard are only transmitted to the program when the ENTER (or RETURN) key is
pressed.
The extraction operation on cin uses the type of the variable after the >> operator to determine how it
interprets the characters read from the input; if it is an integer, the format expected is a series of digits, if a
string a sequence of characters, etc.
1 // i/o example
2
3 #include <iostream>
4 using namespace std;
5
6 int main ()

29
{
7
int i;
8
cout << "Please enter an integer value: ";
9
cin >> i;
10
cout << "The value you entered is " << i;
11
cout << " and its double is " << i*2 << ".\
12
n";
13
return 0;
14
}
As you can see, extracting from cin seems to make the task of getting input from the standard input pretty
simple and straightforward. But this method also has a big drawback. What happens in the example above if
the user enters something else that cannot be interpreted as an integer? Well, in this case, the extraction
operation fails. And this, by default, lets the program continue without setting a value for variable i, producing
undetermined results if the value of i is used later.

OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is
rich in built-in operators and provides the following types of operators –
Assume variable A holds 10 and variable B holds 20, then-
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators

Arithmetic Operators
Operator Description Example
+ Adds two operands A + B will give 30
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
- Subtracts second operand from the first A - B will give -10
% Modulus Operator and remainder of after an B % A will give 0
integer division
++ increases integer value by one A++ will give 11
-- Decreases integer value by one A-- will give 9

30
Relational Operators
There are following relational operators supported by C++ language. Assume variable A holds 10 and variable B
holds 20, then −
== Checks if the values of two operands are equal (A == B) is not true.
or not, if yes then condition becomes true.
!= Checks if the values of two operands are equal (A != B) is true.
or not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less than (A < B) is true.
the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.
<= Checks if the value of left operand is less than or (A <= B) is true.
equal to the value of right operand, if yes then
condition becomes true.

Logical Operators
There are following logical operators supported by C++ language. Assume variable A holds 1 and variable B
holds 0, then −
&& Called Logical AND operator. If both the operands (A && B) is false.
are non-zero, then condition becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands is non-zero, then condition becomes
true.

! Called Logical OR Operator. If any of the two !(A && B) is true.


operands is non-zero, then condition becomes
true.

Assignment Operators
There are following assignment operators supported by C++ language −

31
= Simple assignment operator, Assigns values from right C = A + B will assign value of A + B
side operands to left side operand. into C

+= Add AND assignment operator, It adds right operand C += A is equivalent to C = C + A


to the left operand and assign the result to left
operand.

-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C = C - A


operand from the left operand and assign the result
to left operand.

*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C = C * A


operand with the left operand and assign the result to
left operand.

/= Divide AND assignment operator, It divides left C /= A is equivalent to C = C / A


operand with the right operand and assign the result
to left operand.

%= Modulus AND assignment operator, It takes modulus C %= A is equivalent to C = C % A


using two operands and assign the result to left
operand.

PROGRAM 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.1 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 below:

Diagram

32
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 below:

Diagram

Examples of selection control structures include;


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>
int main ( )
{
if (x == 100)

33
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”;
}

34
else
cout<<“ y is greater than x \n”;
return 0;
}
The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very usefull to test various
conditions using single if...else if statement.
When using if, else if , else statements there are few points to keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax:
The syntax of an if...else if...else statement in C++ is:
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}
Example:
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:

35
int a = 100;
// check the boolean condition
if( a == 10 )
{
// if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}
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;
}

36
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
Less than <
Greater than >
Equals ==
Less than or Equals <=
Greater than or equals >=
Not equals !=

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”;

37
break;
case 2:
cout << “x is 2”;
break;
default:
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;
}

38
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.
Further Example:
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :

39
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
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 below

Diagram

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

40
#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

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>

41
int main ( )
{
int n;
cout << “Enter the starting number:”;
cin >> n;
while (n > 0)
{
Cout << n << “ , ”;
– – n;
}
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
Question: Write a program for the count up to 10.

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>

42
int main ( )
{
int n;
for (n < 0; n = 10; n ++ )
{
cout << n << “ , ”;
return 0;
}
The output of the above program is:-
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Question: Consider and explain the following for statement
for (n = 0; i = 100; n != i; n++; i – –)

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

43
- 10, 9, 8, 7, 6, 5, 4
- Count down Aborted!
THE 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 !

THE CONTINUE 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;

44
}
The output of the above goto program is:-
- 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
- FIRE !

REVISION EXERCISE
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
ARRAYS IN C++
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.
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>

45
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;
}
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

46
3:4
4:5
5:6
6:7
7:8
8:9
9:10
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
int studentMarks [7] = {75, 60, 80, 68, 78, 82, 71};
This array has seven elements of integer type.
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 ( )
}
}

47
return 0;
}

Explanation:
1. The initialized arrayExample array has 24 integer values
2. The first for loop helps to read through the different rows whereas the second
for loop helps in reading through the different columns
3. 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.
4. The output of the program is as follows:
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4

REVISION EXEERCISE 9
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
FUNCTIONS IN C++
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.

48
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.
DECLARATION AND DEFINITION 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
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 !!

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

50
REVISION EXERCISE
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?
4. Distinguish between the logical expressions and mathematical expressions

CLASSES AND OBJECTS IN C++


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

51
{
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.
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.
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;

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

52
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.
DEFINITION OF MEMBER FUNCTIONS
A member function can be defined in two parts, namely:
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;
}
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
INSIDE CLASS DEFINITION
The general format of defining a member function inside the class definition is as follows:

53
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;
}
};
// member function is defined below

54
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

55
price : 246.5
object apple
quantity : 10
price : 300
REVISION EXERCISE
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

56

You might also like