0% found this document useful (0 votes)
27 views146 pages

System Development Theme Module (Sisay Wayu)

system development

Uploaded by

Umer Hassanur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views146 pages

System Development Theme Module (Sisay Wayu)

system development

Uploaded by

Umer Hassanur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 146

MODULE FOR EXIT EXAM TUTORIAL

DEPARTMENT OF INFORMATION TECHNOLOGY

THEMATIC AREA: System development


 Programming Using C++
 Object Oriented System Analysis and Design
 Object Oriented Programming
 Data Structure and Algorithms
 Mobile Computing

APRIL 2024.
TABLE OF CONTENTS

Introduction ................................................................................................................................. 1
I. Background ...................................................................................................................... 1
II. Module Descriptor: ....................................................................................................... 1
Sub theme 1: Programing using c++ ....................................................................................... 3
Unit 1: Overview of programing in c++ ................................................................................. 3
1.1. Introduction ............................................................................................................. 3
1.2. Basics of C++ programing ...................................................................................... 7
1.3. Control statements ................................................................................................ 14
Unit 2: Arrays ........................................................................................................................ 23
2.1 Introduction ........................................................................................................... 23
2.2 What is an arrays .................................................................................................. 24
2.3 Declaration of Arrays ........................................................................................... 24
2.4 Accessing Array Elements .................................................................................... 25
2.5 Initialization of arrays .......................................................................................... 27
2.6 Multidimensional arrays ...................................................................................... 30
Unit 3: Pointer ....................................................................................................................... 32
3.1 Introduction ........................................................................................................... 32
3.2 Dynamic Memory .................................................................................................. 33
3.3 Pointer arithmetic ................................................................................................. 34
3.4 Function Pointers .................................................................................................. 35
Unit 4: Structure .................................................................................................................... 37
4.1 Concept of structure in problem solving............................................................. 37
4.2 struct Specification: Defining Structures ............................................................ 38
4.3 Declaring and using sturct data types ................................................................. 39
4.4 Initializing Structure Variables ........................................................................... 39
4.5 Declaring struct types as part of a struct ............................................................ 41
Unit 5: File management ....................................................................................................... 42
5.1 Managing files using C++. ........................................................................................ 42
5.2 C++ File I/O Classes and Functions......................................................................... 44
5.3 Binary File processing ............................................................................................... 47
5.4 Random Access Files ................................................................................................. 51
5.5 Obtaining the Current File Position ........................................................................ 51
Self-check questions .............................................................................................................. 53
REFERENCES: ..................................................................................................................... 55
i
Sub theme 2: Object Oriented system analysis and Design...................................................... 56
Unit 1: Basic concepts of object-oriented system analysis and design ................................. 56
1.1 Object Oriented Approach ....................................................................................... 56
1.2 Basic Characteristics of Object-Oriented System .................................................. 57
1.3 Benefits of Object - Oriented Systems Analysis and Design (Why to Use?) ........ 61
Unit 2: Requirement Elicitation ............................................................................................ 61
2.1 Introduction ............................................................................................................... 61
2.2 Activities in requirement elicitation ........................................................................ 63
Unit 3: Requirement analysis ............................................................................................. 63
3.1 Introduction ............................................................................................................... 63
3.2 Goal of Object Oriented Analysis ............................................................................ 65
3.3 Use case modelling ..................................................................................................... 65
Unit 5: System Design ......................................................................................................... 70
5.1 Different diagrams that can be used at design phase ............................................. 71
5.2 Describing an architecture using UML ................................................................... 72
Self-check questions .............................................................................................................. 73
REFERENCES: ..................................................................................................................... 77
Sub theme 3: Object Oriented Programing ............................................................................... 78
Unit 1: Introduction to object oriented programing .............................................................. 78
1.1 Principles and Concepts of Object-Oriented Programming (OOP) ..................... 78
Unit 2: Basics in java programing ..................................................................................... 80
1.1 identifiers, data types, operators and control structures in Java. ........................ 80
1.2 Operators ................................................................................................................... 83
1.3 Control structure ....................................................................................................... 84
Unit 3: Objects and classes .................................................................................................... 87
3.1 Introduction ............................................................................................................... 87
3.2 Declaring a Variable of a Class Type ...................................................................... 88
3.3 Initializing an Object................................................................................................. 88
3.4 Constructors in Java ................................................................................................. 89
Unit 4: Objects oriented programing concept ....................................................................... 90
4.1 Inheritance ................................................................................................................. 90
4.2 Encapsulation............................................................................................................. 91
Self-check .............................................................................................................................. 93
REFERENCE ............................................................................................................................ 95
Sub theme 4: Data Structure and algorithm ............................................................................. 96

ii
Unit 1: Common algorithm analysis techniques ............................................................... 96
1.1 Introduction ............................................................................................................... 96
Unit 2: Swapping of various sorting and searching algorithms. ........................................... 97
2.1 Searching .................................................................................................................... 98
2.2 Sorting Algorithms .................................................................................................. 100
Unit 3: ADT linked list operations ...................................................................................... 104
3.1 Creating Linked Lists in C++ ................................................................................. 104
3.2 Adding a node to the list ......................................................................................... 104
Unit 4. Stack and Queue ...................................................................................................... 106
4.1 Standard Stack Operations .................................................................................... 107
4.2 A queue ..................................................................................................................... 108
4.3 Traversing through a tree data structure. ............................................................ 110
Self-check questions ............................................................................................................ 112
REFERENCES ........................................................................................................................ 113
Sub theme 5: Mobile Computing ............................................................................................ 114
Unit 1: Fundamental concepts of wireless communication ................................................ 114
1.1 Introduction ............................................................................................................. 114
1.2 Components of a cellular mobile network ............................................................ 116
Unit 2: Computing trends and mobile computing .......................................................... 118
2.1 Introduction ............................................................................................................. 118
2.2 Mobile communication............................................................................................ 118
2.3 Trends in Computing .............................................................................................. 119
Unit 3: Producing Android based mobile application ................................................... 121
3.1 Introduction ............................................................................................................. 121
3.2 Architecture of android .......................................................................................... 122
3.3 Android Application Components ......................................................................... 123
3.4 Android Service Component .................................................................................. 124
3.5 Activity ..................................................................................................................... 126
3.6 Android Menus ........................................................................................................ 130
Unit 4: Event handling methods, Intents and data handling with in android app
development ....................................................................................................................... 131
4.1 Event listeners .......................................................................................................... 132
4.2 Event handlers ......................................................................................................... 133
4.3 Event Listener Registration .................................................................................... 134
4.4 Event Handling using XML Layout file ................................................................ 135
4.5 Event handling implementation listener interfaces .............................................. 136

iii
Self-check questions ............................................................................................................ 137
REFERENCES: ................................................................................................................... 139

iv
Introduction
I. Background
The exit examination module has been meticulously designed to equip students with the
essential skills and knowledge required to excel in their final assessments. Recognizing the
significance of these examinations as pivotal milestones in their academic journey, this
module serves as a comprehensive guide tailored to empower students with the confidence and
proficiency needed to navigate through the challenges of the exit exams successfully.

Understanding the complexities and expectations associated with exit examinations, this
module aims to provide students with a structured approach to preparation, covering key
topics, exam formats, and strategies to optimize their performance. By fostering a deep
understanding of the exam syllabus and offering targeted practice materials, students can
enhance their proficiency levels and alleviate anxiety associated with the examination process.

Furthermore, this module recognizes the diverse learning styles and preferences among
students and incorporates versatile teaching methodologies to cater to individual needs
effectively. Whether through interactive multimedia resources, practice quizzes, or
collaborative learning activities, students are encouraged to actively engage with the material
and consolidate their learning in a meaningful manner.

II. Module Descriptor:


This comprehensive training module covers essential system development thematic topics in
information technology. It is designed to provide students with a solid foundation in key areas
including Programming Using C++, Object-Oriented System Analysis and Design (OOSAD),
Object-Oriented Programming (OOP), Data Structures and Algorithms, and Mobile
Computing.
In today's rapidly evolving technological landscape, proficiency in these fundamental concepts
is indispensable for aspiring developers and seasoned professionals alike. Whether you're a
newcomer to the field or seeking to enhance your skills, this training program will equip you
with the knowledge and practical insights needed to excel in software development and related
domains.
Throughout this module, you will delve into the intricacies of C++ programming, exploring its
syntax, features, and best practices. You will also learn how to apply object-oriented principles

1
to analyze, design, and develop robust software systems, gaining a deeper understanding of the
underlying concepts and methodologies.
Moreover, this module will guide you through the principles of object-oriented programming,
illustrating how to leverage encapsulation, inheritance, and polymorphism to create modular
and maintainable code. You will explore advanced topics such as design patterns and
architectural paradigms, empowering you to craft elegant solutions to complex problems.
Additionally, you will delve into the realm of data structures and algorithms, learning how to
efficiently store and manipulate data to optimize the performance of your applications. From
basic data structures like arrays and linked lists to advanced algorithms like sorting and
searching, you will acquire the tools necessary to tackle algorithmic challenges with
confidence.
Furthermore, this module will help you to revise the exciting field of mobile computing,
covering topics such as mobile application development, platform-specific considerations, and
emerging trends in mobile technology. Whether you're interested in developing Android apps,
iOS apps, or cross-platform solutions, this training program will provide you with the essential
knowledge and skills to thrive in the mobile development ecosystem.
By the end of this training module, you will not only have gained proficiency in C++
programming, object-oriented analysis and design, object-oriented programming, data
structures and algorithms, and mobile computing, but you will also be well-equipped to tackle
real-world software development projects with confidence and competence.

2
Sub theme 1: Programing using c++
Unit 1: Overview of programing in c++

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Be able to Design computer algorithms tools flow chart, pseudocode
 Apply computer algorithms
 Explain the basics of C++ programming.
 State the concepts of Structures in solving problems.
 Be able to define variables, operators.
 Be able to differentiate different data types.
 Be able to know the complete development cycle of C++.
 Be able to apply the concept and application of iteration and recursion in program
development

1.1. Introduction

A Computer is an electronic device that accepts data, performs computations, and makes
logical decisions according to instructions that have been given to it; then produces
meaningful information in a form that is useful to the user. In current world we live in,
computers are almost used in all walks of life for different purposes. They have been deployed
to solve different real life problems, from the simplest game playing up to the complex nuclear
energy production. Computers are important and widely used in our society because they are
cost-effective aids to problem solving in business, government, industry, education, etc.
In order to solve a given problem, computers must be given the correct instruction about how
they can solve it. The terms computer programs, software programs, or just programs are
the instructions that tells the computer what to do. Computer requires programs to function,
and a computer programs does nothing unless its instructions are executed by a CPU.
Computer programming (often shortened to programming or coding) is the process of
writing, testing, debugging/troubleshooting, and maintaining the source code of computer
programs. Writing computer programs means writing instructions that will make the computer
follow and run a program based on those instructions. Each instruction is relatively simple, yet

3
because of the computer's speed, it is able to run millions of instructions in a second. A
computer program usually consists of two elements:
 Data – characteristics
 Code – action
Computer programs (also known as source code) are often written by professionals known as
Computer Programmers (simply programmers). Source code is written in one of
programming languages. A programming language is an artificial language that can be used
to control the behavior of a machine, particularly a computer. Programming languages, like
natural language (such as Amharic), are defined by syntactic and semantic rules which
describe their structure and meaning respectively. The syntax of a language describes the
possible combinations of symbols that form a syntactically correct program. The meaning
given to a combination of symbols is handled by semantics. Many programming languages
have some form of written specification of their syntax and semantics; some are defined only
by an official implementation. In general, programming languages allow humans to
communicate instructions to machines.
A main purpose of programming languages is to provide instructions to a computer. However,
computers do exactly what they are told to do, and cannot understand the code the programmer
"intended" to write. So computers need to be instructed to perform all the tasks. The
combination of the language definition, the program, and the program's inputs must fully
specify the external behavior that occurs when the program is executed. Computer languages
have relatively few, exactly defined, rules for composition of programs, and strictly controlled
vocabularies in which unknown words must be defined before they can be used.

Available programming languages come in a variety of forms and types. Thousands of


different programming languages have been developed, used, and discarded. Programming
languages can be divided in to two major categories: low-level and high-level languages.
Low-level languages
Computers only understand one language and that is binary language or the language of 1s and
0s. Binary language is also known as machine language, one of low-level languages. In the
initial years of computer programming, all the instructions were given in binary form.
Although the computer easily understood these programs, it proved too difficult for a normal
human being to remember all the instructions in the form of 0s and 1s. Therefore, computers
remained mystery to a common person until other languages such as assembly language was
developed, which were easier to learn and understand.

4
Assembly language correspondences symbolic instructions and executable machine codes and
was created to use letters (called mnemonics) to each machine language instructions to make it
easier to remember or write. For example:

ADD A, B – adds two numbers in memory location A and B


Assembly language is nothing more than a symbolic representation of machine code, which
allows symbolic designation of memory locations.

High-level languages
The lack of portability between different computers led to the development of high-level
languages—so called because they permitted a programmer to ignore many low-level details
of the computer's hardware. Further, it was recognized that the closer the syntax, rules, and
mnemonics of the programming language could be to "natural language" the less likely it
became that the programmer would inadvertently introduce errors (called "bugs") into the
program. High-level languages are more English-like and, therefore, make it easier for
programmers to "think" in the programming language. High-level languages also require
translation to machine language before execution. This translation is accomplished by either a
compiler or an interpreter. Compilers translate the entire source code program before
execution. Interpreters translate source code programs one line at a time. Interpreters are more
interactive than compilers. FORTRAN (FORmula TRANslator), BASIC (Bingers All Purpose
Symbolic Instruction Code), PASCAL, C, C++, Java are some examples of high-level
languages.
Algorithms
An algorithm is defined as a step-by-step sequence of instructions that must terminate and
describe how the data is to be processed to produce the desired outputs. Simply, algorithm is a
sequence of instructions. Algorithms are a fundamental part of computing. There are three
commonly used tools to help to document program logic (the algorithm). These are flowcharts,
structured chart, and Pseudocode. We will use the three methods here. Generally, flowcharts
work well for small problems but Pseudocode is used for larger problems.
Pseudocode
Pseudocode (derived from pseudo and code) is a compact and informal high-level description
of a computer algorithm that uses the structural conventions of programming languages, but
typically omits detailes such as subroutines, variables declarations and system-specific syntax.
As the name suggests, pseudocode generally does not actually obey the synatx rules of any

5
particular language; there is no systematic standard form, although any particular writer will
generally borrow the appearance of a particular language.
Writing pseudocode will save you time later during the construction & testing phase of a
program's development.
Example:
Original Program Specification:
Write a program that obtains two integer numbers from the user. It will print
out the sum of those numbers.
Pseudocode:
Prompt the user to enter the first integer
Prompt the user to enter a second integer
Compute the sum of the two user inputs
Display an output prompt that explains the answer as the sum
Display the result
Structured Charts
Structured chart depicts the logical functions to the solution of the problem using a chart. It
provides an overview that confirms the solution to the problem without excessive
consideration to detail. It is high-level in nature.
Flowchart
A flowchart (also spelled flow-chart and flow chart) is a schematic representation of an
algorithm or a process. The advantage of flowchart is it doesn’t depend on any particular
programming language, so that it can used, to translate an algorithm to more than one
programming language. Flowchart uses different symbols (geometrical shapes) to represent
different processes. The following table shows some of the common symbols.
Example : - Draw flow chart of an algorithm to add two numbers and display their result.
Algorithm description
 Read the rules of the two numbers (A and B)
 Add A and B
 Assign the sum of A and B to C
 Display the result ( c)

The flow chart is:


Start

Read A, B 6

C= A+B
1.2. Basics of C++ programing

1.2.1 IDE Environment


The complete development cycle in C++ is: Write the program, compile the source code,

link the program, and run it.

Writing a Program
To write a source code, your compiler may have its own built-in text editor, or you may be
using a commercial text editor or word processor that can produce text files. The important
thing is that whatever you write your program in, it must save simple, plain-text files, with no
word processing commands embedded in the text. Examples of safe editors include Windows
Notepad, the DOS Edit command, EMACS, and vi. Many commercial word processors, such
as WordPerfect, Word, and dozens of others, also offer a method for saving simple text files.
The files you create with your editor are called source files, and for C++ they typically are
named with the extension .CPP.
Compiling

The complete development cycle in C++ is: Write the program, compile the source code, link
the program, and run it.
Compiling
Your source code file can't be executed, or run, as a program can. To turn your source code
into a program, you use a compiler.
Linking

C++ programs are typically created by linking together one or more OBJ files with one or
more libraries. A library is a collection of linkable files that were supplied with your compiler,
that you purchased separately, or that you created and compiled. All C++ compilers come with
a library of useful functions (or procedures) and classes that you can include in your program.
A function is a block of code that performs a service, such as adding two numbers or printing
to the screen. A class is a collection of data and related functions.
The steps to create an executable file are
1. Create a source code file, with a .CPP extension.
2. Compile the source code into a file with the .OBJ extension.
3. Link your OBJ file with any needed libraries to produce an executable program.
1.2.2 Basic Elements

7
Basic syntax

Basic Input/output in C++

Standard iostream objects:


cout - object providing a connection to the monitor
cin - object providing a connection to the keyboard
cerr - object providing a connection to error stream
clog – object providing a connection to logging stream
To perform input and output we send messages to one of these objects (or one that is
connected to a file)
The Insertion Operator (<<)

• To send output to the screen we use the insertion operator on the object cout
• Format: cout << Expression;
• The compiler figures out the type of the object and prints it out appropriately
cout << 5; // Outputs 5
cout << 4.1; // Outputs 4.1
cout << “String”; // Outputs String
cout << ‘\n’; // Outputs a newline
The Extraction Operator (>>)
• To get input from the keyboard we use the extraction operator and the object cin
• Format: cin >> Variable;
• The compiler figures out the type of the variable and reads in the appropriate type
int X;
float Y;
cin >> X; // Reads in an integer
cin >> Y; // Reads in a float
Chaining Calls
• Multiple uses of the insertion and extraction operator can be chained together:
cout << E1 << E2 << E3 << … ;
cin >> V1 >> V2 >> V3 >> …;
• Equivalent to performing the set of insertion or extraction operators one at a time
• Example
cout << “Total sales are birr” << sales << ‘\n’;

8
cin >> Sales1 >> Sales2 >> Sales3;
Keywords (reserved words)

Reserved/Key words have a unique meaning within a C++ program. These symbols, the
reserved words, must not be used for any other purposes. All reserved words are in lower-case
letters. The following are some of the reserved words of C++.

asm auto bool break case catch


const_cast class const char continue default
dynamic_cast do double delete else enum
explicit extern false float for friend
goto if inline int long mutable
namespace new operator private protected public
reinterpret_cast register return short signed sizeof
static_cast static struct switch template this
throw true try typedef typeid typename
union unsigned using virtual void volatile
Notice that main is not a reserved word. However, this is a fairly technical distinction, and for
practical purposes you are advised to treat main, cin, and cout as if they were reserved as well.

Identifiers

An identifier is name associated with a function or data object and used to refer to that
function or data object. An identifier must:
 Start with a letter or underscore
 Consist only of letters, the digits 0-9, or the underscore symbol _
 Not be a reserved word

For the purposes of C++ identifiers, the underscore symbol, _, is considered to be a letter. Its
use as the first character in an identifier is not recommended though, because many library
functions in C++ use such identifiers. Similarly, the use of two consecutive underscore
symbols, _ _, is forbidden.

At this stage it is worth noting that C++ is case-sensitive. That is lower-case letters are treated
as distinct from upper-case letters. Thus the word NUM different from the word num or the
word Num. Identifiers can be used to identify variable or constants or functions. Function
identifier is an identifier that is used to name a function.

Literals

9
Literals are constant values which can be a number, a character of a string. For example the
number 129.005, the character ‘A’ and the string “hello world” are all literals. There is no
identifier that identifies them.
Comments

A comment is a piece of descriptive text which explains some aspect of a program. Program
comments are totally ignored by the compiler and are only intended for human readers. C++
provides two types of comment delimiters:
Anything after // (until the end of the line on which it appears) is considered a comment.
Anything enclosed by the pair /* and */ is considered a comment.
1.2.3 Data Types, Variables, and Constants
Variables

A variable is a symbolic name for a memory location in which data can be stored and
subsequently recalled. Variables are used for holding data values so that they can be utilized in
various computations in a program. All variables have two important attributes:
 A type, which is, established when the variable is defined (e.g., integer, float,
character). Once defined, the type of a C++ variable cannot be changed.
 A value, which can be changed by assigning a new value to the variable. The kind of
values a variable can assume depends on its type. For example, an integer variable can
only take integer values (e.g., 2, 100, -12) not real numbers like 0.123.
Variable Declaration

Declaring a variable means defining (creating) a variable. You create or define a variable by
stating its type, followed by one or more spaces, followed by the variable name and a
semicolon. The variable name can be virtually any combination of letters, but cannot contain
spaces and the first character must be a letter or an underscore. Variable names cannot also be
the same as keywords used by C++. Legal variable names include x, J23qrsnf, and myAge.
Good variable names tell you what the variables are for; using good names makes it easier to
understand the flow of your program. The following statement defines an integer variable
called myAge:
int myAge;
You can create more than one variable of the same type in one statement by writing the type
and then the variable names, separated by commas. For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs

10
Assigning Values to Your Variables

You assign a value to a variable by using the assignment operator (=). Thus, you would assign
5 to Width by writing
int Width;
Width = 5;
You can combine these steps and initialize Width when you define it by writing
int Width = 5;
Data Types

When you define a variable in C++, you must tell the compiler what kind of variable it is: an
integer, a character, and so forth. This information tells the compiler how much room to set
aside and what kind of value you want to store in your variable.
Several data types are built into C++. The varieties of data types allow programmers to select
the type appropriate to the needs of the applications being developed. The data types supported
by C++ can be classified as basic (fundamental) data types, user defined data types, derived
data types and empty data types. However, the discussion here will focus only on the basic
data types.
Type Size Values
unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to 2,147,483,647
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
char 1 byte 256 character values
float 4 bytes 3.4e-38 to 3.4e38
double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932

Signed and Unsigned

As shown above, integer types come in two varieties: signed and unsigned. The idea here is
that sometimes you need negative numbers, and sometimes you don't. Integers (short and long)
without the word "unsigned" are assumed to be signed. Signed integers are either negative or
positive. Unsigned integers are always positive.

Characters

11
Character variables (type char) are typically 1 byte, enough to hold 256 values. A char can be
interpreted as a small number (0-255) or as a member of the ASCII set. ASCII stands for the
American Standard Code for Information Interchange. The ASCII character set and its ISO
(International Standards Organization) equivalent are a way to encode all the letters, numerals,
and punctuation marks.

Example

Char response; //as Y or N.

1.2.4 Operators
C++ provides operators for composing arithmetic, relational, logical, bitwise, and conditional
expressions. It also provides operators which produce useful side-effects, such as assignment,
increment, and decrement. We will look at each category of operators in turn.

Assignment Operators

The assignment operator is used for storing a value at some memory location (typically
denoted by a variable). Its left operand should be an lvalue, and its right operand may be an
arbitrary expression. The latter is evaluated and the outcome is stored in the location denoted
by the lvalue.

Operator Example Equivalent To


= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
&= n &= 0xF2F2 n = n & 0xF2F2
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4

Arithmetic Operators

C++ provides five basic arithmetic operators. These are summarized in table below

Operator Name Example


+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5

12
% Remainder 13 % 3 //gives 1
Arithmetic operators.
Relational Operators

C++ provides six relational operators for comparing numeric quantities. These are summarized
in table below. Relational operators evaluate to 1 (representing the true outcome) or 0
(representing the false outcome).

Operator Name Example


== Equality 5 == 5
!= Inequality 5 != 5
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or Equal 6.3 >= 5 // gives 1
Relational operators
Note that the <= and >= operators are only supported in the form shown. In particular, =< and
=> are both invalid and do not mean anything.

Logical Operators

C++ provides three logical operators for combining logical expression. These are summarized
in the table below. Like the relational operators, logical operators evaluate to 1 or 0.

Operator Name Example


! Logical Negation !(5 == 5)
&& Logical And 5 < 6 && 6 < 6 // gives 1
|| Logical Or 5 < 6 || 6 < 5 // gives 1
Logical operators

Logical negation is a unary operator, which negates the logical value of its single operand. If
its operand is nonzero it produces 0, and if it is 0 it produces 1.

Logical and produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces 1.
Logical or produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.

Increment/decrement Operators

The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable. These are summarized in the
following table. The examples assume the following variable definition.

int k = 5;

Operator Name Example

13
++ Auto Increment (prefix) ++k + 10 // gives 16
++ Auto Increment (postfix) k++ + 10 // gives 15
-- Auto Decrement (prefix) --k + 10 // gives 14
-- Auto Decrement (postfix) k-- + 10 // gives 15
Increment and decrement operators
Both operators can be used in prefix and postfix form. The difference is significant. When
used in prefix form, the operator is first applied and the outcome is then used in the
expression. When used in the postfix form, the expression is evaluated first and then the
operator applied. Both operators may be applied to integer as well as real variables, although
in practice real variables are rarely useful in this form.

1.3. Control statements


A running program spends all of its time executing statements. The order in which statements
are executed is called flow control (or control flow). This term reflect the fact that the
currently

executing statement has the control of the CPU, which when completed will be handed over
(flow) to another statement. Flow control in a program is typically sequential, from one
statement to the next, but may be diverted to other paths by branch statements.
This can be done using if statement. The if Statement
It is sometimes desirable to make the execution of a statement dependent upon a condition
being satisfied. The if statement provides a way of expressing this, the general form of which
is:
if (expression)
statement;

First expression is evaluated. If the outcome is nonzero (true) then statement is executed.
Otherwise, nothing happens.

14
For example, when dividing two values, we may want to check that the denominator is
nonzero:

if (count != 0)
average = sum / count;
To make multiple statements dependent on the same condition, we can use a compound
statement:
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
}
A variant form of the if statement allows us to specify two alternative statements: one which
is executed if a condition is satisfied and one which is executed if the condition is not
satisfied. This is called the if-else statement and has the general form:
if (expression)
statement1;
else
statement2;
First expression is evaluated. If the outcome is nonzero (true) then statement1 is executed.
Otherwise, statement2 is executed.
For example:
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
} else {
interest = balance * debitRate;
balance += interest;
}
Given the similarity between the two alternative parts, the whole statement can be simplified
to:
if (balance > 0)
interest = balance * creditRate;
else
interest = balance * debitRate;
balance += interest;

Or simplified even further using a conditional expression:


interest = balance * (balance > 0 ? creditRate : debitRate);
balance += interest;

Or just:
balance += balance * (balance > 0 ? creditRate : debitRate);

If statements may be nested by having an if statement appear inside another if statement. For
example:
if (callHour > 6) {
if (callDuration <= 5)

15
charge = callDuration * tarrif1;
else
charge = 5 * tarrif1 + (callDuration - 5) * tarrif2;
} else
charge = flatFee;

A frequently-used form of nested if statements involves the else part consisting of another if-
else statement. For example:
if (ch >= '0' && ch <= '9')
kind = digit;
else {
if (ch >= 'A' && ch <= 'Z')
kind = upperLetter;
else {
if (ch >= 'a' && ch <= 'z')
kind = lowerLetter;
else
kind = special;
}
}
For improved readability, it is conventional to format such cases as follows:
if (ch >= '0' && ch <= '9')
kind = digit;
else if (cha >= 'A' && ch <= 'Z')
kind = capitalLetter;
else if (ch >= 'a' && ch <= 'z')
kind = smallLetter;
else
kind = special;

The if/else Statement


• Provides two possible paths of execution

• Performs one statement or block if the expression is true, otherwise performs another
statement or block.

• General Format:

if (expression)
statement1; // or block
else
statement2; // or block

The if/else if Statement


• Tests a series of conditions until one is found to be true

16
• Often simpler than using nested if/else statements
• Can be used to model thought processes such as:

"If it is raining, take an umbrella,


else, if it is windy, take a hat,
else, take sunglasses”
if (expression)
 statement1; // or block
else if (expression)
statement2; // or block

// other else ifs .


else if (expression)
statementn; // or block

Example:

The switch Statement


The switch statement provides a way of choosing between a set of alternatives, based on the
value of an expression. The general form of the switch statement is:

switch (expression) {
case constant1:
statements;
...
case constantn:
statements;
default:
statements;
}

17
First expression (called the switch tag) is evaluated, and the outcome is compared to each of
the numeric constants (called case labels), in the order they appear, until a match is found.
The statements following the matching case are then executed. Note the plural: each case
may be followed by zero or more statements (not just one statement). Execution continues
until either a break statement is encountered or all intervening statements until the end of the
switch statement are executed. The final default case is optional and is exercised if none of
the earlier cases provide a match.
For example, suppose we have parsed a binary arithmetic operation into its three
components and stored these in variables operator, operand1, and operand2. The following
switch statement performs the operation and stores the result in result.

switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default:cout << "unknown operator: " << ch << '\n';
break;
}

As illustrated by this example, it is usually necessary to include a break statement at the end
of each case. The break terminates the switch statement by jumping to the very end of it.
There are, however, situations in which it makes sense to have a case without a break. For
example, if we extend the above statement to also allow x to be used as a multiplication
operator, we will have:

switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case 'x':
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default:cout << "unknown operator: " << ch << '\n';
break;
}

Because case 'x' has no break statement (in fact no statement at all!), when this case is
satisfied, execution proceeds to the statements of the next case and the multiplication is
performed.

18
It should be obvious that any switch statement can also be written as multiple if-else
statements. The above statement, for example, may be written as:

if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';

However, the switch version is arguably neater in this case. In general, preference should be
given to the switch version when possible. The if-else approach should be reserved for
situation where a switch cannot do the job (e.g., when the conditions involved are not simple
equality expressions, or when the case labels are not numeric constants).
Looping Statements
The ‘while’ Statement
The while statement (also called while loop) provides a way of repeating a statement while a
condition holds. It is one of the three flavors of iteration in C++. The general form of the
while statement is:

while (expression)
statement;

First expression (called the loop condition) is evaluated. If the outcome is nonzero then
statement (called the loop body) is executed and the whole process is repeated. Otherwise,
the loop is terminated.
For example, suppose we wish to calculate the sum of all numbers from 1 to some integer
denoted by n. This can be expressed as:

i = 1;
sum = 0;
while (i <= n)
sum += i;

For n set to 5, Table 2.9 provides a trace of the loop by listing the values of the variables
involved and the loop condition.

19
Table 5.1 While loop trace
Iteration i n i <= n sum += i++
First 1 5 1 1
Second 2 5 1 3
Third 3 5 1 6
Fourth 4 5 1 10
Fifth 5 5 1 15
Sixth 6 5 0

It is not unusual for a while loop to have an empty body (i.e., a null statement). The
following loop, for example, sets n to its greatest odd factor.

while (n % 2 == 0 && n /= 2)
;

Here the loop condition provides all the necessary computation, so there is no real need for a
body. The loop condition not only tests that n is even, it also divides n by two and ensures
that the loop will terminate should n be zero.

The ‘for’ Statement


The for statement (also called for loop) is similar to the while statement, but has two
additional components: an expression which is evaluated only once before everything else,
and an expression which is evaluated once at the end of each iteration. The general form of
the for statement is:

for (expression1; expression2; expression3)


statement;

First expression1 is evaluated. Each time round the loop, expression2 is evaluated. If the
outcome is nonzero then statement is executed and expression3 is evaluated. Otherwise, the
loop is terminated. The general for loop is equivalent to the following while loop:

expression1;
while (expression2) {
statement;
expression3;

20
}

The most common use of for loops is for situations where a variable is incremented or
decremented with every iteration of the loop. The following for loop, for example, calculates
the sum of all integers from 1 to n.

sum = 0;
for (i = 1; i <= n; ++i)
sum += i;

This is preferred to the while-loop version we saw earlier. In this example, i is usually called
the loop variable.
C++ allows the first expression in a for loop to be a variable definition. In the above loop,
for example, i can be defined inside the loop itself:

for (int i = 1; i <= n; ++i)


sum += i;

Contrary to what may appear, the scope for i is not the body of the loop, but the loop itself.
Scope-wise, the above is equivalent to:

int i;
for (i = 1; i <= n; ++i)
sum += i;

Any of the three expressions in a for loop may be empty. For example, removing the first
and the third expression gives us something identical to a while loop:

for (; i != 0;) // is equivalent to: while (i != 0)


something; // something;

Removing all the expressions gives us an infinite loop. This loop's condition is assumed to
be always true:

for (;;) // infinite loop


something;

21
For loops with multiple loop variables are not unusual. In such cases, the comma operator is
used to separate their expressions:

for (i = 0, j = 0; i + j < n; ++i, ++j)


something;

Because loops are statements, they can appear inside other loops. In other words, loops can
be nested. For example,

for (int i = 1; i <= 3; ++i)


for (int j = 1; j <= 3; ++j)
cout << '(' << i << ',' << j << ")\n";

produces the product of the set {1,2,3} with itself, giving the output:

(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)
The ‘do…while’ Statement
The do statement (also called do loop) is similar to the while statement, except that its body is
executed first and then the loop condition is examined. The general form of the do statement
is:
do
statement;
while (expression);

First statement is executed and then expression is evaluated. If the outcome of the latter is
nonzero then the whole process is repeated. Otherwise, the loop is terminated.
The do loop is less frequently used than the while loop. It is useful for situations where we
need the loop body to be executed at least once, regardless of the loop condition. For
example, suppose we wish to repeatedly read a value and print its square, and stop when the
value is zero. This can be expressed as the following loop:

do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);

Unlike the while loop, the do loop is never used in situations where it would have a null
body. Although a do loop with a null body would be equivalent to a similar while loop, the
latter is always preferred for its superior readability.

22
Unit 2: Arrays
Learning objectives of the unit
At the end of this unit trainees are expected to:
 Be able to define array.
 Be able to identify rule in declaring array variables.
 Be able to differentiate single and multi-dimensional array.
 Be able to apply the array variables in C++ programming.

2.1 Introduction
Variables in a program have values associated with them. During program execution these
values are accessed by using the identifier associated with the variable in expressions etc. In
none of the programs written so far have very many variables been used to represent the values
that were required. Thus even though programs have been written that could handle large lists
of numbers it has not been necessary to use a separate identifier for each number in the list.
This is because in all these programs it has never been necessary to keep a note of each
number individually for later processing. For example in summing the numbers in a list only
one variable was used to hold the current entered number which was added to the accumulated
sum and was then overwritten by the next number entered. If that value were required again
later in the program there would be no way of accessing it because the value has now been
overwritten by the later input.

If only a few values were involved a different identifier could be declared for each variable,
but now a loop could not be used to enter the values. Using a loop and assuming that after a
value has been entered and used no further use will be made of it allows the following code to
be written. This code enters six numbers and outputs their sum:

sum = 0.0;
for (i = 0; i < 6; i++)
{
cin >> x;
sum += x;
}
This of course is easily extended to n values where n can be as large as required. However if it
was required to access the values later the above would not be suitable. It would be possible to
do it as follows by setting up six individual variables:

float a, b, c, d, e, f;

and then handling each value individually as follows:

23
sum = 0.0;
cin >> a; sum += a;
cin >> b; sum += b;
cin >> c; sum += c;
cin >> d; sum += d;
cin >> e; sum += e;
cin >> f; sum += f;

which is obviously a very tedious way to program. To extend this solution so that it would
work with more than six values then more declarations would have to be added, extra
assignment statements added and the program re-compiled. If there were 10000 values
imagine the tedium of typing the program (and making up variable names and remembering
which is which)!

To get round this difficulty all high-level programming languages use the concept of a data
structure called an Array.

2.2 What is an arrays


An array is a data structure which allows a collective name to be given to a group of elements
which all have the same type. An individual element of an array is identified by its own
unique index (or subscript).
An array can be thought of as a collection of numbered boxes each containing one data item.
The number associated with the box is the index of the item. To access a particular item the
index of the box associated with the item is used to access the appropriate box. The index
must be an integer and indicates the position of the element in the array. Thus the elements of
an array are ordered by the index.

2.3 Declaration of Arrays


An array declaration is very similar to a variable declaration. First a type is given for the
elements of the array, then an identifier for the array and, within square brackets, the number
of elements in the array. The number of elements must be an integer.
For example data on the average temperature over the year in Ethiopia for each of the last 100
years could be stored in an array declared as follows:
float annual_temp[100];
This declaration will cause the compiler to allocate space for 100 consecutive float variables in
memory. The number of elements in an array must be fixed at compile time. It is best to make
the array size a constant and then, if required, the program can be changed to handle a
different size of array by changing the value of the constant,
const int NE = 100;
float annual_temp[NE];

24
then if more records come to light it is easy to amend the program to cope with more values by
changing the value of NE. This works because the compiler knows the value of the constant
NE at compile time and can allocate an appropriate amount of space for the array. It would not
work if an ordinary variable was used for the size in the array declaration since at compile
time the compiler would not know a value for it.

2.4 Accessing Array Elements


Given the declaration above of a 100-element array the compiler reserves space for 100
consecutive floating point values and accesses these values using an index/subscript that takes
values from 0 to 99. The first element in an array in C++ always has the index 0, and if the
array has n elements the last element will have the index n-1.
An array element is accessed by writing the identifier of the array followed by the subscript
in square brackets. Thus to set the 15th element of the array above to 1.5 the following
assignment is used:
annual_temp[14] = 1.5;

Note that since the first element is at index 0, then the ith element is at index i-1. Hence in
the above the 15th element has index 14.

An array element can be used anywhere an identifier may be used. Here are some examples
assuming the following declarations:

const int NE = 100,


N = 50;
int i, j, count[N];
float annual_temp[NE];
float sum, av1, av2;

A value can be read into an array element directly, using cin

cin >> count[i];

The element can be increased by 5,

count[i] = count[i] + 5;

or, using the shorthand form of the assignment

count[i] += 5;
Array elements can form part of the condition for an if statement, or indeed, for any other
logical expression:

if (annual_temp[j] < 10.0)


cout << "It was cold this year "
<< endl;

25
for statements are the usual means of accessing every element in an array. Here, the first NE
elements of the array annual_temp are given values from the input stream cin.

for (i = 0; i < NE; i++)


cin >> annual_temp[i];

The following code finds the average temperature recorded in the first ten elements of the
array.

sum = 0.0;
for (i = 0; i <10; i++)
sum += annual_temp[i];
av1 = sum / 10;
Notice that it is good practice to use named constants, rather than literal numbers such as 10. If
the program is changed to take the average of the first 20 entries, then it all too easy to forget
to change a 10 to 20. If a const is used consistently, then changing its value will be all that is
necessary.
For example, the following example finds the average of the last k entries in the array. k could
either be a variable, or a declared constant. Observe that a change in the value of k will still
calculate the correct average (provided k<=NE).
sum = 0.0;
for (i = NE - k; i < NE; i++)
sum += annual_temp[i];
av2 = sum / k;
Important - C++ does not check that the subscript that is used to reference an array element
actually lies in the subscript range of the array. Thus C++ will allow the assignment of a value
to annual_temp[200], however the effect of this assignment is unpredictable. For example it
could lead to the program attempting to assign a value to a memory element that is outside the
program's allocated memory space. This would lead to the program being terminated by the
operating system. Alternatively it might actually access a memory location that is within the
allocated memory space of the program and assign a value to that location, changing the value
of the variable in your program which is actually associated with that memory location, or
overwriting the machine code of your program. Similarly reading a value from
annual_temp[200] might access a value that has not been set by the program or might be the
value of another variable. It is the programmer's responsibility to ensure that if an array is
declared with n elements then no attempt is made to reference any element with a subscript
outside the range 0 to n-1. Using an index, or subscript, that is out of range is called Subscript
Overflow. Subscript overflow is one of the commonest causes of erroneous results and can
frequently cause very strange and hard to spot errors in programs.

26
2.5 Initialization of arrays
The initialization of simple variables in their declaration has already been covered. An array
can be initialized in a similar manner. In this case the initial values are given as a list enclosed
in curly brackets. For example initializing an array to hold the first few prime numbers could
be written as follows:
int primes[] = {1, 2, 3, 5, 7, 11, 13};

Note that the array has not been given a size, the compiler will make it large enough to hold
the number of elements in the list. In this case primes would be allocated space for seven
elements. If the array is given a size then this size must be greater than or equal to the number
of elements in the initialization list. For example:
int primes[10] = {1, 2, 3, 5, 7};
would reserve space for a ten element array but would only initialize the first five elements.
Example Program: Printing Outliers in Data
The requirement specification for a program is:
A set of positive data values (200) are available. It is required to find the average value of
these values and to count the number of values that are more than 10% above the average
value.
Since the data values are all positive a negative value can be used as a sentinel to signal the
end of data entry. Obviously this is a problem in which an array must be used since the values
must first be entered to find the average and then each value must be compared with this
average.
An initial algorithmic description is:
initialize.
enter elements into array and sum elements.
evaluate average.
scan array and count number greater than
10% above average.
output results.
This can be expanded to the complete algorithmic description:
set sum to zero.
set count to zero.
set nogt10 to zero.
enter first value.
while value is positive
{
put value in array element with index count.
add value to sum.
increment count.
enter a value.

27
}
average = sum/count.
for index taking values 0 to count-1
if array[index] greater than 1.1*average
then increment nogt10.
output average, count and nogt10.
In the above the variable nogt10 is the number greater than 10% above the average value. It is
easy to argue that after exiting the while loop, count is set to the number of positive numbers
entered. Before entering the loop count is set to zero and the first number is entered, that is
count is one less than the number of numbers entered. Each time round the loop another
number is entered and count is incremented hence count remains one less than the number of
numbers entered. But the number of numbers entered is one greater than the number of
positive numbers so count is therefore equal to the number of positive numbers.
A main() program written from the above algorithmic description is given below:
void main()
{
const int NE = 200; // maximum no of elements in array
float sum = 0.0; // accumulates sum
int count = 0; // number of elements entered
int nogt10 = 0; // counts no greater than 10%
// above average
float x; // holds each no as input
float indata[NE]; // array to hold input
float average; // average value of input values
int i; // control variable

// Data entry, accumulate sum and count


// number of +ve numbers entered
cout << "Enter numbers, -ve no to terminate: " << endl;
cin >> x;
while (x >= 0.0)
{
sum = sum + x;
indata[count] = x;
count = count + 1;
cin >> x;
}

// calculate average
average = sum/count;

// Now compare input elements with average


for (i = 0; i < count; i++)
{
if (indata[i] > 1.1 * average)
nogt10++;
}

// Output results
cout << "Number of values input is " << n;
cout << endl
<< "Number more than 10% above average is "
<< nogt10 << endl;

28
}
Since it was assumed in the specification that there would be less than 200 values the array
size is set at 200. In running the program less than 200 elements may be entered, if n elements
where n < 200 elements are entered then they will occupy the first n places in the array indata.
It is common to set an array size to a value that is the maximum we think will occur in
practice, though often not all this space will be used.
Example Program: Test of Random Numbers
The following program simulates the throwing of a dice by using a random number generator
to generate integers in the range 0 to 5. The user is asked to enter the number of trials and the
program outputs how many times each possible number occurred.
An array has been used to hold the six counts. This allows the program to increment the
correct count using one statement inside the loop rather than using a switch statement with six
cases to choose between variables if separate variables had been used for each count. Also it is
easy to change the number of sides on the dice by changing a constant. Because C++ arrays
start at subscript 0 the count for an i occurring on a throw is held in the i-1th element of this
count array. By changing the value of the constant die_sides the program could be used to
simulate a die_sides-sided die without any further change.
#include <iostream.h>
#include <stdlib.h> // time.h and stdlib.h required for
#include <time.h> // random number generation

void main()
{
const int die_sides = 6; // maxr-sided die
int count[die_sides]; // holds count of each
// possible value
int no_trials, // number of trials
roll, // random integer
i; // control variable
float sample; // random fraction 0 .. 1

// initialize random number generation and count


// array and input no of trials
srand(time(0));
for (i=0; i < die_sides; i++)
count[i] = 0;
cout << "How many trials? ";
cin >> no_trials;

// carry out trials


for (i = 0; i < no_trials; i++)
{
sample = rand()/float(RAND_MAX);
roll = int ( die_sides * sample);
// returns a random integer in 0 to die_sides-1
count[roll]++; // increment count
}

29
// Now output results
for (i = 0; i < die_sides; i++)
{
cout << endl << "Number of occurrences of "
<< (i+1) << " was " << count[i];
}
cout << endl;
}

2.6 Multidimensional arrays


An array may have more than one dimension. Each dimension is represented as a subscript in
the array. Therefore a two dimensional array has two subscripts, a three dimensional array has
three subscripts, and so on.
Arrays can have any number of dimensions, although most of the arrays that you create will
likely be of one or two dimensions.
A chess board is a good example of a two-dimensional array. One dimension represents the
eight rows, the other dimension represents the eight columns.
Suppose the program contains a class named square. The declaration of array named board
that represents would be
Square board[8][8];
The program could also represent the same data with a one dimensional, 64-square array. For
example, it could include the statement
Square board[64];
Such a representation does not correspond as closely to the real-world object as the two
dimensional array, however.
Suppose that when the game begins. The king id located in the fourth position in the first row.
Counting from zero that position corresponds to board[0][3] in the two dimensional array,
assuming that the first subscript corresponds to the row, and the second to the column.
Initializing Multidimensional Arrays
To initialize a multidimensional arrays , you must assign the list of values to array elements in
order, with last array subscript changing while the first subscript holds steady. Therefore, if
the program has an array int theArray[5][3], the first three elements go int theArray[0]; the
next three into theArray[1]; and so forth.
The program initializes this array by writing
int theArray[5][3] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15};
for the sake of clarity, the program could group the initializations with braces, as shown
below.

30
int theArray[5][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9},
{10, 11, 12}, {13, 14,15} };
The compiler ignores the inner braces, which clarify how the numbers are distributed.

Each value should be separated by comma, regardless of whither inner braces are include. The
entire initialization must set must appear within braces, and it must end with a semicolon.
Omitting the Array Size

If a one-dimensional array is initialized, the size can be omitted as it can be found from the
number of initializing elements:
int x[] = { 1, 2, 3, 4} ;
This initialization creates an array of four elements.
Note however:
int x[][] = { {1,2}, {3,4} } ; // error is not allowed.
and must be written
int x[2][2] = { {1,2}, {3,4} } ;

Example of multidimensional array


#include<iostream.h>
void main(){
int SomeArray[5][2] = {{0,0},{1,2}, {2,4},{3,6}, {4,8}}
for ( int i=0; i<5; i++)
for (int j = 0; j<2;j++)
{
cout<<"SomeArray["<<i<<"]["<<j<<'']: '';
cout<<endl<<SomeArray[i][ j];
}
}

31
Unit 3: Pointer
Learning objectives of the unit
At the end of this unit trainees are expected to:
 Be able to define pointer.
 Be able to define pointer variables.
 Be able to differentiate single and multi-dimensional array.
 Be able to apply the array variables in C++ programming.

3.1 Introduction

A pointer is simply the address of a memory location and provides an indirect way of
accessing data in memory. A pointer variable is defined to ‘point to’ data of a specific type.
For example:
int *ptr1; // pointer to an int
char *ptr2; // pointer to a char
The value of a pointer variable is the address to which it points. For example, given the
definitions
int num;
we can write:
ptr1 = &num;
The symbol & is the address operator; it takes a variable as argument and returns the memory
address of that variable. The effect of the above assignment is that the address of num is
assigned to ptr1. Therefore, we say that ptr1 points to num.
ptr1 num

A simple integer pointer.


Given that ptr1 points to num, the expression
*ptr1
dereferences ptr1 to get to what it points to, and is therefore equivalent to num. The symbol * is
the dereference operator; it takes a pointer as argument and returns the contents of the
location to which it points.
In general, the type of a pointer must match the type of the data it is set to point to. A pointer
of type void*, however, will match any type. This is useful for defining pointers which may
point to data of different types, or whose type is originally unknown. A pointer may be cast
(type converted) to another type. For example,

32
ptr2 = (char*) ptr1;

converts ptr1 to char pointer before assigning it to ptr2.


Regardless of its type, a pointer may be assigned the value 0 (called the null pointer). The null
pointer is used for initializing pointers, and for marking the end of pointer-based data
structures (e.g., linked lists).

3.2 Dynamic Memory


In addition to the program stack (which is used for storing global variables and stack frames
for function calls), another memory area, called the heap, is provided. The heap is used for
dynamically allocating memory blocks during program execution. As a result, it is also called
dynamic memory. Similarly, the program stack is also called static memory.

Two operators are used for allocating and deallocating memory blocks on the heap. The new
operator takes a type as argument and allocated a memory block for an object of that type. It
returns a pointer to the allocated block. For example,
int *ptr = new int;
char *str = new char[10];
allocate, respectively, a block for storing a single integer and a block large enough for storing
an array of 10 characters.
Memory allocated from the heap does not obey the same scope rules as normal
variables. For example, in
void Foo (void)
{
char *str = new char[10];
//...
}

when Foo returns, the local variable str is destroyed, but the memory block pointed to by str is
not. The latter remains allocated until explicitly released by the programmer.

The delete operator is used for releasing memory blocks allocated by new. It takes a pointer as
argument and releases the memory block to which it points. For example:

delete ptr; // delete an object


delete [] str; // delete an array of objects

33
Note that when the block to be deleted is an array, an additional [] should be included to
indicate this.
Should delete be applied to a pointer which points to anything but a
dynamically-allocated object (e.g., a variable on the stack), a serious runtime error may occur.
It is harmless to apply delete to the 0 pointer.
Dynamic objects are useful for creating data which last beyond the function call which creates
them.

3.3 Pointer arithmetic


In C++ one can add an integer quantity to or subtract an integer quantity from a pointer. This
is frequently used by programmers and is called pointer arithmetic. Pointer arithmetic is not
the same as integer arithmetic, because the outcome depends on the size of the object pointed
to. For example, suppose that an int is represented by 4 bytes. Now, given

char *str = "HELLO";


int nums[] = {10, 20, 30, 40};
int *ptr = &nums[0]; // pointer to first element

str++ advances str by one char (i.e., one byte) so that it points to the second character of
"HELLO", whereas ptr++ advances ptr by one int (i.e., four bytes) so that it points to the second
element of nums..

Pointer arithmetic.
H E L L O \0 10 20 30 40

str ptr

str++ ptr++

It follows, therefore, that the elements of "HELLO" can be referred to as *str, *(str + 1), *(str + 2),
etc. Similarly, the elements of nums can be referred to as *ptr, *(ptr + 1), *(ptr + 2), and *(ptr + 3).
Another form of pointer arithmetic allowed in C++ involves subtracting two pointers of the
same type. For example:

int *ptr1 = &nums[1];


int *ptr2 = &nums[3];
int n = ptr2 - ptr1; // n becomes 2
34
Pointer arithmetic is very handy when processing the elements of an array.

3.4 Function Pointers

It is possible to take the address of a function and store it in a function pointer. The pointer can
then be used to indirectly call the function. For example,
int (*Compare)(const char*, const char*);

defines a function pointer named Compare which can hold the address of any function that
takes two constant character pointers as arguments and returns an integer. The string
comparison library function strcmp, for example, is such. Therefore:
Compare = &strcmp; // Compare points to strcmp function

The & operator is not necessary and can be omitted:


Compare = strcmp; // Compare points to strcmp function

Alternatively, the pointer can be defined and initialized at once:


int (*Compare)(const char*, const char*) = strcmp;

When a function address is assigned to a function pointer, the two types must match. The
above definition is valid because strcmp has a matching function prototype:
int strcmp(const char*, const char*);

Given the above definition of Compare, strcmp can be either called directly, or indirectly via
Compare. The following three calls are equivalent:

strcmp("Tom", "Tim"); // direct call


(*Compare)("Tom", "Tim"); // indirect call
Compare("Tom", "Tim"); // indirect call (abbreviated)

A common use of a function pointer is to pass it as an argument to another function; typically


because the latter requires different versions of the former in different circumstances. A good
example is a binary search function for searching through a sorted array of strings. This
function may use a comparison function (such as strcmp) for comparing the search string
against the array strings. This might not be appropriate for all cases. For example, strcmp is
case-sensitive. If we wanted to do the search in a non-case-sensitive manner then a different
comparison function would be needed.
As shown in Listing 5.Error! Bookmark not defined., by making the
comparison function a parameter of the search function, we can make the latter
independent of the former.

35
1 int BinSearch (char *item, char *table[], int n,
2 int (*Compare)(const char*, const char*))
3 {
4 int bot = 0;
5 int top = n - 1;
6 int mid, cmp;

7 while (bot <= top) {


8 mid = (bot + top) / 2;
9 if ((cmp = Compare(item,table[mid])) == 0)
10 return mid; // return item index
11 else if (cmp < 0)
12 top = mid - 1; // restrict search to lower half
13 else
14 bot = mid + 1; // restrict search to upper half
15 }
16 return -1; // not found
17 }

Annotation
1 Binary search is a well-known algorithm for searching through a sorted list of
items. The search list is denoted by table which is an array of strings of
dimension n. The search item is denoted by item.
2 Compare is the function pointer to be used for comparing item against the
array elements.
7 Each time round this loop, the search span is reduced by half. This is repeated
until the two ends of the search span (denoted by bot and top) collide, or until
a match is found.
9 The item is compared against the middle item of the array.
10 If item matches the middle item, the latter’s index is returned.
11 If item is less than the middle item, then the search is restricted to the lower
half of the array.
14 If item is greater than the middle item, then the search is restricted to the
upper half of the array.
16 Returns -1 to indicate that there was no matching item.
The following example shows how BinSearch may be called with strcmp
passed as the comparison function:
char *cities[] = {"Boston", "London", "Sydney", "Tokyo"};
cout << BinSearch("Sydney", cities, 4, strcmp) << '\n';

This will output 2 as expected.

36
Unit 4: Structure
Learning objectives of the unit
 Be able to define structure.
 Be able to declare structure and structure variables.
 Be able to initialize structure variables.
 Be able to access members of structure variable
 Be able to define structure within a structure.

4.1 Concept of structure in problem solving


Thus far you have worked with variable’s whose data types are very simple: they are a
numbers of either integer or floating-point format with a specific range. These types of
variables, who only have a single value to their name, are known as basic variables or
primitives. Everything in computers is built on numbers, but not necessarily singular types.
Sometimes it’s advantageous to group common variables into a single collection. For example
a date would require a day, month, and year. From what we have discussed currently
explained, you could create three separate variables for each, like so:

int day, month, year;

This isn’t so bad, but what happens if you want to store two dates and not one? You’d have to
create three more variables and give them unique names:

int day1, month1, year1;


int day2, month1, year2;

This begins to become a hassle. Not only do you have to create many variables, but you have
to keep giving them unique names. C++ provides a way to collect similar variables into a
single structure.

An array is a data structure which holds multiple numbers of objects having the same basic
property (data type) in a contiguous memory slots. Programmer can also reserve contiguous
memory space for aggregates of elements of arbitrary data types each. A data type which is
created to reserve such type of memory space is called user defined data type.

User defined data types can be equally used like predefined data types to declare variable
identifiers. For example we can define simple, array, or pointer variable identifier from this
user defined data type.

37
The term structure in C++ means both a user-defined type which is a grouping of variables as
well as meaning a variable based on a user-defined structure type. For the purpose of
distinction we will refer to the user-defined type side as structure definition and the variable
side as structure variable.
A structure definition is a user-defined variable type which is a grouping of one or more
variables. The type itself has a name, just like ‘int’, ‘double’, or ‘char’ but it is defined by the
user and follows the normal rules of identifiers. Once the type has been defined through the
C++ ‘struct’ keyword, you can create variables from it just like you would any other type.
Since a structure definition is a grouping of several types: it is a group of one or more
variables. These are known as elements or member variables as they are members of the
structure definition they are part of. Following through with our hinted example, a structure
definition could be a ‘date’ which might be made up of three ‘int’ member variables: ‘day’,
‘month’, and ‘year’.

4.2 struct Specification: Defining Structures


Defining a structure is giving the compiler a blue print for creating your type. When you create
a variable based on the structure definition, all of the member variables are created
automatically and grouped under the name you gave. Note that when you create a variable of
any kind, you must give it a unique name that is different than its type. Below is the syntax for
a structure definition:
struct structname
{
datatype1 variable1;
datatype2 variable2;
};

Example defining a student struct,


struct student
{
int id;
char name[15];
};
Example: The follow defines a structure called ‘date’ which contains three ‘int’
member variables: ‘day’, ‘month’, and ‘year’:
struct date {
int day;

38
int month;
int year;
};
struct date
{
int day, month, year;
};

4.3 Declaring and using sturct data types


Once you have defined a structure you can create a variable from it just as you would any
other variable.
student std1;
date birthday;
The above declaration statements would create a variable called ‘birthday’ whose type is the
structure ‘date’. The variable contains three parts: ‘day’, ‘month’, and ‘year’. What this
actually does is set aside a whole block of memory that can contain all of the member
variables. Each member variable then occupies a chunk of it for their individual storage units.
The member variables are not actually created one at a time.
Storage for member variables exist at some offset from the beginning of the glob of memory
reserved by the entire structure. For example, in our ‘date’ structure variable the first member
variable is ‘day’ so it exists at offset 0. The next member variable, ‘month’ in this case, will
exist at the next available offset. If ‘day’ uses 4 bytes (32 bits), then ‘month’ will be at offset
4:
int i;
student std1;
4.4 Initializing Structure Variables

To initialize a structure variable’s members, you follow the original declaration with the
assignment operator (=). Next you define an initialization block which is a list of initializers
separated by commas and enclosed in curly braces. Lastly, you end it with a semi-colon.
These values are assigned to member variables in the order that they occur. Let’s look at an
example:
date nco_birthday = { 19, 8, 1979 };
student std1={"Ababe", "Scr/2222/22"};
This creates a variable called ‘nco_birthday’ and initializes it to a list of values. The values
are assigned to the member variables in the order they are declared in the structure definition.

39
Remember what is mentioned about each member variable having an offset. The same order
in which each member is given an offset is the order in which each is assigned a value in an
initialization. So the first initializer is used to initialize the first member variable in the
structure, next is the second, and so on and so forth. This order of initialization continues until
the values run out.
It is possible to use any expression that you normally would. But remember that the
expression must result in a value. Here is an example of initialization with things other than
literals:
int myday = 19;
int mymonth = 5;
date nco_birthday = { myday, mymonth + 3, 2001 - 22 };
Although you can assign a value to a variable in the same way you initialize it, the same is not
true with structures. So while this works:
int x;
x = 0;
This doesn’t:
date nco_birthday;
nco_birthday = { 19, 8, 1979 };
To specify that you want a member of a specific structure variable, you use the structure
member operator which is the period (also known as a “dot”). Simply use the structure’s
name, follow with the period, and end with the member:
structure.member
Example: to reading and displaying values to and from structure s1.
cin>>s1.id; //storing to id item of s1
cin>>s1.name; //storing a name to s1
cout<<s1.id; //displaying the content of id of s1.
cout<<s1.name; //displaying name

Example:-a program that creates student struct and uses it to store student information.
#include<iostream.h>
#include<conio.h>
struct student
{
int id;
40
char name[15];
};

void main()
{
//creating three student variables
student s1,s2;
cout<<"\n Enter Student Id";
cin>>s1.id;
cout<<"\nEnter Name";
cin>>s1.name;
cout<<"\n Enter Student Id";
cin>>s2.id;
cout<<"\nEnter Name";
cin>>s2.name;

cout<<"\nStudents Information";
cout<<"\n Student id\t Student Name";
cout<<endl<<s1.id<<"\t"<<s1.name;
cout<<endl<<s2.id<<"\t"<<s2.name;
getch();
}

4.5 Declaring struct types as part of a struct


A structure definition contains multiple variables, but not necessarily just primitives. You can
define a structure to have structure member variables.
Now if you have data's like birth of day of an employee, published year of a book, address of a
person. What are you going to do? You must be able to incorporate this type of data's in other
structs. The following program declares two structs one for address and other for student.
#include<iostream.h>
#include<conio.h>
struct Address{
int kebele;
char Kefle_ketema[20];
char roadname[20];
};
struct Student {
int id;
char name[15];
char section[6];
//declaring address type within student
Address studaddress;
};
void main(){
clrscr();
//creating Student type that encapsulates Address
Student s1;
cout<<"\n Enter Student Id";
cin>>s1.id;
cout<<"\nEnter Student Name";
cin>>s1.name;
cout<<"\n Enter Section";
41
cin>>s1.section;
//reading address attributes
cout<<"\nEnter Kebele";
cin>>s1.studaddress.kebele;
cout<<"\nEnter Street Name";
cin>>s1.studaddress.roadname;
cout<<"\nEnter Kefle Ketema";
cin>>s1.studaddress.Kefle_ketema;
cout<<"\n Student Information";
cout<<"\n id\t Name\t Section \t Kebele";
cout<<" \t Street Name \t Kefele Ketema ";
cout<<"\n==================================";
cout<<endl<<s1.id<<"\t"<<s1.name;
cout<<"\t"<<s1.section<<"\t"<<s1.studaddress.kebele;
cout<<"\t"<<s1.studaddress.roadname<<"\t";
cout<<s1.studaddress.Kefle_ketema;
getch();
}

Unit 5: File management


Learning objectives of the unit
At the end of this unit trainees are expected to:
 Be able to define file and stream.
 Be able to declare file variable identifier.
 Be able to open file.
 Be able to process a file.
 Be able to define close a file.

5.1 Managing files using C++.

File handling is an important part of all programs. Most of the applications will have their own
features to save some data to the local disk and read data from the disk again. Files which are
on the secondary storage device are called physical files. In order to process file through
program, logical file must be created on the RAM. This logical file is nothing but an object
having file data type. As an object there should be a variable identifier that points to it. This
variable is called file variable and sometimes also called file handler. C++ File I/O classes
simplify such file read/write operations for the programmer by providing easier to use classes.

42
Streams and Files
The I/O system supplies a consistent interface to the C++ programmer independent of the
actual device being accessed. This provides a level of abstraction between the programmer and
the device. This abstraction is called stream. The actual device is called a file.
Streams
The C++ file system is designed to work with a wide variety of devices, including terminals,
disk drives, and tape drives. Even though each device is very different, the C++ file system
transforms each into a logical device called stream. There are two types of streams: text and
binary.
a. Text Streams
A text stream is a sequence of characters. In a text stream, certain character translations may
occur as required by the host environment. For example a new line may be converted to a
carriage return/linefeed pair. There may not be a one-to-one relationship between the
characters that are written (or read) and those on the external device. Because of possible
transformations, the number of characters written (or read) may not be the same as those on
the external device.
b. Binary streams
A binary stream is a sequence of bytes with a one-to-one correspondence to those in the
external device i.e., no character translations occur. The number of bytes written (or read) is
the same as the number on the external device. However, an implementation-defined number
of null bytes may be appended to a binary stream. These null bytes might be used to pad the
information so that it fills a sector on a disk, for example.
Files
In C++, a file can be anything from a disk file to a terminal or printer. You associate a stream
with a specific file by performing an open operation. Once a file is open, information can be
exchanged between it and a program. All streams are the same but all files are not. If the file
can support position requests, opening that file also initializes the file position indicator to the
start of the file. As each character is read from or written to the file, the position indicator is
incremented. You disassociate a file from a specific stream with a close operation. If you close
a file opened for output, then contents, if any, of its associated stream are written to the
external device. -- this process is referred to as flushing the stream. All files are closed
automatically when the program terminates normally. Files are not closed when a program
terminates abnormally. Each stream that is associated with a file has a file control structure of
type FILE. This structure FILE is defined in the header stdio.h.

43
The standard streams
Whenever a program starts execution, three streams are opened automatically.
stdin --- standard input.
stdout -- standard output
stderr -- standard error
Normally, these streams refer to the console. Because the standard streams are file pointers,
they can be used by the ANSI C file system to perform I/O operations on the console.

5.2 C++ File I/O Classes and Functions


To perform file I/O, the header file fstream.h is requied. fstream.h defines several classes,
including ifstream, ofstream, and fstream. These classes are derived form istream and ostream,
repectively. istream and ostream are derived form ios.
Three file I/O classes are used for File Read/Write operations:
a. ifstream - Can be used for File read/input operations
b. ofstream - Can be used for File write/output operations
c. fstream - Can be used for both read/write c++ file I/O operations
Text and Binary Files
In file processing, files are generally classified into two as
 Text file and
 Binary file
Text File processing
File processing involves the following major steps
1. Declaring file variable identifier
2. Opening the file
3. Processing the file
4. Closing the file when process is completed.
Opening and Closing a file
An open file is represented within a program by a stream object and any input or output
operation performed on this stream object will be applied to the physical file associated to it.
In C++, you open a file by linking it to a stream. Before you can open a file, you must first
obtain a stream. There are three types of streams: input, output, and input/output. To create an
input stream, you must declare the stream to be of class ifstream. To create an output stream,
you must declare it as class ofstream. Streams that will be performing both input and output
operations must be declared as class fstream.
ifstream in ; //input stream
ofstream out ; // output stream

44
fstream io ; // input and output
Once you have declared a stream, you associate it with a file by using the method open().
The method open ( ) is a member of each of the three stream classes. Its prototype is:
void open (const char *filename, int mode, int access = filebuf::penprot );
Reading and writing text files
Simply use the << and >> operators in the same way you do when performing console I/O
except that instead of using cin and cout, you substitute a stream that is linked to a file.
ofstream out ("inventory");
out <<"Radios" << 39.95 << endl;
out << "Toastors" << 19.95 << endl;
out.close ( );
Example: Basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
This code creates a file called example.txt and inserts a sentence into it in the same way we are
used to do with cout, but using the file stream myfile instead.
Example 2: writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";

45
return 0;
}
Example 3: reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}
This last example reads a text file and prints out its content on the screen. Notice how we have
used a new member function, called eof() that returns true in the case that the end of the file
has been reached. We have created a while loop that finishes when indeed myfile.eof()
becomes true (i.e., the end of the file has been reached).
Checking state flags
In addition to eof(), which checks if the end of file has been reached, other member functions
exist to check the state of a stream (all of them return a bool value):

Function Description
bad() Returns true if a reading or writing operation fails. For example in the
case that we try to write to a file that is not open for writing or if the
device where we try to write has no space left.
fail() Returns true in the same cases as bad(), but also in the case that a
format error happens, like when an alphabetical character is
extracted when we are trying to read an integer number.

46
eof() Returns true if a file open for reading has reached the end.
good() It is the most generic state flag: it returns false in the same cases in
which calling any of the previous functions would return true.

5.3 Binary File processing


In binary files, to input and output data with the extraction and insertion operators (<< and >>)
and functions like getline is not efficient, since we do not need to format any data, and data
may not use the separation codes used by text files to separate elements (like space, newline,
etc...).
File streams include two member functions specifically designed to input and output binary
data sequentially: write and read. The first one (write) is a member function of ostream
inherited by ofstream. And read is a member function of istream that is inherited by ifstream.
Objects of class fstream have both members. Their prototypes are:
write(memory_block,size);
read ( memory_block, size );
Where memory_block is of type "pointer to char" (char*), and represents the address of an
array of bytes where the read data elements are stored or from where the data elements to be
written are taken. The size parameter is an integer value that specifies the number of characters
to be read or written from/to the memory block.
There are two ways to write and read binary data to and from a file.
get ( ) and put ( )
read ( ) and write ( )
If you will be performing binary operations on a file, be sure to open it using the ios::binary
mode specifier.
get ( ) and put ( )
These functions are byte-oriented.
o get ( ) will read a byte of data.
o put ( ) will write a bye of data.
The get ( ) method has many forms.
istream & get( char & ch );
ostream & put ( char ch);
The get ( ) method read a single character from the associated stream and puts the value in ch,
and returns a reference to the stream. The put ( ) method writes ch to the stream and returns a
reference to the stream.

47
char in;
ifstream in ( "test", ios::in | ios::binary);
if (!in){
cout <<"Cannot open file";
return 1;
}
while (in) //inn will be 0 when eof is reached
{ in.get ( ch );
cout << ch;
}
When the end-of-file is reached, the stream associated with the file becomes zero.
ofstream out ( "chars", io::out | ios::binary);
for (int i= 0; i < 256; i++)
out.put ( (char ) i ) ; //write all characters to disk
out.close ( );
read ( ) and write ( )
The read ( ) method reads num bytes from the associated stream, and puts them in a memory
buffer (pointed to by buf).

istream & read ( unsigned char * buf, int num );


The write ( ) method writes num bytes to the associated stream from the memory buffer
(pointed to by buf).

ostream & write ( const unsigned char * buf, int num );


If the end-of-file is reached before num characters have been read, then read ( ) simply stops,
and the buffer contains as many characters as were available. You can find out how many
characters have been read by using another member function, called gcount ( ), which has the
prototype:

int gcount ( );
More get ( ) functions
The method get ( ) is overloaded in several ways.
istream &get (char *buf, int num, char delim = '\n');
This get ( ) method reads characters into the array pointed to by the buf until either num
characters have been read, or the character specified by delim has been encountered. The array
pointed to by buf will be null terminated by get ( ). If the delimiter character is encountered in
the input stream, it is not extracted. Instead, it remains in the stream until the next input
operation.
a. int get ( )
It returns the next character from the stream. It returns EOF if the end of file is encountered.
b. getline ( )
istream & getline ( char *buf, int num, char delim ='\n');
48
This method is virtually identical to the get ( buf, num, delim) version of get ( ). The
difference is getline ( ) reads and removes the delimiter from the input stream.
Example: reading a complete binary file
#include <iostream>
#include <fstream>
using namespace std;
ifstream::pos_type size;
char * memblock;
int main () {
ifstream file ("example.txt", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the complete file content is in memory";
delete[] memblock;
}
else cout << "Unable to open file";
return 0;
}
In this example the entire file is read and stored in a memory block. Let's examine how this is
done:
First, the file is open with the ios::ate flag, which means that the get pointer will be positioned
at the end of the file. This way, when we call to member tellg(), we will directly obtain the size
of the file. Notice the type we have used to declare variable size:
ifstream::pos_type size;
ifstream::pos_type is a specific type used for buffer and file positioning and is the type
returned by file.tellg(). This type is defined as an integer type, therefore we can conduct on it
the same operations we conduct on any other integer value, and can safely be converted to
another integer type large enough to contain the size of the file. For a file with a size under
2GB we could use int:
49
int size;
size = (int) file.tellg();
Once we have obtained the size of the file, we request the allocation of a memory block large
enough to hold the entire file:
memblock = new char[size];
Right after that, we proceed to set the get pointer at the beginning of the file (remember that
we opened the file with this pointer at the end), then read the entire file, and finally close it:
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
At this point we could operate with the data obtained from the file. Our program simply
announces that the content of the file is in memory and then terminates.

Function Description
Detecting EOF It returns nonzero when the end of the file has been
int eof ( ); reached; otherwise it returns zero.
Reading and discarding characters Reads and discards characters until either num
from the input stream. characters have been nignored (1 by default ) or until
istream & ignore (int num = 1, int the charcter specified by delim is encounterdd (EOF by
delim = EOF); default). If the delimiting character is encountered, it is
not removed from the input stream.
Obtain the next character in the One can obtain the next character in the input stream
input stream without removing it without removing it from that stream by using peek ( ).
from that stream It returns the next character in the stream or EOF if the
int peek ( ); end of file is encountered.

istream & putback ( char c); One can return the last character read from a stream to
that stream using putback ( ).

Forcing data to be physically When the output is performed, data is not necessarily
written to the disk immediately written to the physical device linked to the
stream. Instead, information is stored in an internal

50
ostream & flush ( ); buffer until the buffer is full. Only then are the contents
of that buffer written to disk. However, you can force
the information to be physically written to the disk
before the buffer is full by calling flush ( ).

5.4 Random Access Files


In C++'s I/O system, you perform random access by using seekg ( ) and seekp ( ) methods.
istream *seekg (streamoff offset, sek_dir origin);
ostream & seekp ( streamoff offet, seek_dir origin);
Here, streamoff is a type defined in iostream.h that is capable of containing the largest valid
value that offset can have. Also seed-dir is an enumeration that has these values:
ios::beg
ios::cur
ios::end
The C++ I/O system manages two pointers associated with a file. One is the get pointer, which
specifies where in then file the next input operation will occur. The other is the put pointer,
which specifies where in the file the next output operation will occur. Each time an input or
output operation takes place the appropriate pointer is automatically sequentially advanced.
The seekg ( ) method moves the associated file's current get pointer offset number of bytes
from the specified origin, which must be one of three values. The seekp ( ) method moves the
associated file's current put pointer offset number of bytes from the specified origin, which
must be one of three values.

5.5 Obtaining the Current File Position


You can determine the current position of each file pointer by using these methods.
streampos tellg ( );
streampows tellp ( );
Here, streampos is a type defined in iostream.h that is capable of holding the largest value that
either function can return.
I/O Status
The C++ I/O system maintains status information about the outcome of each I/O operation.
The current state of the I/O system is held in an integer, in which the following flags are
encoded.
 eofbit -- 1 when end-of-file is encountered; 0 otherwise
 failbit -- 1 when a (possibly) nonfatal I/O error has occurred; 0 otherwise

51
 badbit -- 1 when a fatal I/O error has ocurred; 0 otherwise
These flags are enumerated inside ios. Also defined in ios is goodbit, which has the value 0.
There are two ways in which you can obtain I/O status information.
a. Use the rdstate function/method.
int rdstate ( );
rdstate function returns the current status of the error flags encoded into an integer. It returns
zero, when no error has occurred. Otherwise, an error bit is turned on.
b. Use one or more of these methods.
Method Description
int bad ( ) Returns true if badbit is set.
int fail ( ) Returns true if failbit is set.
int eof ( ) Returns true if there are no errors.
int good ( ) Otherwise they return false.
Once an error has occurred, it may need to be cleared before your program continues. to do
this, use the clear ( ) method.
void clear ( int flags = 0);
If flag = zero (as it is by default), all error flags are cleared (reset to zero). Otherwise, set flags
to the flags or values you want to clear.

52
Self-check questions
Part I: Multiple choices
Instruction: Choose the best response based on your understanding of the topic.

1. What does the "cout" object do in C++?


A. Reads input from the user
B. Writes output to the console
C. Allocates memory dynamically
D. Performs arithmetic calculations
2. Which of the following is NOT a valid data type in C++?
A. int
B. real
C. char
D. float
3. What is the purpose of the "void" keyword in a function declaration?
A. It indicates that the function returns nothing
B. It specifies the access level of the function
C. It declares a variable
D. It signifies a loop control variable
4. What is the correct syntax for declaring a pointer variable in C++?
A. int* ptr;
B. ptr int;
C. ptr = int;
D. int ptr();
5. What does the "new" keyword do in C++?
A. Deletes a variable
B. Allocates memory dynamically
C. Declares a new function
D. Initializes a variable
6. What is the result of the expression "5 + 3 * 2" in C++?
A. 16
B. 11
C. 13
D. 26
7. How do you access the element at index 3 in an array named "arr" in C++?
53
A. arr[3]
B. arr(3)
C. arr{3}
D. arr.at(3)
8. What does the "cin" object do in C++?
A. Writes output to the console
B. Reads input from a file
C. Reads input from the user
D. Allocates memory dynamically
9. Which of the following is NOT a valid C++ identifier?
A. my_variable
B. 123variable
C. _myVariable
D. MyVariable
10. What is the output of the following code snippet?
int x = 5;
cout << "The value of x is: " << x++;
A. The value of x is: 5
B. The value of x is: 6
C. The value of x is: 7
D. The value of x is: 4
11. Which keyword is used to define a class in C++?
A. class
B. struct
C. object
D. type
12. What is the correct syntax for defining a function named "add" that takes two integers as
parameters and returns their sum in C++?
A. add(int x, int y) { return x + y; }
B. int add(int x, int y) { return x + y; }
C. add(int x, int y) => x + y;
D. int add(x, y) { return x + y; }

54
REFERENCES:

1. "C++ Primer" by Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo


2. "Programming: Principles and Practice Using C++" by Bjarne Stroustrup - Authored
by the creator of C++,
3. "Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and
C++14" by Scott Meyers –
4. "The C++ Programming Language" by Bjarne Stroustrup
5. "Accelerated C++: Practical Programming by Example" by Andrew Koenig and
Barbara E. Moo
6. "C++ Templates: The Complete Guide" by David Vandevoorde and Nicolai M. Josuttis
7. "C++ Concurrency in Action" by Anthony Williams -

55
Sub theme 2: Object Oriented system analysis and Design

Unit 1: Basic concepts of object-oriented system analysis and design

Learning objectives of the unit


At the end of this unit trainees are expected to:

 Be able to discuss about system


 Be able to identify good attributes of stems
 Be able to discuss system development life cycle
 Be able to discuss different types of methodologies
 Be able to discuss basic difference between structures and object oriented approaches
 Be able to discuss characteristics of object oriented
 Be able to discuss the difference between structured and object oriented analysis
 Be able to discuss, identify and use tools for structured approach system development.

1.1 Object Oriented Approach

The field of system analysis and design still has a lot of room for improvement: Projects still
run over budget, users often cannot get applications when they need them, and some systems
still fail to meet important user needs. Thus, the state of the systems analysis and design field
is on constant transition and continuous improvement. Analysts and developers learn from past
mistakes and successes and evolve their practices to incorporate new techniques and new
approaches that work better. Today, an exciting enhancement to systems analysis and design is
the application of the object-oriented approach.

56
The object-oriented approach views a system as a collection of self-contained objects,
including both data and processes or it is an approach to the solution of problems in which all
computations are performed in the context of objects.
In object-oriented approach a running program is seen as a collection of objects collaborating
to perform a given task, in this approach:
 Procedures are De –emphasized
 A system is made up of objects
 Users can more easily understand objects
For system development using this approach
 Object oriented programming
 Object Oriented Analysis, design
 Object Oriented CASE tools are expected to be used.

1.2 Basic Characteristics of Object-Oriented System


Object Oriented: Theory is built up on a sound engineering foundation whose elements we
collectively called the object model.
The Object model encompasses the principles of
Abstraction: Denotes essential characteristics of an object that distinguishes it from all other
kinds of objects
Encapsulation: Hiding the inner workings of object’s operations from the outside world and
from other objects
Modularity: The property of a system that has been decomposed in to a set of cohesive and
loosely coupled modules
Hierarchy - Is a ranking or ordering of abstractions Inheritance
Aggregation - The process of creating a new object from two or more other objects.
Other Concepts: Objects, Classes, Polymorphism, Message, Attributes, Methods
The major characteristics of object-oriented SAD approach
a. Classes, Objects and Attributes
A class is the general template we use to define and create specific instances, or objects. Every
object is associated with a class.
Example:
Book, Student, Librarian, Teacher, Staff …….
An object is an instantiation of a class. In other words, an object is a person, place, event, or
thing about which we want to capture information.
57
Example: a specific book, a specific student …….
Each object has attributes that describe information about the object, such as a customer’s
name, address, e-mail, and phone number. The state of an object is defined by the value of its
attributes and its relationships with other objects at a particular point in time.

Methods and Messages


A method is nothing more than an action that an object can perform. Methods are very much
like a function or procedure in a traditional programming language.
Example:
+BorrowBook(), +insert()
Messages are information sent to objects to trigger methods. A message is essentially a
function
or procedure call from one object to another object.

Encapsulation is simply the combining of process and data into a single entity. Object-oriented
approaches combine process and data into holistic entities (objects).
The principle of information hiding suggests that only the information required to use a
software module be published to the user of the module.

58
a. Inheritance
The mechanism where features in a hierarchy inherit from super classes to subclasses by
identifying higher level, or more general, classes of objects.
Typically, classes are arranged in a hierarchy where by the super classes, or general classes are
at the top, and the subclasses, or specific classes, are at the bottom.

Polymorphism and Dynamic Binding


Polymorphism means that the same message can be interpreted differently by different
classes of objects.
Example:
If we sent the message “Draw Image” to a square object, a circle object, and a triangle object,
the results would be very different, even though the message is the same.

Polymorphism is made possible through dynamic binding. Dynamic, or late, binding is a


technique that delays identifying the type of object until run-time.
More on OO System Analysis and Design
Object-oriented approaches to developing systems, technically speaking, can use any of the
traditional methodologies presented in above (waterfall development, parallel development, V-
model, iterative development, system prototyping, and throwaway prototyping). The object-
oriented approaches are mostly associated with a RAD methodology.
In 1995, Rational Software brought three industry leaders together to create a single approach
to object-oriented systems development. Grady Booch, Ivar Jacobson, and James Rumbaugh
worked with others to create a standard set of diagramming techniques known as the Unified
Modeling Language (UML).
According to its creators, any object-oriented approach in developing a system must be
(1) Use case driven,
59
(2) Architecture centric, and
(3) Iterative and incremental.

(1)Use Case Driven


Use case driven means that use cases are the primary modeling tool employed to
define the behavior of the system. A use case describes how the user interacts with
the system to perform some activity, such as placing an order, making a reservation
or searching for information.
(2)Architecture Centric
Architecture centric means that the underlying architecture of the evolving system drives the
specification, construction, and documentation of the system. There are three separate, but
interrelated, architectural views of a system: functional, static, and dynamic.
The functional view describes the external behavior of the system from the perspective of the
user.
The static view describes the structure of the system in terms of attributes, methods, classes,
relationships, and messages.
The dynamic view describes the internal behavior of the system in terms of messages passed
between objects and state changes within an object.
(3) Iterative and Incremental
Object-oriented approaches emphasize iterative and incremental development that undergoes
continuous testing throughout the life of the project. Each iteration of the system brings the
system closer and closer to the final needs of the users.

60
1.3 Benefits of Object - Oriented Systems Analysis and Design (Why to
Use?)
Polymorphism, encapsulation, and inheritance taken together allow analysts to break a
complex system into smaller, more manageable components, to work on the components
individually, and to more easily piece the components back together to form a system. This
modularity makes system development easier to grasp, easier to share among members of a
project team, and easier to communicate to users who are needed throughout the SDLC to
provide requirements and
confirm how well the system meets the requirements.
Some of the major benefits are:-
 Objects are reusable
 Maintenance cost are lowered
 Improved quality and maintainability

Unit 2: Requirement Elicitation

Learning objectives of the unit


At the end of this unit trainees are expected to:

 Be able to define requirement elicitation


 be able to state the identify functional requirement, non-functional requirement and
pseudo requirement of
 be able to identify actors of a given system
 be able to identify use cases of a system a system
 be able to describe use cases of a system
 be able to handle requirement elicitation activities

2.1 Introduction

What is a Requirement? It is a statement describing either an aspect of what the proposed


system must do or a constraint on the system’s development. In either case it must contribute
in some way towards adequately solving the customer’s problem. Generally it is taken the set

61
of requirements (requirements document) - as a whole which represents a negotiated
agreement among the stakeholders, mostly between the system developers and customers.
Types of Requirements
A. Functional requirements
 Describe what the system should do
 What inputs the system should accept
 What outputs the system should produce
 What data the system should store that other systems might use
 What computations the system should perform
 The timing and synchronization of the above

B. Non-functional requirements
 Quality requirements
 Throughput
 Resource usage
 Reliability
 Availability
 Recovery from failure
 Allowances for maintainability and enhancement
 Allowances for reusability

62
2.2 Activities in requirement elicitation

1. Identifying actors. During this activity, developers identify the different types of users
the future system will support.
2. Identifying scenarios. During this activity, developers observe users and develop a set
of detailed scenarios for typical functionality provided by the future system. scenarios
are concrete examples illustrating a single case,
3. Identifying use cases: developers derive from the scenarios a set of use cases that
completely represent the future system. Use cases are abstractions describing all
possible cases.

4. Refining use cases: developers ensure that the system specification is complete, by
detailing each use case and describing the behavior of the system in the presence of errors and
exceptional conditions.
5. Identifying relationships among use cases: developers consolidate the use case model by
eliminating redundancies. This ensures that the system specification is consistent.
6. Identifying nonfunctional requirements: developers, users, and clients agree on aspects
that are visible to the user but not directly related to functionality. These include constraints on
the performance of the system, its documentation, the resources it consumes, its security, and
its quality.

Unit 3: Requirement analysis

Learning objectives of the unit


At the end of this unit trainees are expected to:

 Be able to define the Analysis


 Be able to state the Analysis Concepts
 Be able to identify objects of Analysis
 Be able to compare requirements elicitation and Analysis
 Be able to apply Association Multiplicity Revisited
 Be able to use Generalization Object Oriented Analysis (OOA)

3.1 Introduction

63
Object Oriented Analysis:
1. Is a method of analysis that examines requirements from the perspective of the
classes and objects found in the vocabulary of the problem domain?
2. Is about problems rather than solutions.
3. What rather than how.
4. Is discovery rather than invention.
5. Is decomposition rather than recombination.
6. Is presenting the problem as it is.
7. Discovering and understand requirements including decisions on the system’s scope
and how it should behave.
Therefore the analysis phase will be used to understand what to build
The similarity and the difference between requirement elicitation and analysis.
1. Similarity
 It is quite clear that both the requirement gathering and analysis phase deal about what
to build.
 The artifacts (techniques or methods) used in the requirement gathering phase is used
to provide the starting idea to the analysis phase artifacts.
2. Difference
 The requirement gathering phase tries to understand what the user needs and their
usage of the system while the analysis phase will be used to understand the system
itself in addition to the user usage.
 Requirements analysis in system development encompasses those tasks that go into
determining the needs or conditions to meet for a new or altered product, taking
account of the possibly conflicting requirements of the various stakeholders, such as
beneficiaries or users. Because of this requirements must be actionable, measurable,
testable, related to identified business needs or opportunities, and defined to a level of
detail sufficient for system design.

Object-oriented analysis (OOA) looks at the problem domain, with the aim of producing a
conceptual model of the information that exists in the area being analyzed. The result of
object-oriented analysis is a description of what the system is functionally required to do, in
the form of a conceptual model.

64
3.2 Goal of Object Oriented Analysis

Some of the major goals of object oriented system analysis


 To understand the problem or problems that the eventual system should solve.
 To prompt relevant questions about the problem and the system.
 To decide what the system should do and To decide what the system should not do
 To provide a basis for the development of the system.
 To ascertain that the system will satisfy the needs of its users, and define acceptance
criteria.

In order to address the goals of object oriented analysis different techniques/tools are applied,
these tools are:
 (System) Use case model
 Sequence Diagram
 Conceptual Class Model (analysis level)
 Activity Diagram
 UI prototyping
 Evolving Supplementary specifications

3.3 Use case modelling


The use case used in requirement elicitation is called essential use case which shows some
details of the implementation. The use case modeling is oo system analysis which is also
known as system use case modeling is influenced by the technology to be used for the systems
development.
System use case model is composed of the system use case diagram and its corresponding
documentation. The use case diagram and the documentation will have the same components
as the essential use case model with little technology influence.
Note: system use case talks more of the system implementation than essential one.
The concept of “Include” and “Extend” to usecases is mostly applied at the OO system
analysis phase.
Sequence Diagram
A sequence diagram illustrates the objects that participate in a use case and the messages that
pass between them over time for one use case. A sequence diagram is a dynamic model that
supports a dynamic view of the evolving systems. It shows the explicit sequence of messages

65
that are passed between objects in a defined interaction. Since sequence diagrams emphasize
the time-based ordering of the activity that takes place among a set of objects, they are very
helpful for understanding real-time specification and complex use cases.
 A sequence diagram is an interaction diagram that emphasizes the time ordering of
messages.
 A sequence diagram is formed by: -
 Placing the objects that participate in the interaction at the top of the diagram,
along the X-axis
 The object that initiates the interaction is placed on the left most, and
the other subordinate objects are placed to the right
 Placing the messages that these objects send and receive along the Y-axis, in
order of increasing time from top to bottom
Components of a Sequence Diagram
 A sequence diagram has four key components: -
A. Actor and Objects appear along the top margin
B. Lifeline - Each object has a lifeline, which is a dashed line that represent the
life and perhaps death of the object
 Most objects will be in existence for the duration of the interaction
 Objects may also be created during the interaction, or destroyed
C. A focus of control, which is a tall thin rectangle that sits on top of an object’s
lifeline
 It shows the period of time during which an object is performing an
action, either directly or through subordinate procedure
 The bottom part of a focus of control can be marked by a return
message
D. Messages show the actions that objects perform on each other and on
themselves
General steps to Creating a Sequence Diagram
The best way to learn how to create a sequence diagram is to draw one; in order to draw one
can use the following steps.
Step 1. Identify Objects
The first step is to identify instances of the classes that participate in the sequence being
modeled; that is, the objects that interact with each other during the use case sequence.

66
Objects can also be taken from the use case report created during the development of the use
case diagram.
Note: The object found on sequence diagram can be boundary objects, entity objects or
control objects.
i. Boundary objects: is an object with which an actor associated interacts.
Example: if the actor is human, the boundary object may be a window, screen, dialog box, or
menu.
 Entity objects: - is an object that contains long-lived information, such as that
associated with databases.
 Control objects: used as a connecting tissue between boundary objects and entity
objects.
Step 2. Add Messages
 A message is a communication between two objects, or within an object. Messages
support 5 kinds of actions : -
 Call and Return
 Create and Destroy
 Send
Call action
A call action invokes an operation on an object, it is synchronous, meaning that the sender
assumes that the receiver is ready to accept the message, and the sender waits for a response
from the receiver before proceeding.
In UML a call action represented as an arrow from the calling object to the receiving object
Return action
A return action is the return of a value to the caller, in response to a call action.The UML
represents a return action as a dashed arrow from the object returning the value to the object
receiving the value.
Create action
A create action creates an object, it tells a class to create an instance of itself. In the UML,
create action is represented as an arrow with the stereotype <<create>> from the object that
invokes the create action to the created object.
Destroy action
A destroy action destroys an object; it tells an object to destroy itself. In the UML, a destroy
action is represented as an arrow with the stereotype <<destroy>> from the object that invokes

67
the action to the destroyed object. A large X is also added at the end of the destroy arrow to
denote that the object’s lifeline has been terminate
Analysis level Class Diagram
 Also called conceptual model
 Focused on identification of the vocabulary of the system
 Classes and objects
 Classes for completeness and objects for understanding
 Relationships (with some common mechanisms)
 List attributes and methods (methods are Optional)
 Extract attributes and methods from responsibilities
 Review the model with stakeholders (users)
 For 3 Cs (completeness, correctness and consistency)
Example

68
Activity diagram
Activity diagrams describe the workflow behavior of a system. They are typically used for
business process modeling, for modeling the logic captured by a single use case or usage
scenario, or for modeling the detailed logic of a business rule.UML activity diagrams could
potentially model the internal logic of a complex operation. In many ways UML activity
diagrams are the object-oriented equivalent of flow charts.
Note:- Activity diagrams do not give detail about how objects behave or how objects
collaborate.
Activity diagrams are read from top to bottom and have branches and forks to describe
conditions and parallel activities. A fork is used when multiple activities are occurring at the
same time.
Activity diagrams show the sequence of activities in a process, including sequential and
parallel activities. On the diagram different symbols are used to represent activities, decisions
and so on.
In addition to the different symbols an arrow is used to represent events that connect the
activities.

69
 The diagram above shows a fork after activity1.
 This indicates that both activity2 and activity3 are occurring at the same time.
 After activity2 there is a branch. The branch describes what activities will take place
based on a set of conditions.
All branches at some point are followed by a merge to indicate the end of the conditional
behavior started by that branch. After the merge all of the parallel activities must be combined
by a join before transitioning into the final activity state.

Unit 5: System Design

Learning objectives of the unit


At the end of this unit trainees are expected to:

 Be able to discuss about design goals


 Be able to decompose the system into subsystem
 Be able to map a subsystem to hardware
 Be able to select a persistent data management infrastructure
 Be able to select an access control policy
 Be able to select a global control flow mechanism
 Be able to service specification

70
5.1 Different diagrams that can be used at design phase
 Design - meaningful engineering representation of something that is to be built
 SDLC in which requirements are analyzed in order to produce a description of the
software’s internal structure that will serve as the basis for its construction.
 an iterative process through which requirements are translated into a “blueprint” for
constructing the software.
Object Oriented Design is generally considered as a two-step process:
1. Architectural design
Can be carried out using Class type architecture, Component, Deployment, persistent diagrams
2. Detailed design
Can be carried out using refined class model, State chart, collaboration
System Architectural
It is the process of designing the global organization of a software system, which may
includes:
• Dividing software into subsystems.
• Deciding how these will interact.
• Determining their interfaces.
• Is the core of the design, so all system analysts need to understand it.
• Often tighten up the overall efficiency, reusability and maintainability of the system.
iClient-Server (two or three-tier)
Somehow similar with repository but not restricted with one server. (ex WWW)
ii. MVC (model, view, controller)
• Model – main functionality of the application
• Controller – accepts user inputs in a form of events that trigger the execution of
operation within the model (mange sequence of interaction with users)
• View – corresponds to a particular style and format of presentation of information to
the user.
iii. Repository based
• Is typical architecture for DBMS
• Subsystems access and modify data from single data structure called central repository
iv. Peer-to-peer architecture
• Is a generalization of client/server architecture in which subsystem can act both as a
client and/or as a server

71
5.2 Describing an architecture using UML
Some of the common UML diagrams used to describe architecture include
Component diagrams
• Particularly use full for larger sized development teams. It is essentially a class
diagram focusing on system’s components.
• Generally it is used to represent the different high-level reusable parts of a system.
• Also captures the inter-relationships between these parts.
• Represent the implementation perspective of a system.
• Reflect grouping of the different design elements of a system, for example, classes of
the system.
Deployment diagrams
• the configuration of the runtime elements of the developed system
• Is more useful when a system is built and ready to be deployed.
• Provide the necessary environment for the components to execute in.
• It is always a best practice to have visibility of what your deployment environment is
going to be before the system is built so that any deployment-related issues are
identified to be resolved
Persistent diagram
• Is conceptually similar to design class modeling in terms of content.
• Describes the internal schema of a database, depicting the data tables, the data
columns of those tables, the unique nature of some functional columns (attributes) and
the relationships between the tables.
• Mostly generated from class diagram, however there are minor things to remove from
the class diagram and add in persistent modeling due to the nature of the DBMS to be
used for data management.
State chart diagrams
• State chart diagrams show class states and the events that cause them to transition
between states.
• It is also called a state transition diagram, since it shows an event happens at a specific
time and place.
• State chart diagrams are mostly prepared based on class diagrams. However a state
chart diagrams are not created for all classes

72
Self-check questions
Part I: Multiple choices
Instruction: Choose the best response based on your understanding of the topic.
1. What is the primary goal of object-oriented system analysis and design (OOSAD)?
A. To develop efficient algorithms
B. To design user interfaces
C. To create reusable software components
D. To manage database systems
2. Which of the following is NOT a phase in the object-oriented system analysis and design
process?
A. Requirements analysis
B. Implementation
C. Design
D. Testing
3. What is the purpose of use case diagrams in OOSAD?
A. To model the interactions between system components
B. To visualize the structure of a software system
C. To represent the dynamic behavior of the system from the user's perspective
D. To define the classes and relationships in the system
4. Which diagram is used to represent the static structure of a system, including classes,
attributes, and relationships?
A. Activity diagram
B. Sequence diagram
C. Class diagram
D. State diagram
5. In OOSAD, what does the term "encapsulation" refer to?
A. Combining data and methods into a single unit
B. Hiding implementation details from users
C. Specifying the behavior of objects
D. Creating relationships between classes
6. What is the purpose of inheritance in object-oriented programming?
A. To define the behavior of objects
B. To allow objects to communicate with each other
C. To reuse code and create hierarchical relationships between classes

73
D. To enforce data integrity in the system
7. Which of the following is an example of an association relationship between classes in
OOSAD?
A. Inheritance
B. Aggregation
C. Composition
D. Dependency
8. What is the role of a class diagram in OOSAD?
A. To represent the flow of control in a system
B. To model the dynamic behavior of a system
C. To visualize the structure of classes and their relationships
D. To specify the operations performed by the system
9. What does the term "polymorphism" mean in the context of object-oriented programming?
A. The ability to create objects from classes
B. The ability to define multiple methods with the same name but different
implementations
C. The ability to hide implementation details from users
D. The ability to model real-world entities as objects
10. Which diagram is used to represent the interactions between objects over time in OOSAD?
A. Class diagram
B. Sequence diagram
C. Use case diagram
D. State diagram
11. What is the purpose of the "aggregation" relationship in OOSAD?
A. To represent a whole-part relationship between classes
B. To define hierarchical relationships between classes
C. To specify the behavior of objects
D. To enforce data integrity constraints
12. Which of the following is NOT a principle of object-oriented design?
A. Encapsulation
B. Inheritance
C. Abstraction
D. Normalization
13. What is the primary focus of the "requirements analysis" phase in OOSAD?
74
A. Identifying the system's users
B. Defining the functionality and constraints of the system
C. Creating detailed design specifications
D. Implementing the system's features
14. What does the term "abstraction" mean in OOSAD?
A. Representing real-world entities as objects
B. Hiding implementation details from users
C. Defining hierarchical relationships between classes
D. Creating reusable software components
15. Which diagram is used to represent the dynamic behavior of a system, including state
transitions and events?
A. Use case diagram
B. Activity diagram
C. Sequence diagram
D. State diagram
16. What is the purpose of the "dependency" relationship in OOSAD?
A. To represent a whole-part relationship between classes
B. To define hierarchical relationships between classes
C. To specify the behavior of objects
D. To indicate that one class depends on another class
17. Which of the following is a benefit of using object-oriented analysis and design?
A. Reduced development time and cost
B. Increased complexity and maintenance effort
C. Limited reusability of software components
D. Inflexibility in adapting to changing requirements
18. What is the role of a sequence diagram in OOSAD?
A. To model the interactions between system components
B. To visualize the structure of a software system
C. To represent the dynamic behavior of the system from the user's perspective
D. To define the classes and relationships in the system
19. Which of the following is a characteristic of a well-designed class in OOSAD?
A. High cohesion and low coupling
B. Low cohesion and high coupling
C. Lack of encapsulation and abstraction
75
D. Inheritance and polymorphism
20. What is the purpose of the "use case" in OOSAD?
A. To model the interactions between system components
B. To represent the static structure of a system
C. To define the functional requirements of the system from the user's perspective
D. To specify the operations performed by the system

76
REFERENCES:
1. https://www.scribd.com/presentation/493937421/Chapter4-Analysis ,SAMARA
UNIVERSITY
2. https://www.gopalancolleges.com/gcem/course-material/computer-science/course plan/sem-
Vll/object-oriented-modeling-and-design-10CS71.pdf
3. https://www.javatpoint.com/types-of-software-testing
4. Yeates, D., & Wakefield, T. (2004). Systems Analysis and Design. (2nd ed.). Pearson
Education Limited.
5. Ambler, S. W. (2004). The Object Primer, Agile Model Driven Development. (3rd ed.).
6. Warmer, J. B. (1998). The Object Constraint Language: Precise Modeling with UML.
(1st ed.). Addison-Wesley Object Technology Series.
7. Ambler, S. W. (2004). Agile Model Driven Development. Retrieved from
https://ase.in.tum.de/stars.globalse.org/stars1/BookChapters/7ObjectDesign.pdf

77
Sub theme 3: Object Oriented Programing

Unit 1: Introduction to object oriented programing

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Be able to define Object Oriented Programming.
 Be able to know principles and features of Object Oriented Programming
 Be able to install Java IDE software.
 Be able to know the complete development cycle of Java IDE
 Be able to differentiate java application and java applets.

1.1 Principles and Concepts of Object-Oriented Programming (OOP)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program objects. It
simplifies software development and maintenance by providing some concepts:
Object-oriented programming (OOP) is a programming paradigm based on the concept of
objects, which are data structures that contain data, in the form of fields (or attributes) and
code, in the form of procedures (or methods). An object is an entity that has states and
behaviours. A
Distinguishing feature of objects is that an object’s procedures provide access to and modify
its fields. The main ideas behind Java’s Object-Oriented Programming, OOP concepts include
object, class, abstraction, encapsulation, inheritance and polymorphism.
Object Any entity that has state and behaviour is known as an object. E.g, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a
class. An object contains an address and takes up some space in memory.
Class Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.

Inheritance When one object acquires all the properties and behaviours of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Inheritance is a mechanism in which one object acquires all the states and behaviours of a
parent object. Inheritance uses a parent-child relationship (IS-A relationship).

78
Polymorphism If one task is performed in different ways, it is known as polymorphism.
For example: to convince the customer differently, to draw something, for example, shape,
triangle, rectangle, etc. In Java, we use 
• method overloading and 
• Method overriding to achieve polymorphism.
Abstraction Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing. In Java, we use abstract class and
interface to achieve abstraction. Abstraction is a process of hiding the implementation details
and showing only functionality to the user.
Encapsulation Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines. A java class is
the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here. Encapsulation is a process of wrapping code and data together into a
single unit. It's just like a capsule that contains a mix of several medicines, and is a technique
that helps keep instance variables protected.
Association: Association represents the relationship between the objects. Here, one object can
be associated with one object or many objects. There can be four types of association between
the objects:
• One to One
• One to Many
• Many to One, and
Aggregation is a way to achieve Association. Aggregation represents the relationship where
one object contains other objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents
the is-a relationship. It is another way to reuse objects.

79
Unit 2: Basics in java programing

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Know Java’s primitive types
 be able to identify and use literals
 How to declare variable
 Variable declaration rules
 Using variable in java programing
 Use the arithmetic operators, the relational and logical operators
 Understand the assignment operators
 Use shorthand assignments

1.1 identifiers, data types, operators and control structures in Java.

Identifiers
In Java an identifier is, essentially, a name given to a method, a variable, or any other
userdefined item. Identifiers can be from one to several characters long. Variable names may
start with any letter of the alphabet, an underscore, or a dollar sign. Next may be either a letter,
a digit, a dollar sign, or an underscore. The underscore can be used to enhance the readability
of a variable name, as in line_count. Uppercase and lowercase are different; that is, to Java,
myvar and MyVar are separate names.
In general, Java identifiers follow the following rules:
 They can have alphabets, digits, and the underscore and dollar sign characters.
 They must not begin with a digit
 Uppercase and lowercase letters are distinct.
 They can be of any length.
Test, X, y2, MaxLaad ,$up, Jo, p, nriyvar, sample23
Variable
A variable is a named memory location that can be assigned a value. Further, the value of a
variable can be changed during the execution of a program. That is, the content of a variable is
changeable, not fixed. The following program creates two variables called myVar1 and
myVar2.
Initializing a Variable

80
One way to give a variable a value is through an assignment statement, as you have already
seen. Another way is by giving it an initial value when it is declared. To do this, follow the
variable’s name with an equal sign and the value being assigned. The general form of
initialization is shown here:
type var = value;

Data types
Data types are especially important in Java because it is a strongly typed language. This means
that all operations are type-checked by the compiler for type compatibility. Illegal operations
will not be compiled. Thus, strong type checking helps prevent errors and enhances reliability.
To enable strong type checking, all variables, expressions, and values have a type. There is no
concept of a “type-less” variable, for example. Furthermore, the type of a value determines
what operations are allowed on it. An operation allowed on one type might not be allowed on
another.
Integers
Java defines four integer types: byte, short, int, and long. The most commonly used integer
type is int. Variables of type int are often employed to control loops, to index arrays, and to
perform general-purpose integer math.

Floating-Point Types

81
The floating-point types can represent numbers that have fractional components. There are two
kinds of floating-point types, float and double, which represent single- and double-precision
numbers, respectively. Type float is 32 bits wide and type double is 64 bits wide.
Characters
In Java, characters are not 8-bit quantities like they are in many other computer languages.
Instead, Java uses Unicode. Unicode defines a character set that can represent all of the
characters found in all human languages.
A character variable can be assigned a value by enclosing the character in single quotes. For
example, this assigns the variable ch the letter X:
char ch;
ch = ‘ X’;
The boolean type
The boolean type represents true/false values. Java defines the values true and false using the
reserved words true and false. Thus, a variable or expression of type boolean will be one of
these two values. Here is a program that demonstrates the boolean type:

The boolean type represents true/false values. Java defines the values true and false using the
reserved words true and false. Thus, a variable or expression of type boolean will be one of
these two values. Here is a program that demonstrates the boolean type:
Character Escape Sequences
Enclosing character constants in single quotes works for most printlng characters, but a few
characters, such as the carriage return, pose a special problem when a text editor is used.

82
1.2 Operators
Java provides a rich operator environment. An operator is a symbol that tells the compiler to
perform a specific mathematical or logical manipulation. Java has four general classes of
operators:
Arithmetic
Java defines the following arithmetic operators:
• Bitwise,
• Relational, and
• Logical.
The operators +,-,*, and / all work the same way in Java as they do in any other computer
language (or algebra, for that matter). These can be applied to any built-in numeric data type.
They can also be used on objects of type char.
Increment and Decrement
The increment operator adds 1 to its operand, and the decrement operator subtracts 1.
Therefore,
x = x + 1; is the same as x + +;
x = x - 1; is the same as x-- ;
Both the increment and decrement operators can either precede (prefix) or follow (postfix) the
operand. For example,
x = x + 1; can be written as + +x; // prefix form or as
x++; // postfix form
Consider the following:

83
x = 10;
y = ++x;
In this case, y will be set to 11. However, if the code is written as
x = 10;
y = x++;
Relational and logical operators
It refers to the relationships that values can have with one another, and logical refers to the
ways in which true and false values can be connected together. Since the relational operators
produce true or false results, they often work with the logical operators. For this reason they
will be discussed together here.

1.3 Control structure


Control Statements
There are three categories of program control statements:
 selection statements, which include the if and the switch;
 iteration statements, which include the for, while, and do-while loops; and
 jump statements, which include break, continue, and return.
The if statement
The complete form of the if statement is If(condition) statement; else statement; where the
targets of the if and else are single statements. The else clause is optional. The targets of both
the if and else can be blocks of statements. The general form of the if, using blocks of
statements, is
if(condition)
{

84
statement sequence
}
Else
{
statement sequence
}
The if-else-if ladder
A common programming construct that is based upon the nested if is the if-else-if
ladder. It looks like this:
if{condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
The switch statement
The second of Java’s selection statements is the switch. The switch provides for a multiway
branch. Thus, it enables a program to select among several alternatives.
The general form of the switch statement is
Switch (expression) {
case constant1: statement sequence
break;
case constant2: statement sequence
break;
case constants3: statement sequence
break;
default: statement sequence
}
The for loop
85
You have been using a simple form of the for loop since Chapter l. You might be surprised at
just how powerful and flexible the for loop is. Let’s begin by reviewing the basics, starting
with the most traditional forms of the for. The general form of the for loop for repeating a
single statement is
for (initialization; condition; iteration) statement;
For repeating a block, the general form is
for (initialization; condition; iteration)
{
statement sequence
}

The while loop


The loop repeats while the condition is true. When the condition becomes false, program
control passes to the line immediately following the loop.
class WhileDemo {
public static void main(String args[])
{
char ch;
// print the alphabet using a while loop
ch = 'a ';
while(ch <='z') {
System.out.print (ch)
ch++;
}
}
}
The do-while loop
The last of Java’s loops is the do-while. Unlike the for and the while loops, in which the
condition is tested at the top of the loop, the do-while loop checks its condition at the bottom
of the loop. This means that a do-while loop will always execute at least once. The general
form of the do-while loop is
do{
statements;
} while(condition);
86
Unit 3: Objects and classes

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Be able to define Object Oriented Programming.
 Be able to know principles and features of Object Oriented Programming.
 Be able to install Java IDE software.
 Be able to know the complete development cycle of Java IDE.
 Be able to differentiate java application and java applets.

3.1 Introduction

Object-oriented programming (OOP) involves programming using objects. An object


represents an entity in the real world that can be distinctly identified. For example, a student, a
desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique
identity, state, and behaviors. The state of an object consists of a set of data fields (also known
as properties) with their current values. The behavior of an object is defined by a set of
methods.
Creating a Class
Classes contain two things:
Fields (attributes, data members, class variables):
• Data items that differentiate one object of the class from another. e.g.
employee name, student number
• Characteristics of an object that have values
Methods (behaviors):
• Named, self-contained blocks of code that typically operate on the fields
• Describe what an object can do
• Can be thought of as the verbs in a problem domain
For example:
public class Student {
String name;
String IDNo;
int GPA;
void study(){}
87
}

3.2 Declaring a Variable of a Class Type


Variables and Data Type Variables are defined in Java using the following format:
<access modifier> <type> <variable name>;
e.g. public String name;
private int count;
Valid access modifiers for fields(variables) are:
• Public: available to all methods and classes.
• Private: available only to methods in the class.
• Protected: available only to methods in the class, it’s children and other classes in
the
same package
Class' Member Variables
Consider a class named House:
public class House {
}
The section between the curly brackets, { and }, of a class is referred to as its body. In the
body
of a class, you can create a list of the parts that make up the class. Each of these parts must be
a complete variable with a name and a data type. For example, here are the characteristics that
make up a house, declared as the parts of the above class and each declared as a variable:

public class House {


String propertyNumber;
char propertyType;
byte Stories;
int bedrooms;
double Value;
}

3.3 Initializing an Object


After declaring an instance of a class, you can access each of its members and assign it the
desired value. Here is an example:
public class House {
long propertyNumber;

88
String propertyType;
byte Stories;
public int Bedrooms;
double MarketValue;
}
public class Main {
public static void main(String[] args) {
House property = new House();
property.propertyNumber = 283795;
property.propertyType = "Single Family";
property.Bedrooms = 4;
property.MarketValue = 652880;
}
}
Once a member variable has been initialized, you can use the period operator to access it and
retrieve its value:
public class Main {
public static void main(String[] args) {
House property = new House();
property.propertyNumber = 283795;
property.propertyType = "Single Family";
property.Bedrooms = 4;
property.MarketValue = 652880;
System.out.println("=//= Altair Realty =//=");
System.out.println("Properties Inventory"); ;
System.out.println("Property #: " +
property.propertyNumber);
System.out.println("Property Type: " +
property.propertyType);
System.out.println("Bedrooms: " +
property.Bedrooms);
System.out.println("Market Value: " +
property.MarketValue);
}
}
3.4 Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory. It is a special type of method which is used to initialize the object.
There are two types of constructors in Java:

89
• no-arg constructor, and
• Parameterized constructor.
Rules for creating Java constructor
There are two rules defined for the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized.
Types of Java constructors
There are two types of constructors in Java:
• Default constructor (no-arg constructor)
• Parameterized constructor
A constructor is called "Default Constructor" when it doesn't have any parameter. Syntax of
default constructor: (){}

Unit 4: Objects oriented programing concept

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Be able to describe basic Concepts of Object Oriented Programming.
 Be able to know principles Encapsulation
 Be able to use of the concept of inheritance
 Be able to use of the concept of Polymorphism

4.1 Inheritance
Inheritance is the process by which one object can acquire the properties of another object.
This is important because it supports the concept of hierarchical classification. If you think
about it, most knowledge is made manageable by hierarchical (i.e., top-down) classifications.
For example, a Red Delicious apple is part of the classification apple, which in turn is part of
the fruit class, which is under the larger class/food. That is, the food class possesses certain
qualities (edible, nutritious, etc.) which also, logically, apply to its subclass, fruit. In addition
to these qualities, the fruit class has specific characteristics (juicy, sweet, etc.) that distinguish
it from other food. The apple class defines those qualities specific to an apple (grows on trees,
not tropical, etc.). A Red Delicious apple would, in turn, inherit all the qualities of all
preceding classes, and would define only those qualities that make it unique.
90
Single Inheritance: Derivation a subclass from only one super class is called Single
Inheritance.
Hierarchical Inheritance: Derivation of several classes from a single super class is called
Hierarchical Inheritance:
Multilevel Inheritance: Derivation of classes from another derived classes called Multilevel
Inheritance.
Multiple Inheritances: Derivation of one class from two or more super classes is called
Multiple Inheritances. But java does not support Multiple Inheritance directly. It can be
implemented by using interface concept.
Hybrid Inheritance: Derivation of a class involving more than one from on Inheritance is
called Hydride Inheritance.

4.2 Encapsulation
Encapsulation is a programming mechanism that binds together code and the data it
manipulates, and that keeps both safe from outside interference and misuse. In an object-
oriented language, code and data can be bound together in such a way that a self-contained
black box is created. Within the box are all necessary data and code. When code and data are
linked together in this fashion, an object is created. In other words, an object is the device that
supports encapsulation. Encapsulation is one of the four fundamental OOP concepts. The other
three are inheritance,
Polymorphism and abstraction. Encapsulation in Java is a mechanism of wrapping the data
variables and code acting on the data methods together as as single unit. In encapsulation the

91
variables of a class will be hidden from other classes, and can be accessed only through the
methods of their current class, therefore it is also known as data hiding.
To achieve encapsulation in Java
• Declare the variables of a class as private.
• Provide public setter and getter methods to modify and view the variables values.

92
Self-check
1. Which of the following are valid Identifiers?
a) $amount b) 6tally c) my*Name d) salary
e) score f) first Name g) total# h) cast
2. Where to declare local variables?
A. It declares inside the class and outside of method.
B. It declares inside the class with static prefix and outside of method.
C. It declares inside the method.
3. Where to declare instance variables?
A. It declares inside the class and outside of method.
B. It declares inside the class with static prefix and outside of method.
C. It declares inside the method.
4. Where to declare class variables?
A. It declares inside the class and outside of method.
B. It declares inside the class with static prefix and outside of method.
C. It declares inside the method.
5. Which of following cannot be used as variable name in Java Programming?
A. literal
B. Keywords
C. Identifier
D. Identifier and Keywords
6. A name of variable is known as
A. Data Type
B. Constant
C. Identifier
7. 6. Which is the invalid variable name ?
A. tenthTeam
B. TenthTeam
C. 10thTeam
D. None of Above
8. A variable name should not begin with
A. A number
B. Special characters but underscore and dollar sign
C. All of above
93
9. Which is the valid variable name ?
A. 5thTeam
B. &5thteam
C. _5thTeam
D. None of Above
10. A variable declared inside the method is known as
public class TestMain {
public static void main(String[] args) {
String msg = "Hello World"; // msg variable name
System.out.println(msg);
}
}
A. Instance Variable
B. Class Variable
C. Local Variable
11. A variable declared outside of a method is known as
public class TestMain {
String msg = "Hello World"; // msg variable name
public static void main(String[] args) {
TestMain test = new TestMain();
System.out.println(test.msg);
}
}
A. Instance Variable
B. Class Variable
C. Local Variable
12. A variable declared outside of a method with prefix static keyword is known as
public class TestMain {
static String msg = "Hello World"; // msg variable name
public static void main(String[] args) {
System.out.println(msg);
}
}
A. Instance Variable
94
B. Class Variable
C. Local Variable
REFERENCE
1. Java: A Beginner's Guide, Eighth Edition by Herbert Schildt
2. Java: How to Program, 9th Edition (Deitel)
3. https://www.javatpoint.com/

95
Sub theme 4: Data Structure and algorithm

Unit 1: Common algorithm analysis techniques

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Define data structure
 Understand ADT
 Define algorithm and know it’s characters

1.1 Introduction

Algorithm analysis techniques are essential for evaluating the efficiency and performance of
algorithms. Usually, the efficiency or running time of an algorithm is stated as a function
relating the input length to the number of steps (time complexity) or storage locations (space
complexity). Algorithm analysis is an important part of a broader computational complexity
theory, which provides theoretical estimates for the resources needed by any algorithm which
solves a given computational problem. These estimates provide an insight into reasonable
directions of search for efficient algorithms.
Here are some common techniques:
Asymptotic Analysis: Analyzing the behavior of algorithms as the input size approaches
infinity. It's represented using Big O, Omega, and Theta notations.
Big O Notation: Describes the upper bound of an algorithm's running time in the worst-case
scenario. Big-Oh notation is a way of comparing algorithms and used for computing the
complexity of algorithms; i.e., the amount of time that it takes computer program to run. It is
only concerned with what happens for very a large value of n. Therefore, only the largest term
in the expression (function) is needed. For example, if the number of operations in an
algorithm is n 2 – n, n is insignificant compared to n 2 for large values of n. Hence the n term
is ignored. Of course, for small values of n, it may be important.
However, Big-Oh is mainly concerned with large values of n. It describes the upper bound of
an algorithm's runtime and calculates the time and amount of memory needed to execute the
algorithm for an input value. In other words, it calculates the worst-case time complexity of an
algorithm. The expression can be described as a function f(n) belongs to the set O(g(n)) if
there exists a positive constant c such that it lies between 0 and cg(n), for sufficiently large n.
96
For any value of n, the running time of an algorithm does not cross the time provided by
O(g(n)). Since it gives the worst-case running time of an algorithm, it is widely used to
analyze an algorithm as we are always interested in the worst-case scenario.
Properties of the Big-O Notation
• Higher powers grow faster
• Fastest growing term dominates a sum
If f(n) is O(g(n)), then f(n) + g(n) is O(g)
E.g 5n4 + 6n3 is O (n4)
• Exponential functions grow faster than powers
E.g. n20 is O( 1.05n)
• Logarithms grow more slowly than powers
E.g. log2n is O( n0.5)
Omega Notation: Describes the lower bound of an algorithm's running time in the best-case
scenario.
Theta Notation: Describes the tight bound of an algorithm's running time, combining both
upper and lower bunds.
Space Complexity Analysis: Evaluates the amount of memory space required by an algorithm
to solve a problem.
Time Complexity Analysis: Analyzes the number of basic operations performed by an
algorithm as a function of the input size.
Amortized Analysis: Analyzes the average time complexity of a sequence of operations on a
data structure.
Worst-Case Analysis: Determines the maximum time required by an algorithm for any input
of size n.
Best-Case Analysis: Determines the minimum time required by an algorithm for any input of
size n.
Experimental Analysis: Testing the algorithm on different inputs and measuring its
performance.
Optimization Techniques: Strategies to improve the efficiency of algorithms, such as
memorization, dynamic programming, and loop optimization.

Unit 2: Swapping of various sorting and searching algorithms.

Learning objectives of the unit


97
At the end of this unit trainees are expected to:
 Understand basic searching algorithm
 Implement searching algorithms
 Differentiate searching algorithms
 Differentiate sorting algorithms

2.1 Searching
Information retrieval is one of the most important applications of computers. We are given a
name and are asked for an associated telephone listing. We are given an account number and
are asked for the transactions occurring in that account. We are given an employee name or
number and are asked for the personnel records of the employee. Searching is a process of
looking for a specific element in a list of items or determining that the item is not in the list.
There are two simple searching algorithms:
• Sequential Search, and
• Binary Search
Linear Search (Sequential Search)
The search always starts at the first element in the list and continues until either the item is
found in the list or the entire list is searched. Because we are interested in the performance of
the sequential search (that is, the analysis of this type of search), for easy reference and for the
sake of completeness, we give the sequential search algorithm for array-based lists. If the
search item is found, its index (that is, its location in the array) is returned. If the search is
unsuccessful, -1 is returned. Note that sequential search does not require the list elements to be
in any particular order.
A linear search is the simplest approach employed to search for an element in a data set. It
examines each element until it finds a match, starting at the beginning of the data set, until the
end. The search is finished and terminated once the target element is located.
To determine the average number of comparisons in the successful case of the sequential
search algorithm:
1. Consider all possible cases.
2. Find the number of comparisons for each case.
3. Add the number of comparisons and divide by the number of cases.
A linear search runs in at worst linear time and makes at most n comparisons, where n is the
length of the list. If each element is equally likely to be searched, then linear search has an
average case of (n+1)/2 comparisons, but the average case can be affected if the search
probabilities for each element vary. Linear search is rarely practical because other search

98
algorithms and schemes, such as the binary search algorithm and hash tables, allow
significantly faster searching for all but short lists.
• Worst-case performance O(n)
• Best-case performance O(1)
• Average performance O(n)
Implementation:
int Linear_Search(int list[], int key)
{
int index=0;
int found=0;
do{
if(key==list[index])
found=1;
else
index++;
}while(found==0&&index<n);
if(found==0)
index=-1;
return index;
}
Binary Search
Sequential search is easy to write and efficient for short lists, but a disaster for long ones.
Imagine trying to find the name “Amanda Thompson” in a large telephone book by reading
one name at a time starting at the front of the book! To find any entry in a long list, there are
far more efficient methods, provided that the keys in the list are already sorted into order.
Binary search algorithm,
• Divide the search space into two halves by finding the middle index “mid”.
• Compare the middle element of the search space with the key.
• If the key is found at middle element, the process is terminated.
• If the key is not found at middle element, choose which half will be used as the next
search space.
Implementation:
int Binary_Search(int list[],int k)
{

99
int left=0;
int right=n-1;
int found=0;
do{
mid=(left+right)/2;
if(key==list[mid])
found=1;
else{
if(key<list[mid])
right=mid-1;
else
left=mid+1;
}
}while(found==0&&left<right);
if(found==0)
index=-1;
else
index=mid;
return index;
}

2.2 Sorting Algorithms

Sorting is one of the most important operations performed by computers. Sorting is a process
of reordering a list of items in either increasing or decreasing order. The following are simple
sorting algorithms used to sort small-sized lists.
• Insertion Sort
• Selection Sort
• Bubble Sort
• Insertion Sort: The insertion sort works just like its name suggests it inserts each item into
its proper place in the final list. The simplest implementation of this requires two list
structures: the source list and the list into which sorted items are inserted. To save memory,
most implementations use an in-place sort that works by moving the current item past the
already sorted items and repeatedly swapping it with the preceding item until it is in place.
100
It's the most instinctive type of sorting algorithm. The approach is the same approach that you
use for sorting a set of cards in your hand. While playing cards, you pick up a card, start at the
beginning of your hand and find the place to insert the new card, insert it and move all the
others up one place.
Implementation
void insertion_sort(int list[]){
int temp;
for(int i=1;i<n;i++){
temp=list[i];
for(int j=i; j>0 && temp<list[j-1];j--)
{
list[j]=list[j-1];
list[j-1]=temp;
}//end of inner loop
}//end of outer loop
}//end of insertion_sort
Selection Sort
Insertion sort has one major disadvantage. Even after most entries have been sorted properly
into the first part of the list, the insertion of a later entry may require that many of them be
moved. All the moves made by insertion sort are moves of only one position at a time. Thus to
move an entry 20 positions up the list requires 20 separate moves. If the entries are small,
perhaps a key alone, or if the entries are in linked storage, then the many moves may not
require excessive time. But if the entries are very large, records containing hundreds of
components like personnel files or student transcripts, and the records must be kept in
contiguous storage, and then it would be far more efficient if, when it is necessary to move an
entry, it could be moved immediately to its final position. Our next sorting method
accomplishes this goal.
Implementation:
void selection_sort(int list[])
{
int i,j, smallest;
for(i=0;i<n;i++)
{
smallest=i;
101
for(j=i+1;j<n;j++)
{
if(list[j]<list[smallest])
smallest=j;
}//end of inner loop
temp=list[smallest];
list[smallest]=list[i];
list[i]=temp;
} //end of outer loop
}//end of selection_sort
• Selection sort doesn’t need extra space and it produce an output in same memory.
• At the end of each step in selection sort, the smallest element will be in its sorted position.
Assuming the sorting is ascending order.
Bubble Sort
The bubble sort makes n –1 passes through a sequence of n elements. Each pass moves
through the array from left to right, comparing adjacent elements and swapping each pair that
is out of order. This gradually moves the larger elements to the right. It is called the bubble
sort because if the elements are visualized in a vertical column, then each pass appears to
“bubble up” the next largest element by bouncing it off smaller elements, much like the rising
bubbles in a carbonated beverage.
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in the wrong order. These passes through the list are repeated until no
swaps had to be performed during a pass, meaning that the list has become fully sorted. This
algorithm is not suitable for large data sets as its average and worst-case time complexity is
quite high.
Basic Idea:
• Loop through array from i=0 to n and swap adjacent elements if they are out of order.
Algorithm
(Precondition: s = {s0 . . . sn–1 } is a sequence of n ordinal values.)
(Post condition: The entire sequence s is sorted.)
1. Do steps 2–4 for i = n – 1 down to 1.
2. Do step 3 for j = 0 up to i–1 .
3. If the two consecutive elements s j and sj+1, are out of order, swap them.
4. (Invariants: The subsequence {si . . . sn–1 } is sorted, and si = max{s0 . . . si}.)
102
Implementation:
void bubble_sort(list[])
{
int i,j,temp;
• Bubble sort doesn’t need extra space and it produce an output in same memory.
• At the end of each step in bubble sort, the largest element will be in its sorted
position. Assuming the sorting is ascending order.
27649
26749
26479
24679
24679
for(i=0;i<n; i++){
for(j=n-1;j>i; j--)
{
if(list[j]<list[j-1])
{
temp=list[j];
list[j]=list[j-1];
list[j-1]=temp;
}//swap adjacent elements
}//end of inner loop
}//end of outer loop

}//end of bubble_sort

103
Unit 3: ADT linked list operations

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Differentiate array and linked list
 Understand the concept of single and double linked list
 Write a C++ code to effectively implement linked list structure
 Know how to create, delete and traverse a linked list

A linked list is a linear data structure, in which the elements are not stored at contiguous
memory locations. The elements in a linked list are linked using pointers. Linked lists are the
most basic self-referential structures. Linked lists allow you to have a chain of struct with
related data. Linked List forms a series of connected nodes, where each node stores the data
and the address of the next node.

3.1 Creating Linked Lists in C++


A linked list is a data structure that is built from structures and pointers. It forms a chain of
"nodes" with pointers representing the links of the chain and holding the entire thing together.
A diagram like this one can represent a linked list:

3.2 Adding a node to the list

The first problem that we face is how to add a node to the list. For simplicity's sake, we will
assume that it has to be added to the end of the list, although it could be added anywhere in
the list. Adding new node to the list can be done: • At the beginning of the list • At the end of
the list and • In between the lists.
Adding node at the beginning
Once after we know how to create a node, adding the node to the existing list is mandatory. As
we saw on the previous part, adding the new node at the end of the list is possible. But that is
not the only option to insert new nodes to the linked list. The other option is to insert the new

104
node at the beginning of the existing list. Inserting at the beginning is relatively easy than the
other two options. That is because, we don’t need to move through the lists and we have the
name of the first list.
Implementation
temp = new node;
cout<< "Please enter the name of the person: ";
cin>> temp->name;
cout<< "Please enter the ID of the person : ";
cin>> temp->ID;
cout<< "Please enter the height of the person : ";
cin>> temp->height;
temp->nxt = NULL;
if(start_ptr==NULL)
start_ptr=temp;
else
{
temp->nxt=start_ptr;
start_ptr=temp;
}
Adding node at the end It is harder if there are already nodes in the list. In this case, the secret
is to declare a second pointer, temp2, to step through the list until it finds the last node.

temp2 = start_ptr; // We know this is not NULL - list not empty!


while (temp2->nxt != NULL)
{ temp2 = temp2->nxt; // Move to next link in chain }
The loop will terminate when temp2 points to the last node in the chain, and it knows when
this happened because the nxt pointer in that node will point to NULL. When it has found it, it
sets the pointer from that last node to point to the node we have just declared:

105
Insertion in between nodes The other option of inserting new node is adding them in between
the nodes. This can be done by the user interest. Assume that we have multiple nodes in the
linked list and the user wants to add the new one between two of them. This process is a bit
difficult because inserting between two nodes needs connecting three different nodes. The first
thing we need to do now is, use a temporary variable and move to the required node. We are
not going to use start_ptr because we say that the first list must have a name and we cant move
that name from the first list.
temp2=start_ptr; Then move temp2 until we reach the place where we want to add the new
node or to the end of the list. while(temp2->data!=key && temp2->nxt!=NULL)
temp2=temp2->nxt; Assume key is the data that we are searching for to insert the new node.

Unit 4. Stack and Queue


Learning objectives of the unit
At the end of this unit trainees are expected to:
 Understand stack
 Know the applications of stack
 Write a code to implement all applications of stack on the course material
 Understand the concept of queue
 Know the applications of queue
 Work on the operations of queue

A stack is a version of a list that is particularly useful in applications involving reversing, such
as the problem of given above. In a stack data structure, all insertions and deletions of entries
are made at one A simple data structure, in which insertion and deletion occur at the same end,
is termed (called) a stack. It is a LIFO (Last In First Out) structure.
A Stack is a linear data structure that holds a linear, ordered sequence of elements. It is an
abstract data type. A Stack works on the LIFO process (Last In First Out), i.e., the element that
was inserted last will be removed first. To implement the Stack, it is required to maintain a
Figure below Stack operation Push and Pop pointer to the top of the Stack, which is the last
element to be inserted because we can access the elements only on the top of the Stack.
The operations of insertion and deletion are called PUSH and POP
Push - push (put) item onto stack

106
Pop - pop (get) item from stack end, called the top of the stack.

Example 3.3. xxxxxxxxxxxxxxxxx

4.1 Standard Stack Operations


The following are some common operations implemented on the stack:
push(): When we insert an element in a stack then the operation is known as a push. If the
stack is full then the overflow condition occurs.
pop(): When we delete an element from the stack, the operation is known as a pop. If the stack
is empty means that no element exists in the stack, this state is known as an underflow state.
isEmpty(): It determines whether the stack is empty or not.
isFull(): It determines whether the stack is full or not.
peek(): It returns the element at the given position.
count(): It returns the total number of elements available in a stack.
change(): It changes the element at the given position.
display(): It prints all the elements available in the stack.
PUSH: PUSH operation implies the insertion of a new element into a Stack. A new element is
always inserted from the topmost position of the Stack; thus, we always need to check if the
top is empty or not, i.e., TOP=Max-1 if this condition goes false, it means the Stack is full, and
no more elements can be inserted, and even if we try to insert the element, a Stack overflow
message will be displayed.
Implementation:
Stacks can be implemented both as an array (contiguous list) and as a linked list. We want a
set of operations that will work with either type of implementation: i.e. the method of

107
implementation is hidden and can be changed without affecting the programs that use them.
The Basic Operations:
Push()
{
if there is room {
put an item on the top of the stack
else
give an error message
}
}
Pop()
{
if stack not empty
{
return the value of the top item
remove the top item from the stack
}
Else
{
give an error message
}
}
CreateStack()
{
remove existing items from the stack
initialise the stack to empty}

4.2 A queue
A queue is an information structure in which the first item that is inserted is the first that is
available (first in, first out). This is in contrast to a stack in which the first item that is
available is the last item inserted (first in, last out). Many software applications require the
logical equivalent of accessing ''things" in the same order as inserted. For computer
applications, we similarly define a queue to be a list in which all additions to the list are made

108
at one end, and all deletions from the list are made at the other end. Queues are also called
first-in, first-out list or FIFO in short.
A Queue is defined as a linear data structure that is open at both ends and the operations are
performed in First In First Out (FIFO) order. Queue, like Stack, is also an abstract data
structure. The thing that makes queue different from stack is that a queue is open at both its
ends. In general a queue is:
• A linear data structure that has access to its data at the front and rear.
• Operates on FIFO (Fast In First Out) basis.
• Uses two pointers/indices to keep track of information/data

Basic Operations of Queue


A queue is an object (an abstract data structure - ADT) that allows the following
operations:
• Enqueue: Add an element to the end of the queue
• Dequeue: Remove an element from the front of the queue
• IsEmpty: Check if the queue is empty
• IsFull: Check if the queue is full
• Peek: Get the value of the front of the queue without removing it
Application of Queue
Task Scheduling: Queues can be used to schedule tasks based on priority or the order in
which they were received.
Resource Allocation: Queues can be used to manage and allocate resources, such as printers
or CPU processing time.
Batch Processing: Queues can be used to handle batch processing jobs, such as data analysis
or image rendering.
Message Buffering: Queues can be used to buffer messages in communication systems, such
as message queues in messaging systems or buffers in computer networks.
Event Handling: Queues can be used to handle events in event-driven systems, such as GUI
applications or simulation systems.
Traffic Management: Queues can be used to manage traffic flow in transportation systems,
such as airport control systems or road networks.
Operating systems: Operating systems often use queues to manage processes and resources.
For example, a process scheduler might use a queue to manage the order in which processes
are executed.
109
Network protocols: Network protocols like TCP and UDP use queues to manage packets that
are transmitted over the network. Queues can help to ensure that packets are delivered in the
correct order and at the appropriate rate.
Printer queues: In printing systems, queues are used to manage the order in which print jobs
are processed. Jobs are added to the queue as they are submitted, and the printer processes
them in the order they were received.

4.3 Traversing through a tree data structure.


Traversing through a tree data structure in C++ involves similar techniques as described
earlier, but with the implementation in C++. Here's a note on ways to traverse a tree using
C++.
Inorder Traversal
In C++, inorder traversal of a binary tree can be implemented using recursion.
void inorder(Node* node) {
if (node != nullptr) {
inorder(node->left);
cout << node->data << " ";
inorder(node->right);
}
}
Preorder Traversal:
Preorder traversal can also be implemented recursively in C++:
void preorder(Node* node) {
if (node != nullptr) {
cout << node->data << " ";
preorder(node->left);
preorder(node->right);
}
}
Postorder Traversal:
Postorder traversal can be implemented recursively as well:
void postorder(Node* node) {
if (node != nullptr) {
postorder(node->left);
postorder(node->right);
cout << node->data << " ";
}
}
Level Order Traversal (Breadth-First Traversal):

110
Level order traversal can be implemented using a queue data structure for breadth-first
traversal:
void levelOrder(Node* root) {
if (root == nullptr)
return;

queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* current = q.front();
cout << current->data << " ";
q.pop();
if (current->left != nullptr)
q.push(current->left);
if (current->right != nullptr)
q.push(current->right);
}
}

111
Self-check questions
Part I: Multiple choices
Instruction: Choose the best response based on your understanding of the topic.
1. ________ of an algorithm refers to defining the mathematical bound /framing of its
runtime performance.
A. Symptotic analysis
B. Asymptotic analysis
C. Posterior Analysis
D. Priori Analysis
2. Using asymptotic analysis, we can very well conclude the __________ scenario of an
algorithm.
A. best case
B. average case
C. worst case
D. best case, average case, and worst case
3. Which case indicates the minimum time required for program execution?
A. best case
B. average case
C. worst case
D. None of the above
4. __________ is the formal way to express the upper bound of an algorithm's running time.
A. Omega Notation
B. Theta Notation
C. Big Oh Notation
D. All of the above
5. Worst Case indicates maximum time required for program execution.
A. Yes
B. No
C. Can be yes or no
D. Cannot say
6. Which of the following is a linear asymptotic notation?
A. Ο(1)
B. Ο(log n)
C. Ο(n)
112
D. Ο(n log n)
7. Ο(log n) is?
A. constant asymptotic notations
B. logarithmic asymptotic notations
C. polynomial asymptotic notations
D. quadratic asymptotic notations
8. Omega Notation is the formal way to express the lower bound of an algorithm's running
time.
A. True
B. False
C. Can be true or false
D. Cannot say
9. The Theta notation is the formal way to express ____________ of an algorithm's running
time.
A. upper bound
B. lower bound
C. lower bound and upper bound
D. None of the above
10. Asymptotic analysis is _______ bound.
A. output
B. input
C. outer
D. inner

REFERENCES
[1] Data Structures A Pseudocode Approach With C ++ By – Richard F. Gilber. Behrouz A.
Forouzan (Thomson Press)
[2] https://www.javatpoint.com/ last accessed May 2023
[3] Gregory L. Heileman, Data Structures, Algortihms, And Object –Oriented Programming,
[4] https://dev.to/rinsama77/ last accessed January 2023
[5] https://www.geeksforgeeks.org last accessed May 2023
[6] SartajSahni, Data Structures, Algorithms, and Applications In C ++
[7] https://www.quora.comlast accessed april 2023
[8] https://favtutor.com/blogs/ last accessed May 2023

113
Sub theme 5: Mobile Computing

Unit 1: Fundamental concepts of wireless communication

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Be able to understand the basics of wireless communication.
 Be able to understand cellular mobile communication.
 Be able to understand computing trends.
 Be able to learn different mobile generations (1G,..5G).
 Be able to learn about electromagnetic spectrum.

1.1 Introduction

Wireless communication is basically transmitting and receiving voice and data using
electromagnetic waves in open space. The origin of wireless communications can be traced
back to the year 1857, when the behavior of electromagnetic waves was explained
mathematically using four equations by James Clerk Maxwell. Maxwell’s four equations
describe the electric and magnetic fields arising from varying distributions of electric charges
and currents, and how those fields change with time.
The equations were the mathematical representation of decades of experimental observations
of the electric and magnetic effects of charges and currents. According to Maxwell, an
accelerated charge creates a magnetic field in its neighborhood which in turn creates an
electric field in the same area. A moving magnetic field produces an electric field and vice
versa. These two fields vary with time, so they act as sources of each other. Thus, an
oscillating charge having non-zero acceleration will emit an electromagnetic (EM) wave and
the frequency of the wave will be same as that of the oscillation of the charge. Though the
electromagnetic waves were first discovered as a communication medium at the end of the
nineteenth century, these were put in use for the masses later.
Wireless communication has become an integral part of our daily lives, enabling seamless
connectivity and information exchange across various devices and networks. Understanding
the fundamental concepts of wireless communication is essential for comprehending the

114
underlying principles, technologies, and protocols that facilitate wireless connectivity. In this
note, we explore the key fundamental concepts of wireless communication:
Electromagnetic Spectrum: Wireless communication relies on electromagnetic waves for
transmitting data. The electromagnetic spectrum encompasses a range of frequencies, from
low-frequency radio waves to high-frequency gamma rays. Different wireless technologies
utilize specific frequency bands within this spectrum, each offering distinct advantages in
terms of coverage, bandwidth, and propagation characteristics.
Modulation: Modulation is the process of encoding digital information onto an analog carrier
signal for transmission over the wireless medium. Common modulation techniques include
Amplitude Modulation (AM), Frequency Modulation (FM), and Phase Shift Keying (PSK).
Modulation schemes are chosen based on factors such as data rate, bandwidth efficiency, and
signal-to-noise ratio.
Propagation: Wireless signals propagate through the air via various mechanisms, including
reflection, diffraction, scattering, and refraction. The propagation characteristics of wireless
signals depend on factors such as frequency, terrain, weather conditions, and obstacles in the
environment. Understanding propagation phenomena is crucial for designing reliable wireless
communication systems and optimizing signal coverage.
Multiplexing: Multiplexing techniques enable multiple users to share the available bandwidth
of a wireless channel efficiently. Frequency Division Multiplexing (FDM), Time Division
Multiplexing (TDM), and Code Division Multiplexing (CDM) are common multiplexing
techniques used in wireless communication systems. By dividing the available spectrum or
time slots among multiple users, multiplexing enables simultaneous transmission and
reception of data, thereby increasing network capacity.
Channel Coding and Error Control: Wireless channels are susceptible to noise, interference,
and fading, which can degrade signal quality and cause transmission errors. Channel coding
techniques such as Forward Error Correction (FEC) and Automatic Repeat reQuest (ARQ) are
employed to detect and correct errors introduced during transmission. Error control
mechanisms enhance the reliability and robustness of wireless communication systems,
ensuring accurate delivery of data across noisy channels.
Wireless Networking Protocols: Wireless communication protocols define the rules and
standards for data exchange between wireless devices and networks. Common wireless
networking protocols include Wi-Fi (IEEE 802.11), Bluetooth, Zigbee, LTE (Long-Term
Evolution), and 5G. Each protocol has specific characteristics, such as data rate, range, power
consumption, and network topology, tailored to different applications and use cases.
115
Security and Privacy: Ensuring the security and privacy of wireless communication is
paramount to protect sensitive information and prevent unauthorized access. Encryption
techniques, authentication mechanisms, and secure protocols such as WPA2 (Wi-Fi Protected
Access 2) and HTTPS (Hypertext Transfer Protocol Secure) safeguard wireless transmissions
against eavesdropping, tampering, and unauthorized access.
Understanding these fundamental concepts of wireless communication lays the groundwork
for designing, implementing, and optimizing wireless systems and networks. As wireless
technology continues to evolve and expand into new domains such as IoT, smart cities, and 5G
networks, a solid grasp of these concepts becomes increasingly essential for engineers,
researchers, and practitioners in the field of wireless communication.

1.2 Components of a cellular mobile network


 Mobile station (MS)
 Base station (BS)
 Mobile switching center (MSC)
 Base station controller (BSC)
 Public switched telephone network (PSTN)

Mobile station (MS)


MSs are usually a mobile phone. Each mobile phone contains a transceiver (transmitter and
receiver), an antenna, and control circuitry. Antenna converts the transmitted RF signal into an
EM wave and the received EM waves into an RF signal. The same antenna is used for both
transmission and reception, so there is a duplexer switch to multiplex the same antenna.
Base station (BS)
One of the important components in the cellular network is the BS. BS provides direct
communication with mobile phones and it defines the cell. When cells are grouped together, a
cluster is formed. Within a cluster, no channels are reused.
Mobile switching center (MSC):
The MSC is the control center for the cellular system. The MSC is also known as mobile
telephone switching office (MTSO). It coordinates the actions of the BSs providing overall
control and acts as a switch and connects into the PSTN.
Base station controller (BSC)
A number of BSs are connected to a BSC as shown in Figure 1.8. An important function of
BSC is that it manages the “handoff” from one BS to another as a subscriber moves from

116
cellto-cell. The BSC contains logic to control each of the BSs. Also, a group of BSCs are in
turn connected to a MSC via microwave link or telephone lines.

117
Unit 2: Computing trends and mobile computing
Learning objectives of the unit
At the end of this unit trainees are expected to:
 Be able to understand the basics of wireless communication.
 Be able to understand cellular mobile communication.
 Be able to understand computing trends.
 Be able to learn different mobile generations (1G,..5G).
 Be able to learn about electromagnetic spectrum.
2.1 Introduction
Mobile computing Mobile Computing is a technology that allows transmission of data, voice
and video via a computer or any other wireless enabled device without having to be connected
to a fixed physical link. Mobile Computing is a technology that allows transmission of data,
voice and video via a computer or any other wireless enabled device without having to be
connected to a fixed physical link. The main concept involves –
 Mobile communication
 Mobile hardware
 Mobile software

2.2 Mobile communication


The mobile communication in this case, refers to the infrastructure put in place to ensure that
seamless and reliable communication goes on. These would include devices such as protocols,
services, bandwidth, and portals necessary to facilitate and support the stated services.
Mobile Hardware
Mobile hardware includes mobile devices or device components that receive or access the
service of mobility. They would range from portable laptops, smartphones; tablet Pc's,
Personal Digital Assistants. These devices will have a receptor medium that is capable of
sending and receiving signals. These devices are configured to operate in full- duplex,
whereby they are capable of sending and receiving signals at the same time.
Mobile software
Mobile software is the actual program that runs on the mobile hardware. It deals with the
characteristics and requirements of mobile applications. This is the engine of the mobile
device.
In other terms, it is the operating system of the appliance. It's the essential component that
operates the mobile device.

118
2.3 Trends in Computing
There are five prominent generations in the history of computing. Each generation has
witnessed several technological advances.
First Generation (1940-1956) The examples of first generation computers are – these
computers use centralized computing.
• ENIAC
• UNIVACTBM 701
Second Generation (1956-1963)
Several advancements in the first-gen computers led to the development of second generation
computers. Following are various changes in features and components of second generation
computers:
It had features like −
• Batch operating system
• Faster and smaller in size
• Reliable and energy efficient than the previous generation
• Less costly than the previous generation
• But still they do centralized computing
Examples The examples of second generation computers are:
• Honeywell 400
• CDC 1604
• IBM 7030
Third Generation (1964-1971) The features of the third generation computers are
 Supports time-sharing OS
 Faster, smaller, more reliable and cheaper than the previous generations
 Easy to access
 Possible to do distributed computing
Fourth Generation (1972-2010)
Features
It supports features like −
• Multiprocessing & distributed OS
• Object-oriented high level programs supported
• Small & easy to use; hand-held computers have evolved
• No external cooling required & affordable
• This generation saw the development of networks and the internet

119
• Mobile computation become possible
Fifth Generation (2010-Present)
It supports features like −
• Powerful, cheap, reliable and easy to use.
• Portable and faster due to use of parallel processors and Super Large Scale Integrated
Circuits.
• Rapid software development is possible.
• Mobile computing and other computing such as ubiquitous computing become possible.

120
Unit 3: Producing Android based mobile application

Learning objectives of the unit


At the end of this unit trainees are expected to:
 Be able to understand Android versions
 Be able to discuss Android architercture
 Be able to list the most common android application components
 Be able to understand activity component of android
 Be able to create activity component of Android
 Be able to modify activity component of Android
3.1 Introduction
Android is an operating system that is based on a modified version of Linux. It was originally
developed by a startup of the same name, Android, Inc. In 2005, as part of its strategy to enter
the mobile space, Google purchased Android, Inc. and took over its development work (as
well as its development team). Google wanted the Android OS to be open and free, so most of
the
Android code was released under the open source Apache License. That means anyone who
wants to use Android can do so by downloading the full Android source code. Moreover,
vendors (typically hardware manufacturers) can add their own proprietary extensions to
Android and customize Android to differentiate their products from others.
The main advantage to adopting Android is that it offers a unified approach to application
development. Developers need only develop for Android in general, and their applications
should be able to run on numerous different devices, as long as the devices are powered using
Android.
Android devices come in all shapes and sizes including, but not limited to, the following
types of devices:
• Smartphones
• Tablets
• E-reader devices
• Internet TVs
• Automobiles
• Smartwatches

121
3.2 Architecture of android
Android is a mobile operating system based on the Linux kernel. It is an open-source operating
system for mobile devices that has been built upon other open-source projects. Java is one of
the two official languages for Android development; the other language is Kotlin. Kotlin
depends on JVM and can coexist with Java in the same application. Kotlin aims to solve
several limitations of Java.

Applications—At this top layer are the applications that ship with the Android device
(such as Phone, Contacts, Browser, and so on-System App), as well as applications that
you download and install from the Android Market-User App.
Java API framework—The framework exposes the various capabilities of the Android OS to
application developers so that they can make use of them in their applications. It includes
Activity, Content Providers,View System, Location, Telephony and related.
Native Libraries—These contain the code that provides the main features of an Android OS.
For example, the SQLite library provides database support so that an application can use it for
data storage. The WebKit library provides functionalities for web browsing, OpenGl ES,
OpenMax AL.
Android runtime—The Android runtime is located in the same layer with the libraries and
provides a set of core libraries that enable developers to write Android apps using the Java
programming language. The Android runtime also includes the Dalvik virtual machine, which
enables every Android application to run in its own process, with its own instance of the
Dalvik virtual machine. (Android applications are compiled into Dalvik executables). Dalvik

122
is a specialized virtual machine designed specifically for Android and optimized for battery-
powered mobile devices with limited memory and CPU power.
Hardware Abstraction Layer (HAL): HAL provides an interface for communication with
hardware and drivers. It provides ways for data passing from/to hardware devices
to the higher-level Java API framework. This way, you develop software based on the
hardware interface without the need to know the implementation of the hardware. The HAL
consists of multiple libraries; each library implements access for a specific type of hardware
components such as the camera or Bluetooth.
Linux kernel—this is the kernel on which Android is based. This layer contains all the low-
level device drivers (Audio, Display, WIFI …) for the various hardware components of an
Android device.

3.3 Android Application Components


Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact. There are following four
main components that can be used within an Android application –

Additional Components
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are

123
3.4 Android Service Component
Services in Android are a special component that facilitates an application to run in the
background in order to perform long-running operation tasks. The prime aim of a service is to
ensure that the application remains active in the background so that the user can operate
multiple applications at the same time.
A service can run continuously in the background even if the application is closed or the user
switches to another application. Further, application components can bind itself to service to
carry out inter-process communication (IPC). There is a major difference between android
services and threads; one must not be confused between the two. Thread is a feature provided
by the Operating system to allow the user to perform operations in the background. While
service is an android component that performs a long-running operation about which the user
might not be aware of as it does not have UI.

124
Types of Android Services

i. Foreground Services
Services that notify the user about its ongoing operations are termed as Foreground Services.

125
Users can interact with the service by the notifications provided about the ongoing task. Such
as in downloading a file, the user can keep track of the progress in downloading and can also
pause and resume the process.
ii. Background Services
Background services do not require any user intervention. These services do not notify the
user about ongoing background tasks and users also cannot access them. The process like
schedule syncing of data or storing of data fall under this service.
iii. Bound Services
This type of android service allows the components of the application like activity to bound
themselves with it. Bound services perform their task as long as any application component is
bound to it. More than one component is allowed to bind them with a service at a time. In
order to bind an application component with a service bindService() method is used.

3.5 Activity
An activity provides the window in which the app draws its UI. This window typically fills the
screen, but may be smaller than the screen and float on top of other windows. Generally, one
activity implements one screen in an app. For instance, one of an app’s activities may
implement a Preferences screen, while another activity implements a Select Photo screen.
The Activity class is designed to facilitate this paradigm. When one app invokes another, the
calling app invokes an activity in the other app, rather than the app as an atomic whole. In this
way, the activity serves as the entry point for an app's interaction with the user. You
implement an activity as a subclass of the Activity class.
How to Declare Activities
To declare an activity, open your manifest file and add an element as a child of the element.
For example
<manifest ... >
<application ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...
</manifest >
The Launcher Activity
Almost all Android applications will have several Activities. One of these Activities is the
Launcher Activity. Each application has only one Launcher Activity. It is equivalent to the

126
Java class with the main method that starts an application. The Launcher Activity is executed
when the user clicks the application icon. The programmer has to decide which Activity is the
Launcher Activity and declare it in the AndroidManifest.xml file. In the Manifest XML file,
you will have an element called application, where all Activities of your app are children of
this element, including the Launcher Activity. Inside the application element and the Activity
that you would like to declare as the Launcher Activity, you include a subelement called
intent-filter. The intent-filter element has two properties, action and category. For your activity
to be the Launcher Activity, its intent-filter action name must be MAIN, and its category must
be LAUNCHER.
Activity Life cycle
Android Activity Lifecycle is controlled by 7 methods of android.app. Activity class. The
android Activity is the subclass of ContextThemeWrapper class. Simply it can be said that an
activity is the single screen in android. It is like window or frame of Java. The 7 lifecycle
method of Activity describes how activity will behave at different states.

5.5 Android User Interface


The user interface is an important part of the app and is vital in its success. It is a large topic
that would be difficult to cover in-depth in one or two chapters—it could be a book on its own.
This chapter will only investigate some aspects of it, specifically aspects related to the user
interface component used in simple android applications. We will study Views, Layouts,
Widgets, and other components that enable the creation of nice-looking and user-friendly
interfaces for Android apps.
Android XML and UI Widgets

127
Before running a project it is important to know that the screen size, both the width and height
of a device, as well as the pixel density influence the design of your app. When designing your
app’s screen, it is helpful if you have information about the display characteristics of the
device you are designing for. Creating and testing your app with a proper AVD emulator and
the actual device is the best way to start your app design. However, to be certain about the
appropri-ateness of your application design, you need to be mindful of the dimensions and
density of the device you are designing for. Here are some of the scaling units that you need to
be aware of when specifying the UI for your app.
• px – screen pixels.
• in – inches based on the physical screen size.
• mm – millimeters based on the physical screen size.
• pt – 1/72 of an inch based on physical screen size.
• dp or dip – device-independent unit relative to a 160 dpi screen.
• sp – similar to dp but used for font sizes.
• dpi – dots per inch; the number of pixels within a physical area of the screen is
referred to as dpi.
5.5.2 Android XML
XML stands for Extensible Markup Language. XML is a markup language much like HTML
used to describe data. XML tags are not predefined in XML. We must define our own Tags.
Xml as itself is well readable both by human and machine. Also, it is scalable and simple to
develop. In Android we use xml for designing our UI layouts because xml is lightweight
language so it doesn’t make our layout heavy. The whole concept of Android User Interface is
defined using the hierarchy of View and ViewGroup objects. A ViewGroup is an invisible
container that organizes child views. These child views are other widgets which are used to
make the different parts of UI. One ViewGroup can have another ViewGroup as an child
element.
Views
View is an Android class that is an essential building block of Android’s user interface. It
occupies the rectangular area of your device and is in charge of drawing and handling user
interactions. In Java, we use the object to refer to almost everything. When developing
Android apps, however, we are dealing with UI components, and almost everything is a visual
object; hence, we can use View instead of using the object to refer to any UI component of an
app.

128
View allows you to create a layout or display an area of our app to put View subclasses and UI
components inside it. In Android, every UI element is a View, i.e., is a subclass of the View
class.
View Properties
Each View has multiple attributes or properties. Some of these properties need to be set when
defining View objects inside the layout. Examples of properties that you can set when defining
a View object include setting text, positions, margins, padding, dimensions, background
colors, text font size, style, etc. These properties can be set in the XML layout file or
programmatically in the code. The decision to set the properties using the XML layout files or
programmatically depends on whether you know the properties before runtime or not. If you
know the properties of your UI elements before runtime, one can use the XML layout file.
Otherwise, if your UI remains unknown until runtime, i.e., you want to set these properties
dynamically, use code to set them. Keep in mind that defining Views and their properties in
the XML layout could keep the code clean.
UI Widgets
A View class has several widget subclasses. These classes are grouped in a package called
Widgets. They are fundamental control elements of the graphical user inter-face of an app. It is
through these elements that the user can interact with the app. Examples of Widget elements
that are widely used in Android apps include
i. Button,
ii. Checkbox,
iii. RadioButton,
iv. ProgressBar,
v. RatingBar,
vi. ImageView,
vii. ListView,
viii. Switch, etc.
UI Layout
The basic building block for user interface is a View object that is created from the View class
and occupies a rectangular area on the screen. Views are the base class for UI components like
TextView, Button, EditText etc. The ViewGroup is a subclass of View.
One or more Views can be grouped together into a ViewGroup. A ViewGroup provides the
android layout in which we can order the appearance and sequence of views. A layout is an

129
invisible container that defines the visual structure for a user to interface with your app, such
as in an activity.
Android provides the following ViewGroups or layouts:
• ConstraintLayout
• LinearLayout (horizontal)
• LinearLayout (vertical)
• RelativeLayout
• TableLayout
• FrameLayout
• GridLayout
• ConstraintLayout
Both GridLayout and RelativeLayout are considered as legacy layouts, which means that their
use is not encouraged anymore. This is because Android has introduced a more powerful
layout, i.e., ConstraintLayout. . ConstraintLayout is a default Layout, i.e., when you create a
new Activity, the auto layout for the Activity will be ConstraintLayout.

3.6 Android Menus


Menu are an important part of the UI component which is used to provide some common
functionality around the application. With the help of menu, users can experience a smooth
and consistent experience throughout the application. Android Menu is a part of your user
interface and provides users with a list of available options from which they can choose. Based
on their selection, the proper functionality is performed.
Types of Menus we have three types of Menus available to define a set of options and actions
in our android applications. The Menus in android applications are the following:
i. Android Options Menu
Android Options Menu Android Options Menu is a primary collection of menu items in an
android application and is useful for actions that have a global impact on the searching
application. They are the primary menus of android. They can be used for settings, search,
delete item etc. The inflate( ) method of MenuInflater class can be used. To perform event
handling on menu items, you need to override onOptionsItemSelected() method of Activity
class. The options menu is usually present in the action bar. You can find several options listed
in the options menu through which you can make a selection.
ii. ii. Android Context Menu
Android Context Menu is a floating menu that only appears when the user clicks for a long
time on an element and is useful for elements that affect the selected content or context frame.

130
The contextual action mode displays action items that affect the selected content in a bar at the
top of the screen and allows the user to select multiple items.
iii. iii. Android Popup Menu
A popup menu displays a list of items in a vertical list that's anchored to the view that invoked
the menu. It's good for providing an overflow of actions that relate to specific content or to
provide options for a second part of a command. Actions in a popup menu should not directly
affect the corresponding content—that's what contextual actions are for. Rather, the popup
menu is for extended actions that relate to regions of content in your activity. Generally,
Popup Menu is a menu that appears over your view and covers your view. Below you can find
an example of the same.

Unit 4: Event handling methods, Intents and data handling with in


android app development
Learning objectives of the unit
At the end of this unit trainees are expected to:
 Understanding of Android's event handling mechanisms.
 develop expertise in asynchronous event handling techniques, such as using Handlers
 develop a clear understanding of the concept of Intents in Android,

Event handling comes with Event and Handling. The Events are the actions that take place
whenever the user interacts with the UI components. Suppose, for instance, a user pressed a
button, and your device flashlight got turned on. Did you ever think about how to see effects
when different actions are applied to the UI we have discussed earlier? The answer is simply
through event handling. Interactions with the user interface generate some actions. These
actions are nothing but an event.
In Android, when an activity is performed by the user it requires further action from the
framework. The system handles these events with its listeners and handlers. They're special
methods defined in Android View classes. For example, an activity loads and has a button.
When the user clicks it, it will take an action like displaying some text or moving to another
view. This response to the event is managed by the event listeners and event handlers. This is
one way to intercept events from the user interaction and there's more than one way to
intercept events from the user.
In general, Events are a useful way to collect data about a user's interaction with interactive
components of Applications. Like button presses or screen touch etc. The Android framework

131
maintains an event queue as first-in, first-out (FIFO) basis. You can capture these events in
your program and take appropriate action as per requirements.
To handle events in android application, one should know the following three concepts:
i. Event listeners
ii. Event handlers
Event listener’s registration
4.1 Event listeners
Below are some of the essential An event listener is an interface in the View class that
contains a single callback method. These methods will be called by the Android framework
when the View to which the listener has been registered is triggered by user interaction with
the item in the UI.
An event listener works as an interface in the View class. These methods are called by the
Android framework when the View, with which an event listener is linked, is called by the
user. event listeners:
OnClickListener: This listener is used to handle the click events on UI elements like buttons,
images, or views. It allows you to perform specific actions when a user clicks on the
associated UI element.
OnLongClickListener: This listener is similar to OnClickListener but is used to handle long-
click events. You can use this listener to perform actions when a user long-presses on a UI
element.
OnCheckedChangeListener: This listener is used with CheckBox and RadioButton UI
elements. It allows you to perform actions when the checked state of these elements changes.
You can use it to implement logic based on whether a checkbox or radio button is checked or
unchecked.
TextChangedListener: This listener is used with EditText UI elements. It enables you
respond to changes in the text entered by the user. You can use it to perform validation, update
UI elements dynamically, or trigger actions based on the user's input.
OnItemSelectedListener: This listener is used with Spinner UI elements. It allows you to
respond to the selection of an item from a dropdown list. You can use it to perform actions
based on the user's selection, such as updating other UI elements or retrieving data related to
the selected item.
OnTouchListener: This versatile listener responds to touch events on UI elements. You can
use it to handle touch gestures, such as tapping, swiping, or dragging, and implement custom
interactions based on touch input.

132
OnFocusChangeListener: This listener is triggered when a UI element gains or loses focus.
It's helpful for managing the focus behavior of various elements and performing actions based
on focus changes.
OnSeekBarChangeListener: Designed for SeekBar UI elements, this listener responds to
changes in the progress of a SeekBar (e.g., when a user slides the thumb). You can use it to
react to changes in the SeekBar's value and update other UI elements accordingly.
GestureDetector: While not a single listener, the GestureDetector class allows you to detect
various complex touch gestures, such as double-tap, pinch-to-zoom, and fling, among others.
You can use this class to handle more advanced touch interactions in your app.
ViewTreeObserver. OnGlobalLayoutListener: This listener helps you observe changes in the
layout of a view hierarchy. It's useful when you need to react to changes in the size or position
of UI elements and make adjustments accordingly.

4.2 Event handlers

Event handles are the actual methods that have the action that is to be taken. After an event has
happened and event listeners are registered, event listeners call Event Handler. These are
useful to define some callback methods. They are responsible for handling events and
performing specific actions based on their events. The method of the Event handles are the
methods that have the specified action that is required to be performed. Usually, these methods
are present in the event listeners call-back method. It is used to define the task that has to be
completed. Event listeners, when called trigger event handlers.
When an event happens and registered an event listener for the event, the event listener calls
the Event Handlers, which is the method that actually handles the event. Some of the
commonly used event handlers are as follows
OnClick ( ) : Handles click events on UI elements. It allows you to perform actions when a
user taps on the associated UI element.
OnLongClick ( ) : Handles long-click events on UI elements. You can use it to trigger actions
when a user long-presses on a UI element.
OnCheckedChange ( ) : Handles changes in the checked state of CheckBox and RadioButton
UI elements. It allows you to perform actions based on whether a checkbox or radio button is
checked or unchecked.
TextWatcher: Handles changes in the text entered by the user in EditText UI elements. You
can use it to respond to text changes, perform validation, or update UI elements dynamically.

133
OnItemSelected ( ) : Handles the selection of an item from a Spinner UI element. It enables
you to respond to item selections and perform actions based on the selected item.
OnTouch ( ): Handles various touch events on UI elements. It allows you to implement
customtouch gestures or interactions, such as tapping, swiping, or dragging.
OnFocusChange ( ): Handles focus changes of UI elements. It triggers actions when a UI
element gains or loses focus.
OnSeekBarChange ( ): Handles changes in the progress of a SeekBar UI element. It responds
to the user sliding the thumb and enables you to update other UI elements based on the
SeekBar's value.
GestureDetector: This class provides multiple methods to handle touch events and gestures,
such as double-tap, pinch-to-zoom, or fling. It offers more advanced touch interaction
capabilities.
ViewPager.OnPageChange ( ): Handles changes in the pages of a ViewPager UI element. It
allows you to respond to page changes and perform actions based on the current page.
DatePickerDialog.OnDateSet( ): Handles date selections in a DatePickerDialog. It enables
you to respond to the selected date and perform actions based on it.
TimePickerDialog.OnTimeSet ( ): Handles time selections in a TimePickerDialog. It allows
you to respond to the selected time and perform actions based on it.
AdapterView.OnItemClick ( ): Handles item clicks in AdapterView-based UI elements like
ListView or GridView. It triggers actions when a user clicks on an item in the AdapterView.
CompoundButton.OnCheckedChange ( ): Handles changes in the checked state of
compound UI elements like Switch or ToggleButton. It allows you to perform actions based
on the state change.
SensorEvent ( ): Handles sensor data from various sensors on the device, such as
accelerometer, gyroscope, or proximity sensor. It enables you to respond to sensor events and
perform actions based on sensor data.

4.3 Event Listener Registration


Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. It is a process in
which an Event handler is registered with an Event listener. In this way the event handler is
called when the Event listener is triggered.
Whenever the event occurs, then the handler should perform the task. Therefore, both need to
be synced properly. Though there are several tricky ways to register your event listener for any

134
event, commonly there are three ways of event listener registration, out of which one can use
any of them based on the situation.
The three ways of event listener registration are the following:
I. First, you can directly register the event listeners using the activity’s XML file (Event
Handling using XML Layout file).
II. By registering the listener inside the activity class. ( Event Handling Using an anonymous
inner class).
III. The last method is register the event listener by writing it in an Activity class that extends
properties from the Listener Class. ( Event handling by implementing listener interfaces )

4.4 Event Handling using XML Layout file


In Android, event handling can be done using XML layout files. This involves specifying the
event handler method directly in the XML file. Using this method of event listener registration
could give several advantages such as Readability and Organization of your code since Event
handling code specified in XML layouts provides a clear and organized separation between the
UI elements and their associated event handlers. Limited Flexibility and Limited Error
Handling are some of the disadvantage of this method since XML layout file event handling is
best suited for simple and straightforward event interactions. To have complex event handling
requirements or to perform dynamic operations based on the events, handling events
programmatically in the code may offer more flexibility and control.
Event Handling Using an anonymous inner class
In Android, event handling can also be accomplished using an anonymous inner class. This
approach allows you to define event handlers inline without the need for separate named
methods or separate event listener classes. Using an anonymous inner class for event handling
in Android has its advantages and disadvantages. Some of the Advantages are:
• Concise and Inline Implementation: Anonymous inner classes allow you to define event
handlers inline within your code, making it more concise and readable. You don't need to
create separate classes or methods for each event handler, providing a compact
implementation.
• Simplified Code Structure: Using anonymous inner classes reduces the need to create
separate classes or methods solely for event handling purposes. This simplifies the code
structure, especially when dealing with simpler event interactions or when the event handling
logic is straightforward.
• Easy Access to Outer Scope: Anonymous inner classes have access to variables and methods
of the enclosing scope. This allows you to directly reference and modify variables or call
135
methods from within the event handler, making it easier to work with and update the UI or
other relevant components.
• Flexibility in Event Handling Logic: Anonymous inner classes offer flexibility by allowing
you to define and customize the event handling logic directly. You can easily modify the
behavior of the event handler for different UI elements or event types without creating
additional classes.

4.5 Event handling implementation listener interfaces


Event handling can also be achieved by implementing listener interfaces provided by the
Android framework. This approach allows you to handle events by creating separate classes
that implement the corresponding listener interface.
Using a listener interface implementation for event handling in Android has also its own
advantages and disadvantages.
Some of the Advantages are:
Reusability: Implementing listener interfaces allows you to create separate classes that can be
reused across multiple UI elements or event types. This promotes code reusability, reducng
duplication and making it easier to maintain and update the event handling logic.
Separation of Concerns: Listener interfaces separate the event handling logic from the UI
code, enhancing code organization and making your codebase more maintainable. It promotes
a clear separation of concerns, where the UI elements are responsible for displaying
information, while the listener classes handle the corresponding events.
Flexibility: Implementing listener interfaces gives you flexibility in handling events in
customized ways. You have complete control over the implementation details within the
listener class, allowing you to perform specific actions based on the event, update UI elements,
or perform complex operations as needed.
Polymorphism and Inheritance: By implementing listener interfaces, you can leverage the
concepts of polymorphism and inheritance. You can create multiple classes that implement the
same listener interface and override the event handling methods to provide specific behavior
for each class. This flexibility enables you to handle events differently based on the context or
specific requirements.
Separated Testability: With listener interface implementation, event handling code can be
easily tested in isolation. You can create separate test cases for your listener classes and verify
the functionality independently, ensuring comprehensive testing coverage.

136
Self-check questions
Part I: Multiple choices
Instruction: Choose the best response based on your understanding of the topic.
1. In Android, what method is typically used to create options menu items for an
activity?
A. onCreateOptionsMenu()
B. onOptionsItemSelected()
C. onCreateOptions()
D. onOptionsSelected()
2. What is the primary purpose of a context menu in Android?
A. To display options related to the overall application
B. To provide options based on the current context (such as a long press on a UI
C. element)
D. To manage background tasks in an activity
E. To handle navigation between different activities
3. Which method is used to handle the selection of an item from the options menu in
Android?
A. onItemSelected()
B. handleOptionsMenuSelection()
C. onOptionsItemSelected()
D. menuItemSelected()
4. In Android, which type of progress bar is best suited for indicating indeterminate
progress, where the duration of the task is unknown?
A. Horizontal ProgressBar
B. Circular ProgressBar
C. Determinate ProgressBar
D. SeekBar
5. In Android, which method is commonly used to prepare and start a MediaPlayer
instance for playing audio or video?
A. initializePlayer()
B. startPlayer()
C. prepareAsync()
D. playMedia()

137
6. What is the primary purpose of the setOnClickListener method on a button in
Android?
A. To define the appearance of the button
B. To handle click events when the button is pressed
C. To set the text displayed on the button
D. To enable/disable the button
7. 2. Which interface is commonly used to handle touch events in Android?
A. OnClickListener
B. OnTouchListener
C. OnLongClickListener
D. OnDragListener
8. What is the purpose of the onItemClick method in Android event registration?
A. To handle the event when an item in a ListView is clicked
B. To handle the event when a long press is performed on an item in a ListView
C. To handle the event when the list view is scrolled
D. To handle the event when an item in a RecyclerView is clicked
9. What is the purpose of using the setOnClickListener method when registering event
listeners for buttons in Android?
A. To handle button presses and perform actions accordingly
B. To define the appearance of the button
C. To enable/disable the button
D. To set the text displayed on the button
10. 6. Which method is commonly used to register an event listener for a checkbox in
Android?
A. setOnCheckedChangeListener
B. setOnTouchListener
C. setOnClickListener
D. setOnLongClickListene

138
REFERENCES:
[1]. Abdul-RahmanMawlood-Yunis, Android For Java Programmers, Wilfrid
Laurier University Waterloo, ON, Canada,2nd edutuib 2022.
[2]. Afif Osseiran, Jose F. Monserrat etc, 5G Mobile and Wireless Communications
Technology,2nd edition, Cambridge University Press, 2016.
[3]. Behrouz A. Forouzan, Data Communications and Networking, 4th edition, New Delhi:
Tata McGrawHill Publishing Company Ltd., 2006.
[4]. Gottapu Sasibhushana Rao, Mobile Cellular Communication, 1st edition, Dorling
Kindersley (India) Pvt. Ltd., 20

139
140

You might also like