BMS 201 C++ Notes 2021
BMS 201 C++ Notes 2021
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.
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.
3
Machine dependent Machine independent
Does not contain library of inbuilt functions Incorporate library of inbuilt functions
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.
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 4 Function 5
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
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
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
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
STOP
18
4) As a programmer, you are told to write a program for computing the sum of the first 20 positive integers.
The program is supposed to output the sum after computing
i) Write an algorithm for performing the above task
ii) Rewrite the above algorithm using the flowchart method
5) A supermarket is planning to give discounts to its customers based on the total costs of purchases made
by the customer. Discounts are given as follows:
- Total sales exceeding 5000/=, discount is 8%
- Sales greater than 3000/= and less than 5000/=, discount is 5%
- Sales greater than or equal to 1500/= and less than 3000/=, discount is 2%
- Sales less than 1500/=, no discount
Required: Develop an algorithm and draw up a flowchart for a program that can be used to control this process
19
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.
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
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
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.
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
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
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;
}
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 !=
37
break;
case 2:
cout << “x is 2”;
break;
default:
cout << “ value of x unknown”;
return 0;
}
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
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.
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 !
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
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;
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);
class fruit
{
private:
int quantity;
float price;
public:
void getdata (int x, float y); // function prototype declaration
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;
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