You are on page 1of 516

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/341219052

Fundamentals of Data Structures

Presentation · May 2020


DOI: 10.13140/RG.2.2.15098.72644

CITATIONS READS

0 4,782

1 author:

Hitesh Mohapatra
K L University
97 PUBLICATIONS 588 CITATIONS

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Intrusion Detection System View project

Wireless Sensor Network View project

All content following this page was uploaded by Hitesh Mohapatra on 07 May 2020.

The user has requested enhancement of the downloaded file.


©

DATA STRUCTURE
HITESH MOHAPATRA
Programming Structure
and Methodology
Agenda

Introduction to Programming
1
Structure and Methodology 2hrs

2 Computation Fundamentals 2hrs


3 Decision Control Structure 2hrs
Module 1: Introduction to Programming
Structure and Methodology
Module Overview

▪ When we decide to choose software development or programming as our


career, we often come with a pre-conceived notion about it.
▪ This notion can be defined in one line as “Programming equals Coding”.
▪ However, this notion is wrong and highly underestimates the job of a
programmer.
▪ In this module, you will understand what programming actually is and how
you can gain an analytical approach to programming.
▪ The modules talks about the disadvantages of following the programming
equals coding equation.
▪ It also presents and explain the right methodology to programming, which
is “problem solving”.
▪ It describes how critical thinking and problem solving can help you create
good computer programs and excel in your field, by detaching
programming language syntax from programming.
▪ It advocates and explain the use of algorithms, pseudocode, and
flowcharts for designing programs, before coding them.
What is
programming
according to
you?

What is your
job as a
programmer
going to be?

Are you just


going to write
code? Or, will
you do more
than that?
Objectives

▪ At the end of this module, you will be able to:


– Understand the disadvantages of straightaway writing code for a problem
– Understand how problem solving and critical thinking can be used in
programming
– Define algorithms
– Use algorithms for designing programs
– Identify the rules for using pseudocode
– Identify the rules for drawing flowcharts
What is Programming?

▪ Programming is the skill of understanding a task and following a


methodology to write a computer program to automate it.
▪ A computer program is a set of instructions written in a programming
language, which the processor can decipher to perform the specific task.
▪ As a programmer, your aim is to write good programs.
Characteristics of a Good Program

Modularity

Adherence to
Minimal
standard
complexity
techniques

Loose
Leanness
coupling

Good
Programs

High fan-in,
Ease of
low/medium
maintenance
fan-out

Portability Extensibility

Reusability
Characteristics of a Good Program (Contd.)

▪ A good program has the following characteristics:


– Modularity:
• A program should be divided into modules that contain related set of instructions.
• For example, when you are writing a program to automate banking tasks, you can
divide it into modules such as module for creation of bank account, module for
closure of bank account, module for deposits, and module for withdrawals. These
modules can further have subordinate modules, such as module for input/output or
module for saving data to a database.
– Minimal complexity:
• The complexity of a program is defined by how clear and simple the logic of the
program is, and the time and resources that the program requires to execute.
– Loose coupling:
• Loose coupling means that a change in one module does not disrupt the working of
another module or require you to make changes in it.
Characteristics of a Good Program (Contd.)

– Ease of maintenance:
• A program should be easy to change at any stage by the same programmer or any
other programmer.
• Minimal complexity and loose coupling facilitate ease of maintenance.
– Extensibility:
• A program is extensible if new features can be added to it without significant
overhaul of the existing program.
– Reusability:
• A program can have functions or modules that can be reused to achieve a task in
any other program without significant changes.
– Portability:
• A program that can be executed on different execution platforms with minimal or
no changes, is portable.
• The behavior of a portable program does not change when its underlying execution
environment changes.
Characteristics of a Good Program(Contd.)

– High fan-in, low/medium fan-out:


• Fan-in of a module refers to the number of its subordinate modules.
• Fan-out of a module refers to the number of modules of which it is a subordinate.
• Fan-out of a module should not be more than seven because it tightens coupling,
and may affect portability and ease of maintenance.
• High fan-in improves ease of maintenance and portability and reduces unnecessary
redundancy and complexity in the code.
– Leanness:
• A lean program is the one that is conceptualized with the aim of minimizing defects,
maximizing quality, and expediting delivery for the client while optimizing the effort
and time spent on it.
– Adherence to standard techniques:
• A program should use established coding standards ad techniques if they fit the
requirement.
• A program should not try to reinvent the wheel for established standards and
techniques. This helps to minimize defects and save effort and time. It also
promotes leanness.
Activity 1: Let’s Become Critics!

▪ Let’s look at a program written by some fresh recruits.


▪ Analyze the program and identify which characteristics of a good program
are missing from the program.
▪ Now, analyze how you can modify the program to incorporate the
characteristic and discuss.
Solution to Activity1
Solution to Activity I: Let’s Become Critics!

Too much complexity

Lack of extensibility

Lack of modularity

Tight coupling
Programming Coding

▪ Programming is not just about writing code.


▪ When you straightaway start coding for a given problem, you:
– May write code that does not have some or most of the good characteristics
of a program
• For example, you may have 10 if statements in a code, which can be reduced to 4, if
you use the if-else-if structure thoughtfully. This indicates unnecessary complexity.
- However, because you did not think about all the options before you started coding, you
wrote a separate if statement for every option.
• Another example is when you write a program to create bank accounts of various
types and fix the number of types to 5.
- In the future, if another type of bank account is added, you will have to check your
program and modify it to incorporate this additional bank account type. This indicates
that your program was not extensible.
– May try to modify existing code from another program to write a new
program
• For example, you may start coding a program for calculating Arithmetic
Progressions based on a Fibonacci Series program that you have written.
- This increases chances of errors and does not necessarily give you the best way to solve
the problem.
Programming Coding

– May use a trial and error approach to programming and waste time
• For example, you may start writing a program for a search engine and may reach a
dead-end where you are unable to return the closest matches for a user’s
keywords.
- In this case, you would again go back and start coding from beginning to identify what
went wrong and where.
• Another example is where you assign an integer type to a variable and towards the
end of the program, you realize that it may also have a floating value.
- However, because you did not think about all possible cases in the problem area, you
just assumed that the variable can be an integer. Now, you have to go back, check, and
change the usage of the variable in your entire program.
– May limit your program’s capabilities and performance because you did not
think hard about the best way to write the program; you just started writing it!

When you start coding straightaway, you are trying to reach a


destination without knowing the directions. Imagine, how much
easier it is when you know the directions to your destination!
The Right Programming Methodology

▪ Programming is a means to solve a problem faced by your client and


enable a processor (computer or any other embedded device with a
processor) to perform a desired task.
▪ Your client’s requirement is the ‘problem’, and your program will be it’s
solution.
▪ To traverse from the problem to the solution, you need to follow a
methodology and not straightaway start coding.
▪ The right programming methodology, requires you to:
– Adopt an analytical problem solving approach
– Critically think about the given problem
What is Problem Solving?

▪ Problem solving refers to a systematic approach to defining the problem


(situations or tasks that presents uncertainties or difficulties and need to
be handled to overcome or reduce these uncertainties or difficulties) and
creating a vast number of possible solutions without judging these
solutions.
▪ Selecting the optimum solution from among the various options and
implementing it helps you solve the problem.
▪ While you use the problem solving approach, you need to apply critical
thinking at each stage.
▪ Critical thinking is defined as “Purposeful mental activity that helps
formulate or solve problems, make decisions, or fulfill a desire to
understand.”
Problem Solving and Programming

Identify and define Analyze the Identify possible Evaluate solutions


the problem problem solutions

•What does the •How is it •Is there only 1 •Will this give me
client want to currently done? way to do this? the best
automate? •What •What are the performance?
information do I other ways to do •Will this be
have? this? extensible,
•What do I need portable,
as output? reusable…?

Implement the Develop an action Select the best


solution plan solution

•Start •Document the •Which is the


programming by designed solution having
referring to the solution. all the good
Good designed characteristics?
Program! solution.
Activity 2 - Let’s Do it to Believe it!

Team A Team B Others


Write a program for Explain the logic of Note answers to
the game of tic-tac- tic-tac-toe game by questions in the
toe. using words and/or sheets given to you.
diagrammatic
representations.
Use any programming You do not have to Keep an eye on both
language that you write a program. the teams to write
know. Follow the problem your answers.
solving approach.
You have 10 minutes! You also have 10 -
minutes!
Solution to Activity 2
Solution to Activity 2 - Let’s Do it to Believe it!

Team A Team B
Started writing the code within the Took time to think before starting
first 1-2 minutes? to write the description?
Consider all or most of the Consider all or most of the
options/cases for the given options/cases for the given
problem before writing the code? problem before describing them?
Went back and made changes to Made lesser number of changes to
their code often? the descriptions
Spent more effort because they Spent lesser effort in making
were reworking on code every time changes because they were
they went wrong? working with language?
Were working more individually Were thinking together as a team
rather than as a team? and then describing?
Solution to Activity 2 - Let’s Do it to Believe it!
(Contd.)

Pseudocode

Algorithms Flowcharts

Problem
Solving in
Programming
What is an Algorithm?

▪ An algorithm:
– Is a finite set of clearly defined steps that describe “how” you want to solve a
problem
– Has a definite set of inputs and a predictable and known set of result (solution
to the problem)
– Converts input into output by following the defined set of steps
▪ A computer program is itself an algorithm. However, because it is written
according to the syntax of a specific programming language, you tend to
focus on syntactic issues and lose the focus on the algorithm itself.
▪ The problem solving approach to programming requires you to design an
algorithm that adheres to the “good characteristics of a program” and then
write code from the algorithm.
▪ You can write an algorithm in simple language, use pseudocode, or use
flowcharts. For example, if you write down the step to tell your friend the
way to your home from office, you would be writing an algorithm!
Algorithms Simplified

▪ The word ‘algorithm’ may sound intimidating to most of us, but they are
actually very much related to the way in which we think in our everyday
lives.
▪ Suppose, your friends asks you the directions from our current location to
your home. What would you do? Your friend has a problem and is asking
for a solution.

OK. How to do
plan to My own vehicle.
commute?

OK. So exit from


gate 2 of the
parking and turn
left.

Drive 5 kms and turn


right from the traffic
light…
Algorithms Simplified (Contd.)

▪ The thought process, while you explain the directions to your friend, is
what constitutes an algorithm.
▪ Now, imagine any software that gives the direction from one place to
another. How does it work – it asks you for the source and destination
(which you knew) and the mode of travel (which you asked your friend
for). Based on these inputs, it gives you the directions.
▪ So, writing algorithms is all about choosing the right thought process for a
solution to a problem.
Example of an Algorithm

▪ Identify and define the problem Algorithm to find the largest number
▪ Analyze the problem among 5 numbers entered by a user.
▪ Identify possible solutions
▪ Evaluate solutions To find the largest number in an unsorted list of
integers.
▪ Select the best solution
1. Assume that the first number in the list is the
▪ Develop an action plan largest.
▪ Implement the solution 1I. Go through all other numbers in the list and
My user can compare them to the first number, executing
input a list of
numbers and step III every time you compare.
my algorithm
has to find the III. If the number being compared is greater than
largest.
the first number, make it the first number in the
list.
This list of IV. When all numbers have been compared, the
numbers can be in
any order. It will first number will be the largest.
have only positive
numbers.
Activity 3 - ‘Algo’ Writing

▪ Since all of us here today are from engineering and science backgrounds,
we would know what exponents are.
▪ In school and college, you would have been given the task of writing a
program to calculate the value of a number raised to the power of a
positive exponent.
▪ Now, let’s see if our problem solving approach can help us design an
algorithm to write a computer program for this easily.
▪ Start thinking critically:
– What is your input?
– What possible values can it have?
– What values should not be allowed?
– What is the desired output?
– What does “raised to power mean”?
– How can you calculate raised to power by using a
mathematical operator?
Solution to Activity3
Solution to Activity 3 - Algo Writing

▪ If you thought critically about the answers to the questions listed in the
last slide and more such cases, you can come up with an algorithm such as
the following:
– To calculate the value of a positive number raised to the power of another
positive number.
– I. Input base and exponent from the user.
– II. If the exponent is < 1, tell the user that the input is invalid.
– III. If base entered is 1, display the result as 1 and exit.
– IV. If the exponent entered is 1, display the base number as the answer and
What is your input?
exit.
Any positive numbers. The
– V. Set result equal to base. exponent can be 1 or more.
If baseinisresult.
1, thenDecrementBase can be one or more.
the answer
– VI. Multiply result by base and store the exponent by 1.
will be 1 irrespective of the
– VII. If exponent is > 1, perform step IV again. exponent.
If exponent is 1, then the
If base and exponent are not 1, then they will
– VIII. Display the result and exit.
answer will be the value of
be greater than 1 and need to be calculated by
the base.
multiplying base by itself “exponent” number
of times. Result is used to store the product in
between.
What is Pseudocode?

▪ If a problem is simple, writing an algorithm in natural language may be


acceptable. However, in the world of computers, most problems are not
simple to solve.
▪ Therefore, you need a more standardized, compact method for writing
algorithms, rather than verbose sentences that may be interpreted
differently by different people.
▪ Pseudocode uses natural language and structural conventions to write
algorithms. It is a mix of informal syntax (not specific to any programming
language) and brief description in natural language.
▪ It is different from a program because it omits or condenses various
programmatic details such as:
– It omits variable declarations
– It condenses statements that would comprise a block of code into a single
statement in natural language
– It does not use any programming language specific syntax
– It cannot be complied or run
Pseudocode Conventions

▪ There are no standard conventions for pseudocode as it an informal


technique and the style of writing pseudocode varies among programmers.
▪ Some general rules/keywords that you can use to write pseudocode are:
– Use variable names (without declaring them). Use arrays syntax
<arrayname[number of elements] to represent lists.
– Use keywords INPUT, READ, or GET to input data from a data source or an
I/O device such as a keyboard
– Use keywords DISPLAY, PRINT, or SHOW to output values to a data storage
or an I/O device such as the monitor or printer
– Use verbs such as IS EQUAL TO, INITIALIZE, SET, INCREMENT, and
DECREMENT
– Use decision making statements such as IF-THEN-ELSE-ENDIF to check for
conditions/cases.
– Use loops such as WHILE-END, and DO-WHILE-END or REPEAT UNTIL to
perform an operation repetitively.
Pseudocode Conventions

– Use arithmetic operators (+, -, *, /), relational operators (==, <=, >=, <>, >, <),
assignment operator (=), and logical operators (OR, NOT, AND) to form
conditions.
– Functions can be used by giving them a name preceded by FUNCTION: . They
can be called as CALL <function name>. Return values by using RETURN. Use
verbs such as WHEN to add a condition to RETURN.
– Use proper indentation and give the pseudocode a name.
▪ The degree to which you use natural language in your pseudocode is
optional. However, limiting the use of verbose natural language is
encouraged to avoid ambiguity.
▪ Let’s see some examples now.
Example of a Pseudocode

▪ The following is a pseudocode for finding the largest number in an


unsorted list.

LargestNum (A)

INPUT numat[5]
INITIALIZE i to 2
REPEAT UNTIL i<=5
IF numat[i] > numat[1]
SET numat[i] =numat[1]
ENDIF
DISPLAY numat[1]
EXIT
Example of a Pseudocode (Contd.)

▪ The following is another example of a pseudocode for determining the


grade of a student based on his or her marks.

CalcGrade (marks)
CALL GETMARKS
IF marks > 80
SET grade = ‘A’
ELSE
IF marks >45
SET grade = ‘B’
ELSE
SET grade =‘C’
ENDIF
ENDIF
DISPLAY grade

FUNCTION: GETMARKS
INPUT marks
RETURN marks
Activity 4: Pseudocoding!

▪ Suppose you again have to think and design an algorithm to calculate the
value of a number raised to the power of a positive exponent.
▪ But, this time, instead of complete language, you need to use pseudocode
to write your algorithm.
▪ Start thinking critically by using the same questions again:
– What is your input?
– What possible values can it have?
– What values should not be allowed?
– What is the desired output?
– What does “raised to power mean”?
– How can you calculate raised to power by using a
mathematical operator?
Solution to Activity 4
Solution to Activity 4 - Pseudocoding!
CalcPower
INPUT base, exponent
IF exponent < 1
DISPLAY “Invalid Input.”
EXIT
ENDIF
IF base is equal to1
DISPLAY 1
ELSE
IF exponent is equal to 1
DISPLAY base
ELSE
INITIALIZE result=base
DO
result = result* base
DECREMENT exponent by 1
UNTIL exponent > 1
END-DO
DISPLAY result
ENDIF
ENDIF
What is a Flowchart?

▪ Sometimes it is easier to understand a procedure by looking at a diagram,


especially when it is complex.
▪ To represent your algorithm diagrammatically, you can use flowcharts.
▪ Flowcharts are diagrams consisting of boxes of different shapes and arrows
connecting the boxes. The boxes show a step in the algorithm and the
arrows indicate the flow from one step to another.
▪ You can use flowcharts for a part or whole of your algorithm, in addition
to pseudocode or individually.
▪ Flowcharts help to look at the flow visually and critically think about it,
refine it, and make a good design for your program.
▪ To create flowcharts, you can use some commonly followed conventions.
However, as in the case of pseudocode, there is no industry-wide
standard and there may be differences in flowcharts created by different
programmers.
Flowchart Conventions

▪ The following table shows some basic conventions followed to create


flowcharts.
Symbol Purpose

Start and End with the words


START or END written inside them.
Processing step with the
processing step written inside
Input/output of data with the
variable name written in it
Condition step with the condition
written inside
Flow between any two other
symbols. Also used to show
looping.
Example of a Flowchart

▪ The following is a flowchart for out algorithm for finding the largest
number in an unsorted list of 5 numbers.
START

READ
NUMAT[5]

SETi=2

Is
SET numat[i] numat[
Yes i] > No DISPLAY
=numat[1] STOP
numat[ NUMAT[1]
1]

INCREMENT i
Example of a Flowchart (Contd.)

▪ The following is another example of a flowchart for determining the grade


of a student based on his or her marks.
START

READ
marks

Is Is
Yes No No
SET grade=‘A’ marks marks SET grade=‘C’
> 80 > 45

Yes

SET grade=‘B’

DISPLAY
STOP
grade
Activity 5 - Flowchart Time

▪ We have created an algorithm and pseudocode for calculating the value of


a number raised to the power of a positive exponent.
▪ Now, let’s create a flowchart for the same problem.
Solution to Activity 5
Solution to Activity 5 - Flowchart Time

▪ Let’s see a flowchart for calculating the value of a number raised to a


positive exponent.
Summary

▪ In this module, you learned that:


– You should not start writing code straightaway and adopt a problem solving
approach in programming.
– Algorithms can be used to critically think about and document the solution to
a problem.
– Pseudocode and flowcharts are a means for writing algorithm.
– Pseudocodes use natural language and structural conventions for writing
algorithms
– Flowcharts are diagrammatic representations of algorithms.
Module 2: Computation Fundamentals
Objectives

▪ At the end of this module, you will be able to:


– Understand different types of data types
– Understand Input/Output/Process requirements
– Understand usage of operators and expressions
– Understand calls of Expressions, Operators, Expressions and
statements
Why Data Types?
Understanding the Need of Data Types

▪ Data type is used to identify various types of data


▪ Different data types are used for storing different kinds of data
▪ Different data type provides different :
▪ Storage
▪ Space
▪ Format
▪ Basic types allow minimum memory
Data Types

▪ Size and Range of Data Types on 16 bit machine.


TYPE SIZE (Bits) Range

Char or Signed Char 8 -128 to 127

Unsigned Char 8 0 to 255

Int or Signed int 16 -32768 to 32767

Unsigned int 16 0 to 65535

Short int or Signed 8 -128 to 127


short int
Unsigned short int 8 0 to 255

Long int or signed long 32 -2147483648 to 2147483647


int
Unsigned long int 32 0 to 4294967295

Float 32 3.4 e-38 to 3.4 e+38

Double 64 1.7e-308 to 1.7e+308

Long Double 80 3.4 e-4932 to 3.4 e+4932


What is a variable?
Understanding the Need of Variable

▪ Variable is used to store temporary data


▪ Variable has a name and data type
– variable name is used to access and manipulate the value of the variable
– data type determines the type of data that the variable can store
Different types of data

▪ Scalar data
▪ Vector data
▪ Associated array
Scalar data

▪ Scalar data and data type:


– Scalar data holds one value at a time
– Scalar data type is the type of a scalar variable.
– For example, char, int, float, and double are the most common scalar data types
Scalar Operators

▪ Produces a new result from one or more other values


– For example, + is an operator because it takes two numbers (the operands,
like 8 and 7), and produces a new value (15, the result).
▪ Operators for Numbers
– Addition, subtraction, multiplication, and division operators
▪ Operators for Strings
– String values can be concatenated with the " . " operator
▪ Numeric and String Comparison Operators

Comparison Numeric String


Equal == eq
Not equal != ne
Less than < lt
Greater than > gt
Less than or equal to <= le
Greater than or equal to >= ge
Vector data

▪ Vector data :
– is used in GIS
– represent the location of a point, a line, and an area
▪ Vector graphics is used for geometrical primitives
▪ Vector graphics formats are opposite to raster graphics:
– raster graphics is the representation of images as an array of pixels
– used for the representation of photographic images
Associated array

▪ Associative array:
– An abstract data type
– A collection of unique keys and a collection of values
– A key is associated with one value
– Example : associative container, map, mapping, dictionary, finite map, and in
query-processing an index or index file

Key Value

John 1

Michel 2

Bob 3

Allen 4
Activity 1

▪ What is the need of data type?


▪ Where do we use vector data?
Need of data type

▪ Data type is used to identify various types of data


▪ Different data types are used for storing different kinds of data
Vector data usage

▪ Vector data is used in GIS:


– for storing the images
– for representing the location of a point, a line, and an area
Activity 2

▪ State True or False:


1. Scalar data holds more than one value.
2. The dot (.) operator is used for numerical operations.
3. In associative array a key is associated with one value
Solution to Activity 2
Solution to Activity 2

1. False
2. False
3. True
Input/Output/Process
Activity 3

▪ Identify input, process and output elements.


– Datasheets
– Labor
– Computer
– Electricity
– Data Entry
– File Data Sheets
– Entered Data
– Filed Data Sheets
Solution to Activity 3
Solution to Activity 3

▪ Input
– Datasheets
– Labor
– Computer
– Electricity
▪ Process
– Data Entry
– File Data Sheets
▪ Output
– Entered Data
– Filed Data Sheets
Operators

▪ Types of operators:
– Arithmetic operators
– Assignment operators
– Unary operators
– Comparison operators
– Logical operators
Arithmetic Operators

Operator Description Example Explanation


+ Adds the operands X=y+z Adds the value of y and z and
stores the result in x

- Subtracts the right operand X=y-z Subtracts z from y and stores


from the left operand the result in x

* Multiplies the operands X=y*z Multiples the values y and z and


stores the result in x

/ Divide the left operand by the X=y/z Divides y by z and stores the
right operand result in x

% Calculates the remainder of an X=y%z Divides y by z and stores the


integer division remainder in x
Assignment Operators (Contd.)

Operator Description Example Explanation


+= Adds the operands and X += y Adds the value of y to x
assigns the result to the left and stores the result in x
operand Equivalent to x = x + y
-= Subtracts the right operand X -= y Subtracts y from x and
from the left operand and stores the result in x
stores the result in the left
operand Equivalent to x = x - y
*= Multiplies the left operand X *= y Multiples the values x and y
by the right operand and and stores the result in x
stores the result in the left
operand Equivalent to x = x * y

/= Divide the left operand by X /= y Divides x by y and stores


the right operand and the result in x
stores the result in the left
operand Equivalent to x = x / y
%= Divides the left operand by X %= y Divides x by y and stores
the right operand and the remainder in x
stores the remainder in the
left operand Equivalent to x = x % y
Unary Operators

Operator Description Example Explanation


++ An increment operator x++ Equivalent to x = x + 1
increases the value of the
operand by one
-- The decrement operator x-- Equivalent to x = x - 1
decreases the value of the
operand by one
Comparison Operators

Operator Description Example Explanation


== Evaluates whether or not x == y Returns true if the values
the operands are equal are equal and false
otherwise
!= Evaluates whether or not x != y Returns true if the values
the operands are not equal are not equal and false
otherwise
> Evaluates whether or not x> y Returns true if x is greater
the left operand is greater than y and false otherwise
than the right operand

< Evaluates whether or not x< y Returns true if x is less


the left operand is less than y and false otherwise
than the right operand

>= Evaluates whether or not x >= y Returns true if x is greater


the left operand is greater than or equal to y and false
than or equal to the right otherwise
operand

<= Evaluates whether or not x <= y Returns true if x is less


the left operand is less than or equal to y and false
than or equal to the right otherwise
operand
Logical Operators

Operator Description Example Explanation


&& Evaluates to true, if both the conditions x > 5 && y < 10 The result is true if condition1
evaluate to true, false otherwise (x>5) and condition2 (y<10)
are both true. If one of them is
false, the result is false.

|| Evaluates to true, if at least one of the x > 5 || y < 10 The result is true if condition1
conditions evaluate to true, false if none (x>5) or condition2 (y<10) or
of the conditions evaluate to true. both evaluate to true. If both
the conditions are false, the
result is false.

! The effect of the ! operator is that the !(x ==0) The result is true, if the
logical value of its operand is reversed. condition (x==0) is false. If the
same condition is true then the
result is false.
Activity 4

▪ Write a pseudo code to accept the employee salary and IT details. Now
using the arithmetic operator display the net salary.
Solution to Activity 4
Solution to Activity 4

//declare the variables


Declare salary, it, netsalary
// accept the salary and it
Display enter employee salary
Accept salary

Display enter it details


Accept it

// using subtraction operator calculate the netsalary


netsalary = salary – it
Print netsalary
Activity 5

▪ Write a pseudo code to accept the ten employees names.


Note: Make use of unary operator.
Solution to Activity 5
Solution to Activity 5

//declare the variables


Declare empname, counter
// accept the employee name
Counter = 1
While (counter <= 10)
{
Display enter employee name
Accept empname
counter++
}
Activity 6

▪ Write a pseudo code to accept employee name, designation and work


experience. Using the following table display the output.

Designation Work Result


Experience (in
years)
SE 4 Eligible for promotion
SSE 6 Eligible for promotion
TL 8 Eligible for promotion

Note: Make use of logical operator.


Solution to Activity 6
Solution to Activity 6

//declare the variables


Declare empname, desig, workex

// accept the details


Display enter empname, desig, workex
Accept empname, desig, workex

//Take the decision


If (design == ‘SE’) && (workex == 4)
{
Print “Eligible for promotion”
}
Else
Solution to Activity 6 (Contd.)

If (design == ‘SSE’) && (workex == 6)


{
Print “Eligible for promotion”
}
Else
If (design == ‘TL’) && (workex == 8)
{
Print “Eligible for promotion”
}
Summary

▪ In this module, you learned that:


– Data type is used to identify various types of data.
– Different data types are used for storing different kind of data.
– Different data type provides different :
• Storage
• Space
• Format
– Variable is used to store temporary data.
– Variable name is used to access and manipulate the value of the variable.
– Variable data type determines the type of data that the variable can store
– The following are the various types of data:
• Scalar data
• Vector data
• Associated array
Summary (Contd.)

– The following are the various types of operators:


• Arithmetic operators
• Assignment operators
• Unary operators
• Comparison operators
• Logical operators
Module 3: Decision Control Structure
Objectives

▪ At the end of this module, you will be able to:


– Understand the need for using conditional statements
– Implement various conditional statements
Understanding the Need for Using Conditional
Statements

▪ Consider a scenario.
– You are working in a reputed IT organization.You are given two choices, either
to travel abroad for a project or to train the fresh recruits and be considered
for a promotion. What would you do?
▪ As in real life, when writing a program, you need to consider a number of
choices to complete a task.
▪ You can implement “choice making” in programs by using conditional
statements.
▪ Based on how many choices you have and how they are related, you can
use the following types of conditional statements in programs:
– If-then-else
– Nested if-then-else
– Switch - case
Understanding If-then-else Statements

▪ You use if-then-else statements when there is a scope to perform two


actions with one condition.
– For example, you need to print the employee details, such as employee name,
employee code, date of birth, date of joining, and department, only if the
employee designation is Trainee else print “No records found.”
▪ It is the simplest conditional statement.
▪ The following is a sample pseudo code that uses this conditional
statement:
If employee designation is “trainee” then
print employee details
else
print “No results found.”
Writing an Algorithm Using If-then-else

Here is the algorithm for the pseudo code just shown.

1. Initialize a variable desig to store the employee designation.


2. Enter employee designation.
3. desig = user input.
4. If desig is “trainee”.
print employee details
else
print “No results found.”
Creating a Flowchart for If-then-else

Start

Initialize a variable
desig

Enter designation

No

desig = Print “No results


“trainee” found.”

Yes

Print employee Stop


details
Activity 1- Using If-then-else

▪ Consider a scenario.
– You are asked by your project manager to print “Grade A” against the
employee code if their salary is greater than Rs. 50,000 else print “Grade B”.
▪ Write a pseudo code for the above-mentioned scenario using if-then-else
statements.
▪ Write an algorithm for the above-mentioned scenario using if-then-else
statements.
▪ Draw a flowchart for the above-mentioned scenario using if-then-else
statements.
Solution to Activity1
Solution to Activity 1- Using If-then-else

Pseudo code:
Initialize a variable sal to store employee salary.
Enter salary.
Store user input in the variable sal.
Check if the value of sal is greater than Rs. 50,000
If yes, print “Grade A” else print “Grade B.”

Algorithm:
1. sal = 0.
2. Enter salary.
3. sal = user input.
4. If employee salary is greater than Rs. 50,000
then
print “Grade A”
else
print “Grade B”
Solution to Activity 1: Creating a Flowchart Using
If-then-else (Contd.)

Start

Initialize a variable
salary

Enter salary

No

Salary > Print “Grade B”


50000

Yes

Stop
Print “Grade A”
Understanding the Need for Nested IF
Statements

▪ Consider a scenario.
– A branch of a leading service provider has attained 10 percent more
subscribers than were targeted. Therefore, the CFO wants to increase the
salary of the branch employees as follows: if employee salary is greater than Rs.
30,000 but between 30K and 45K then increase salary by 10 percent; if salary
is between 46K and 55K then increase salary by 8 percent. In case employee
salary is less than 30K but between 20K and 29K then increase salary by 15
percent; if salary is between 10K and 19K then increase salary by 10 percent.
You are asked to write a pseudo code so that the employee salary can be
updated in the company database.
▪ What would you do in such a situation?
– Use If-then-else statements for each option.
– But this will lead to a long pseudo code and a long program. This would also
decrease the program efficiency.
Understanding the Need for Nested IF
Statements (Contd.)

▪ In such a scenario, you use nested if statements.


▪ Nested if statements are complex.
▪ Each if condition may have one or more sub-conditions.
▪ Each sub-condition defines an action that needs to be taken if the
condition is true.
Understanding Nested IF Statements through
Pseudo code

Enter employee salary


Store user input in the variable sal
If employee salary is greater than Rs. 30,000
If salary is between Rs. 30,001 and Rs 45,000
then increase salary by 10 percent
Else
If salary is between Rs. 45,001 and Rs. 55,000
then increase salary by 8 percent.
else if salary is less than Rs 30,000 Nested IF
If salary is between Rs. 20,000 and Rs. 29,999
then increase salary by 15 percent
else
If salary is between Rs. 10,000 and Rs. 19,999
then increase salary by 10 percent
Understanding Nested IF Statements through
Algorithm

1. Initialize a numeric variable sal.


2. Enter salary.
3. sal = the user input.
4. If sal > 30,000
a. If sal between Rs. 30,001 and Rs 45,000
then increase salary by 10 percent
b. Else
If sal between Rs. 45,001 and Rs. 55,000
then increase salary by 8 percent.
Nested IF
5. Else if sal < 30,000
a. If sal between Rs. 20,000 and Rs. 29,999
then increase salary by 15 percent
b. Else
If sal between Rs. 10,000 and Rs. 19,999
then increase salary by 10 percent
6. Update database and then save.
Understanding Nested IF Statements through
Flowchart

Start
Increase sal by
sal between 10%
30001 and
Initialize sal 45K
variable sal >30K

sal between
Enter 450001 and
salary 55K
sal between
20K and Increase sal by
29999 8%

Increase sal by
sal < 15%
30K
Stop
sal between
10K and
19999
Increase sal by
10%
Activity 2: Writing Nested IF Statements

▪ Consider a scenario.
– The new Cricket Board needs to develop a program to update the run rate of
a live match. The requirement is that if the ball is wide or no ball and if no runs
taken, then run rate should be increased by 1. If ball is wide or no ball and runs
taken then the run rate should increase by 1 plus the number of runs taken. If
the ball is within normal range and runs taken then run rate should be runs
taken plus the run rate.
▪ Write a pseudo code and an algorithm for the above scenario.
▪ Draw a flowchart for the above scenario.
Solution to Activity 2
Solution to Activity 2: Writing Nested IF Statements in
Pseudo code

If ball is wide or no ball


If runs taken then
add number of run rate plus 1 to the run rate
else
if no runs taken then
add 1 to the run rate
If ball is within the normal range then Nested IF
if runs taken
add number of runs taken to the run rate
else
if no runs taken
do not change the run rate
Solution to Activity 2: Writing Nested IF Statements in an
Algorithm (Contd.)

1. Initialize the variable ball and runs


2. Player balls to the batsman Nested IF
3. Store the result in ball
4. If ball is wide or a no ball
1. If runs taken then add the number of runs taken plus 1 to the run rate
2. Else if no runs taken then add 1 to the run rate
5. If ball is within the normal range then
1. If runs taken then add the number of runs taken to the run rate
2. Else if no runs taken then do not change the run rate

Nested IF
Solution to Activity 2: Writing Nested IF Statements in a
Flowchart (Contd.)

Start
Set runs Play a
=0 Set r = 0 ball

Initialize variables
balls, runs, and r
Store input for balls Enter input for
in balls balls and r

Runs Runs
If ball within take take
If ball
normal n? n?
Wide
range or No Yes
Yes Ball
No runs = r + runs
runs = r + runs +1
No
runs = runs

runs = runs + 1
Stop

Nested IF
Understanding the Need for Switch – Case Statements

▪ Reconsider the scenario that you just used in the Activity section of
nested if statements.
– The new Cricket Board needs to develop a program to update the run rate of
a live match. The requirement is that if the ball is wide or no ball and if no runs
taken, then run rate should be increased by 1. If ball is wide or no ball and runs
taken then the run rate should increase by 1 plus the number of runs taken. If
the ball is within normal range and runs taken then run rate should be runs
taken plus the run rate.
▪ While writing the pseudo code and algorithm, and drawing the flowchart
for the scenario, you noticed there are sub-conditions (if statements)
within a single if statement.
▪ Did it increase the complexity of your pseudo code, algorithm, and
flowchart?
– It certainly did.
▪ So, the solution is to use the switch – case statements.
Understanding Switch - Case Statements

▪ Switch – case is a mechanism that helps you define multiple decision


statements.
▪ These decision statements can be referred to as case statements.
▪ The switch statement passes control to one of the multiple case statements
depending on the condition.
▪ It is a substitute for nested and complex if statements.
▪ So, is it a good choice to use switch – case statements over nested if
statements?
– Yes.
Advantages of Switch – Case Statements

▪ Switch – case statements:


– Make programming easier and simple.
– Bring clarity to the code.
– Reduce repetitive coding.
– Are executed faster than nested if statements.
– Evaluates the condition and checks it against many values.
Using Switch – Case Statements

▪ Consider a scenario.
– A leading cellular company has completed the annual performance appraisal of
its employees. The managers have assigned grades to their team members
based on their annual performance. If performance is excellent, grade S is
assigned. If performance is very good, grade A is assigned. If performance is
satisfactory, grade B is assigned. If performance is not satisfactory, grade C is
assigned.
▪ Now, let us have a look at the use of switch – case statements.
Using Switch – Case Statements in a Pseudo code

Switch grade
In case grade is S, print “Excellent.”
In case grade is A, print “Good.”
In case grade is B, print “Satisfactory.”
In case grade is C, print “Not Satisfactory.”
Using Switch – Case Statements in an Algorithm

1. Initialize variable grade.


2. Enter user input for grade.
3. Store user input in grade.
4. In case grade is S, print “Excellent.”
5. In case grade is A, print “Good.”
6. In case grade is B, print “Satisfactory.”
7. In case grade is C, print “Not Satisfactory.”
Using Switch – Case Statements in a Flowchart

Initialize Enter Store the input in


Start variable grade the grade
grade

Case
grade
Case
grade
Case
grade
Case
grade
Case conditions
= “S” = “A” = “B” = “C”

Print Print Print Print “Not


“Excellent” “Good” “Satisfactory” Satisfactory”

Stop
Activity 3: Using Switch - Case Statements

▪ Write a pseudo code for the cricket board scenario using switch -case
statements.
▪ Write an algorithm for the cricket board scenario using switch - case
statements.
▪ Draw a flowchart cricket board scenario using switch - case statements.
Solution to Activity 3
Solution to Activity 3: Using Switch - Case Statements
through Pseudo code

Switch ball
Case ball is wide or no ball and runs taken
add number of run taken plus 1 to the run rate
Case ball is wide or no ball and no runs taken
add 1 to the run rate
Case ball is within the normal range and runs taken
add number of runs taken to the run rate
Case ball is within the normal range and no runs taken
do not change the run rate
Solution to Activity 3: Using Switch - Case Statements
through Algorithm (Contd.)

1. Initialize switch ball.


2. Initialize A, B, C, and D.
3. Set A to “ball is wide or no ball and runs taken”.
4. Set B to “ball is wide or no ball and no runs taken”.
5. Set C to “ball is within the normal range and runs taken”.
6. Set D to “ball is within the normal range and no runs taken”.
7. Case A: add number of run taken plus 1 to the run rate.
8. Case B: add 1 to the run rate.
9. Case C: add number of runs taken to the run rate.
10. Case D: do not change the run rate.
Solution to Activity 3: Using Switch - Case Statements
through Flowchart (Contd.)
Set A = “ball is wide or no
Start
Set runs = ball and runs taken”
0 Set r = 0 Set B = “ball is wide or no
ball and no runs taken”
Set C = “ball is within the
normal range and runs
Initialize variables taken”
balls, runs, r, A, B, C, Set D = “ball is within the
Play a ball
and D normal range and no runs
taken”

Case A Case B Case C

Case D

runs = r + runs + 1 runs = r + runs + 1 runs = r + runs

runs = runs
Case conditions
Stop
Summary

▪ In this module, you learned that:


– You can use if-then-else statements when there is a scope to perform two
actions with one condition.
– Switch-case is a mechanism that helps you define multiple decision statements.
– The switch statement passes control to one of the multiple case statements
depending on the condition.
Using Constructs, Vectors, Arrays, and
Sorting and Searching Techniques
Agenda

1 Using Constructs 2hrs

2 Vectors and Arrays 2hrs

3 Sorting and Searching Techniques 4hrs


Module 1: Using Constructs
Objectives

▪ At the end of this module, you will be able to:


- Understand conditional constructs
- Understand the use of nested conditional statements in algorithm, pseudo
code, and flowcharts
- Determine where to use nested if statements and switch – case statements

Duration 2hrs
Understanding the Need for Using Constructs

▪ Consider a scenario.
– The HR department of your organization is recruiting people on a large-scale.
It is month-end and the Payroll department needs to generate payslips for all
its employees, irrespective of their date of joining. This means even if the
employee has joined just a day before the month-end, his/her payslip should be
generated. It is known that the employee code for each new recruit is in
succession of the last employee code.You are asked to write the pseudo code
for such a program. What would you do?
▪ Would you request the HR to update you regarding the new employee
code every time a new employee joins your organization?
– This will decrease your efficiency of writing the pseudo code as you will be
completely dependent on HR inputs.
▪ So, the solution is to create a strategy that would automatically generate
payslips of all employees even if the last employee code is not known.
Understanding Types of Constructs

▪ To create such a strategy, you can use constructs.


▪ Constructs can be any of the following three types:
– Conditional construct
– Iterative construct
– Conditional iterative construct
▪ Conditional constructs are statements that provide alternate paths for a
task, which if true, define the action to be taken.
– The two types of conditional constructs are if-then-else conditions and switch
– case.
▪ Iterative constructs are statements that allow any action to be repeated N
number of times.
– Types of iterative constructs are while, do while, and for loops.
▪ Conditional iterative constructs are statements that are repeated N
number of times until the condition under which it is performing turns
false. It has an iterative construct within a conditional construct.
Understanding Conditional Constructs

▪ Reconsider the scenario on generating pay slips.


– The HR department of your organization is recruiting people on a large-scale.
It is month-end and the Payroll department needs to generate payslips for all
its employees, irrespective of their date of joining. This means even if the
employee has joined just a day before the month-end, his/her payslip should be
generated. It is known that the employee code for each new recruit is in
succession of the last employee code.You are asked to write the pseudo code
for such a program. What would you do?
▪ Can you provide the solution by using if-then-else or switch constructs?
– The answer is NO. This is because there are no alternate paths that need to
be taken. The requirement is to generate pay slips for all employees at the
month-end irrespective of their date of joining.
▪ So, you cannot use conditional constructs in all situations.
▪ Then, which construct would be idle for such a situation?
– The solution is to use iterative constructs.
Activity 1: Conditional Constructs

▪ Consider the scenario.


– DelMag Ltd has decided to part away with some of its operations to its sister
concern MyDelMag. Therefore, it has prepared a list of employees who would
be shifted to MyDelMag. For this, it needs to transfer the employee records of
these employees to the employee database of MyDelMag. Can this problem be
resolved by using conditional constructs?
– Yes, the problem can be resolved by using conditional constructs. But, the
program will be extremely lengthy as there will be n number of if or switch –
case statements as the number of employees to be transferred.
▪ Then, what is the solution?
Solution to Activity 1
Solution to Activity 1 - Conditional Constructs

▪ Use iterative constructs.


Understanding the while Loop

▪ While loop:
– Checks whether the defined condition is true before executing the code
specified within the loop.
– In case the defined condition is false then the code within the while loop will
not be executed. In such a case the next statement following loop will be
executed.
– For example, consider the following pseudo code:
While not end of file
generate pay slip
Print “No more records.”
– Here, pay slip will be generated till the last employee code is found. If there is
no employee code, which means it has reached end of file, the program will
print “No more records.”.
▪ Therefore, the pay slip scenario we just discussed can be solved through
the while loop.
Using the while Loop

▪ Consider a scenario.
– A small-scale cellular company, Cellbell Services, is acquired by a cellular giant,
WipCell Ltd. Now, WipCell wants to append the employee details of CellBell
Services to its employee database. We need to write a pseudo code to help
WipCell be able to do this using the while loop.
▪ Pseudo code:
Open WipCell Employee database
Open CellBell Services Employee database
Go to end of the WipCell Employee database
While not end of file
read CellBell Services Employee database
append employee details in WipCell Employee database
Save WipCell Employee database
Close CellBell Services Employee database
Close WipCell Employee database
Understanding the Do while Loop

▪ Do while loop:
– Checks whether the defined condition is true after executing the code
specified within the loop.
– This means that the code within the do while loop will be executed at least
once even if the condition is false. This is because here, the condition is
evaluated at the end of the loop.
– For example, consider the following pseudo code:
Do
generate pay slip
Print pay slip
while employee department is Finance
– Here, pay slip will be generated and printed even if the employee department
is not Finance.
– In case the condition defined at the end of the do while loop is true then the
loop is re-executed until the condition turns false.
Using the Do while Loop

▪ Reconsider the scenario.


– A small-scale cellular company, Cellbell Services, is acquired by a cellular giant,
WipCell Ltd. Now, WipCell wants to append the employee details of CellBell
Services to its employee database. We need to write a pseudo code to help
WipCell be able to this using the Do while loop.
▪ Pseudo code:
Open WipCell Employee database
Open CellBell Services Employee database
Go to end of the WipCell Employee database
Do
read CellBell Services Employee database
append employee details in WipCell Employee database
while not end of CellBell Services Employee database
Save WipCell Employee database
Close CellBell Services and WipCell Employee databases
Understanding the For Loop

▪ For loop:
– Is a simple form of while loop. The only difference is that in the for loop the
number of iterations is known.
– Maintains a loop counter to track the number of times the loop is executed. The
for loop stops when the loop counter equals the specified number of iterations.
– For example, you need to generate pay slips for employees whose employee
code is between 020 and 030 and also print the number of total pay slips
generated. Consider the following pseudo code:
Set counter equal to 0
For start_employee_code = 020 end_employee_code = 030
generate pay slip
Set counter to counter + 1
Print counter
Using the For Loop

▪ Reconsider the scenario we used for the while and Do while loops.
– A small-scale cellular company, Cellbell Services, is acquired by a cellular giant,
WipCell Ltd. Now, WipCell wants to append the employee details of CellBell
Services to its employee database. We need to write a pseudo code to help
WipCell be able to this using the for loop.
▪ Pseudo code:
Open WipCell and CellBell Services Employee databases
Go to end of the WipCell Employee database
r = last serial number in the CellBell Services Employee database
For rec = 0
read CellBell Services Employee database
append employee details in WipCell Employee database
rec = rec + 1
Till rec = r
Save WipCell Employee database
Close CellBell Services and WipCell Employee databases
Activity 2 - Using Iterative Statements

▪ Consider a scenario.
– A real estate company, ReaLand, wants to outsource a project to another
company. It has shortlisted a list of companies and has gathered details about
them and has stored in two files, Real1 and Real2. Now, ReaLand wants to
store this information in their MarketStudy database file and then generate a
detailed report for analysis.You need to write the details collected for each
company in the MarketStudy file and then generate a report.

▪ Write a pseudo code for the above scenario using the while loop.
▪ Write a pseudo code for the above scenario using the Do while loop.
▪ Write a pseudo code for the above scenario using the For loop.
Solution to Activity 2
Solution to Activity 2 - Using Iterative
Constructs

▪ Pseudo code using the while loop:


Open Real1 and MarketStudy files
Go to end of the MarketStudy file
While not end of the Real1 file
read Real1
write in MarketStudy
Close Real1
Open Real 2
while not end of the Real2 file
read Real2
write in MarketStudy
Save the MarketStudy file
Generate report
Close Real2 and MarketStudy file
Solution to Activity 2 - Using Iterative
Constructs (Contd.)

▪ Pseudo code using the Do while loop:


Open Real1 and MarketStudy files
Go to end of the MarketStudy file
Do
read Real1
write in MarketStudy
While not end of the Real1 file
Close Real1
Open Real 2
Do
read Real2
write in MarketStudy
while not end of the Real2 file
Save the MarketStudy file
Generate report
Close Real2 and MarketStudy file
Solution to Activity 2 - Using Iterative
Constructs (Contd.)

▪ Pseudo code using the For loop:


Open Real1 and MarketStudy files
Contd.
Go to end of the MarketStudy file
Save the
Rec = 0 MarketStudy
Store the last serial number of the Real1 file in rec file
For counter = 0
read Real1 Generate
report
write in MarketStudy
counter = counter + 1 Close Real2
When counter = rec close Real1 and
Open Real 2 MarketStudy
Store the last serial number of the Real2 file in rec file
For counter = 0
read Real2
write in MarketStudy
counter = counter + 1
When counter = rec close Real2
Understanding the Need for Conditional Iterative
Statements

▪ Consider a scenario.
– DelMag Ltd has decided to part away with some of its operations to its sister
concern MyDelMag. The company has prepared a list of prominent
shareholders who need to be informed about the decision. It wants to intimate
its shareholders via e-mail or phone. Each shareholder may have one or more
e-mail IDs or phone numbers. Can this problem be resolved by using
conditional constructs?
▪ Here, you have a condition as well as the need to repeat an action.
– Condition: If the shareholder has one or more e-mail IDs or phone numbers.
– Action: Inform shareholders about DelMag decision to part away with some of
its operations to its sister concern MyDelMag.
▪ Therefore, in such a scenario, you use conditional iterative constructs.
Using Conditional Iterative Statements

▪ Pseudo code using the while loop:


Open DelMag Shareholder database
Read DelMag Employee database
If shareholder has one or more e-mail ID
While not end of shareholder’s e-mail IDs
write an e-mail to the shareholder to inform about the company’s
decision
else if shareholder has one or more phone numbers
While not end of shareholder’s phone numbers
write an SMS to inform about the company’s decision
Using Conditional Iterative Statements (Contd.)

▪ Pseudo code using the Do while loop:


Open DelMag Shareholder database
Read DelMag Employee database
If shareholder has one or more e-mail ID
Do
write an e-mail to the shareholder to inform about the company’s
decision
While not end of shareholder’s e-mail IDs
else if shareholder has one or more phone numbers
Do
write an SMS to inform about the company’s decision
While not end of shareholder’s phone numbers
Using Conditional Iterative Statements (Contd.)

▪ Pseudo code using the For loop:


Open DelMag Shareholder database
Read DelMag Employee database
If shareholder has one or more e-mail ID
for counter = 0
write an e-mail to the shareholder to inform about the company’s
decision
counter = counter + 1
else if shareholder has one or more phone numbers
for counter = 0
write an SMS to inform about the company’s decision
for counter = counter + 1
Using Conditional Iterative Statements

▪ Reconsider the scenario.


– DelMag Ltd has decided to part away with some of its operations to its sister
concern MyDelMag. The company has prepared a list of prominent
shareholders who need to be informed about the decision. It wants to intimate
its shareholders via e-mail or phone. Each shareholder may have one or more
e-mail IDs or phone numbers.
▪ Write a pseudo code using switch-case with the while loop.
▪ Write a pseudo code using switch-case with the Do while loop.
▪ Write a pseudo code using switch-case with the for loop.
Using Conditional Iterative Statements

▪ Pseudo code using the while loop:


Open DelMag Shareholder database
Read DelMag Employee database
Switch A, B
case A = shareholder has one or more e-mail ID
While not end of shareholder’s e-mail IDs
write an e-mail to the shareholder to inform about the company’s
decision
case B = shareholder has one or more phone numbers
While not end of shareholder’s phone numbers
write an SMS to inform about the company’s decision
Using Conditional Iterative Statements (Contd.)

▪ Pseudo code using the Do while loop:


Open DelMag Shareholder database
Read DelMag Employee database
Switch A, B
case A = shareholder has one or more e-mail ID
Do
write an e-mail to the shareholder to inform about the company’s
decision
While not end of shareholder’s e-mail IDs
case B = shareholder has one or more phone numbers
Do
write an SMS to inform about the company’s decision
While not end of shareholder’s phone numbers
Controlling Constructs

▪ You need to control constructs to allow the program to function properly


and complete the desired task.
▪ You can control both conditional and iterative constructs by using the
break keyword.
Controlling Conditional Constructs

▪ Controlling conditional constructs:


Note: You do not need a break statement in the if-then-else conditional statement.
Using if-then-else automatically controls the flow of the program.
– Using break in a switch, allows you exit from the switch-case statements and
pass control to the next statement following the switch.You write break at the
end of every case in the switch.
▪ For example, consider the following pseudo code:
switch S = “A” or “B”
case S = “A”
print “Good performance.”
break
case S = “B”
print “Poor performance.”
break
generate report
Controlling Iterative Constructs

▪ Iterative constructs run the statements within the body until the condition
given does not turns false.
▪ Using break in iterative constructs stops the loop from becoming an
infinite loop.
▪ Consider the two pseudo codes to add two numbers but exit the while or
do while loop when one of the numbers is 0.
Enter two numbers Enter two numbers
Store first number in N Store first number in N
Store second number in P Store second number in P
do
while (N or P not equal to 0)
Sum = N + P
Sum = N + P print Sum
print Sum If N = 0 or P = 0 then
If N = 0 or P = 0 then break
break while (N or P not equal to 0)
Controlling Iterative Constructs (Contd.)

▪ The pseudo code shows the use of break statement in the for construct.
Enter two numbers
Store first number in N
Store second number in P
for (; ;)
Sum = N + P
print Sum
If N = 0 or P = 0 then
break
Activity 4 - Controlling Constructs

▪ Consider a scenario.
– Your company maintains a file that has the names of all the companies they
have worked with. It also has company names that they have blacklisted for
future operations. Write a pseudo code, using the while, do while, and for
loops, that prints the company names that appear before the first blacklisted
company name.
▪ Write a pseudo code using the while loop that prints the company names
that appear before the first blacklisted company name.
▪ Write a pseudo code using the do while loop that prints the company
names that appear before the first blacklisted company name.
▪ Write a pseudo code using the for construct that prints the company
names that appear before the first blacklisted company name.
Solution to Activity 4
Solution to Activity 4 - Controlling Constructs

▪ Pseudo code using the while loop: Do while loop:


Open Company database file Open Company database file
While (not end of Company file) Do
read Company name read Company name
if company name is blacklisted
if company name is blacklisted
break
break else
else print company name
print company name While (not end of Company file)
Solution to Activity 4 - Controlling Constructs

▪ Pseudo code using the for construct:


Open Company file
For ( ; ;)
read Company name
if company name is blacklisted
break
else
print company name
counter = counter + 1
Summary

▪ In this module, you learned that:


– Constructs are of the following three types:
• Conditional constructs
• Iterative constructs
• Conditional iterative constructs
– The two types of conditional constructs are if-then-else conditions and
switch-case.
– There are three types of iterative constructs while, do while, and for loops.
– You need to control constructs to allow the program to function properly and
complete the desired task.
– You can control both conditional and iterative constructs by using the break
keyword.
Module 2: Vectors and Arrays
Objective

- At the end of this module, you will be able to:


- Understand the need of arrays in programming
- Use arrays
- Understand the need of vectors in programming
- Use vectors

Duration 2hrs
Understanding the Need of Grouping Data

▪ Consider a scenario:
– You are a software programmer attending a seminar on Open Source. Along
with you there are around 50 other delegates. At the beginning of the seminar
there is an ice breaking session where each delegate introduces herself and
distributes their visiting cards to the other delegates. At the end of the session
you have around 50 visiting cards lying unorganized on your desk.
– How can you organize the cards?
– The cards can be organized by putting them into a container, such as a card
holder.
– This real life scenario is also applicable in computer programming.
Introducing Array

▪ Applications often need to work on huge amount of data


▪ Data needs to be organized
▪ Similar data can be grouped to simplify operation on them
▪ Data structures enable grouping data
▪ An example of a simple data structure is an array
Understanding the Need of Array

▪ Simple calculator pseudo code to compute the sum of two numbers:


Var1 = 20
Var2 = 30
Result=Var1 + Var 2
▪ Calculator pseudo code to compute the sum up to 100 numbers:
Var1 = 20
Var2 = 30
…….
……..
Var100=19
Result=Var1 + Var 2+….+Var100
▪ 100 variables needs to be created
▪ A better way to handle situations like this: use an array
Understanding Array

▪ An array stores elements of the same type


▪ Each element in an array is identified by an index
▪ Each element of an array occupies the same number of bytes.
▪ Elements of an array can be retrieved using its index.
Understanding Array (Contd.)

▪ Consider a scenario:
▪ You are a programmer and you have been assigned to develop a program that will
randomly generate a 10 digit lottery number each time it runs.
▪ How will you use an array as the solution?
Activity 1 – Understanding Array

▪ Provide the pseudo code of the lottery number generator program


discussed in the previous slide.
Solution to Activity I
Solution to Activity I

Declare Integer lotteryNumbers[10]


Declare Integer index
For index = 0 to 9
Set lotteryNumbers[index]= RANDOM (0, 9)
End For
For index 0 to 9
print lotteryNumbers[index]
End For
Types of array

▪ Arrays can be:


▪ One-dimensional: Data is stored in consecutive addresses in the memory.
▪ Multi-dimensional:
▪ Two-dimensional array are most frequently used. Data is stored by rows or columns in
consecutive addresses in the memory.
Activity 2

▪ Consider a scenario:
▪ You are modeling a real life one day cricket match. The batting team has three power
play sessions of five overs each and a normal play session of 35 overs. You need to
record the runs scored in each of the sessions by both the team.
▪ You need to use two-dimensional array and depict this scenario visually.
▪ Provide the pseudo code to create the two dimensional array and retrieve
the runs scored by the second team in the third power play session.
Solution to Activity 2

▪ You will require a two-dimensional array with four columns representing


the four sessions and two rows representing the two teams.
Solution to Activity 2 (Contd.)

//Declare and initialize array


int ScoreArray[2][4] = {{80, 42, 46, 150}, //Team 1
{65, 30, 41, 100}}; //Team 2

//Retrieve runs scored by Team 2 in the third power play session


variable runs=ScoreArray[1,2];
Understanding Associative Array

▪ Associative array:
▪ Abstract data type
▪ Collection of data values where each value is associated with a key.
▪ Multiple keys can have same values
▪ Multiple values cannot have same key
▪ As an example of movie show time, you might find that two different
movie halls are showing the same movie of Harry Potters at 2:00 p.m.
However you would never find a movie hall listed twice, showing two
different movies in the same time slot.
▪ If you model this example as an associative array, identify the keys and
values.
Understanding Associative Array (Contd.)
Activity 3 – Creating Associated Array

▪ Create an associated array to model the movie show time example using
array-like notation.Then, retrieve the movie name and screening time of
Fun Cinemas
Solution to Activity 3
Solution to Activity 3

//Declare and initialize array


moviearray['Rex Cinemas']='Harry Potter 2 PM'
moviearray['Inox Cinemas']='Harry Potter 2 PM'
moviearray['Fun Cinemas']='Red Dragon 3 PM'
moviearray['Park Multiplex']='Sunshine 4 PM'
//Retrieve runs scored by Team 2 in the third power play session
Variable movie=moviearray [‘Fun Cinemas'];
Associative Array Implementations

▪ Smalltalk, .NET, Python, and REALbasic implements associative arrays as


dictionaries.
▪ C++ and Java implements associative arrays as maps.
▪ The method to iterate through the elements of an associated array
depends on the programming language being used.
Limitations of Array

▪ Primary limitation of array:


▪ Static size: Need to specify size during creation
▪ Can be addressed by using vector
▪ Consider this example:
▪ You need to create an array to store years and you do not know whether the array will
store 30 or 30,000 years at runtime.
▪ How will you set the array size and what might be the result?
Introducing Vectors

▪ Vectors:
– Type of sequence container
– Implemented as dynamic arrays
– Stored in contiguous storage locations
– May contain both primitive types and objects
– Storage in vectors is handled automatically
Introducing Vectors (Contd.)

▪ Vector allows:
– Accessing individual elements by their position index
• Can be performed at constant time
– Iterating over the elements in any order
• Can be performed at linear time
– Adding and removing elements from its end
• Can be performed at constant amortized time
Activity 4

▪ Consider a scenario:
– Ananth Nag is one of the members organizing the annual day functions of their
college, which is open for everybody. Ananth Nag is organizing a lucky draw
where people can submit their names and after every one hour a winner will
be declared. The winners name will then be removed from the lot but new
people can still keep joining as the game continues. The game will continue for
five hours
▪ You need to model the lucky draw game using a vector.
Solution to Activity 4
Solution to Activity 4

1. Create a vector
2. Keep adding names to the vector as people submits
3. 3 After one hour Generate a random number in the range of 0 to the
size of the vector
4. 4 Iterate through the elements the number of times represented by the
random number
5. Remove the name from the vector
6. Repeat steps 2 to 5 five times
Limitation of Vectors

▪ Insertion and deletion of elements that are between other elements


require shifting of elements
▪ Different programming languages provides different vector implementation
– The rate at which the capacity of a vector grows is implementation dependent.
Summary

▪ In this module, you learned that:


– An array is a fundamental data structure that stores elements of the same
type.
– Elements of an array can be retrieved using its index.
– Arrays can be one-dimensional or multidimensional
– Associative array is a collection of data values where each value is associated
with a key.
– The primary limitation of array is that you need to define the size of an array
before adding elements of you.
– Vectors are a kind of sequence container.
– Vector containers are implemented as dynamic arrays.
– Storage in vectors is handled automatically, allowing it to be expanded and
contracted as needed.
Summary (Contd.)

▪ Vector allows:
– Accessing individual elements by their position index
– Iterating over the elements in any order
– Adding and removing elements from its end
– In a vector, insertion and deletion of elements that are between other
elements require shifting of elements
▪ Different programming languages provides different vector implementation
Module 3: Sorting and Searching Techniques
Objectives

▪ At the end of this module, you will be able to:


– Understand the need of searching techniques
– Implement various searching techniques
– Understand the need of sorting techniques
– Implement various sorting techniques
Understanding the Need of Searching Techniques

▪ A searching technique finds if a target element is part of the given set of


data
▪ Consider a scenario:
– An online dictionary application has a random list of 10,000 words. Currently
an end user enters a word to search for its meaning. The application starts
from the first word in the dictionary, each word is compared to the word to
be searched. Search stops when either the word is found, or word greater than
the word is found, or the end of the dictionary is reached.
▪ For a similar online dictionary application, will you use the preceding
approach?
▪ No. This process is very inefficient because it has a very large search
space. No attempt has been made to reduce the search space. If there
were 10,000 words in the dictionary, on an average it would make 5,000
comparisons.
Understanding the Need of Searching
Techniques(Contd.)

▪ So, what can you do in such a scenario and why?


– The algorithm used and the way the data is organized have a significant impact
on the efficiency of a searching technique.
– The same search approach used in the online dictionary application would
have been more efficient had the word been arranged alphabetically.
– Using this approach, open the dictionary in two halves. Check whether the
word is in the left half or the right half? If, it is in left half, then again split the
left half into equal left/right halves. Continue this process until the word is
found.
– In this scenario how does the efficiency of the searching approach improve?
– In each step, the search space is reduced to half. Therefore, if there are 10,000
words in the dictionary, then after first step the search space is reduced to
5,000, after second step, it is reduced to 2,500, and so on.
Activity -1 : Searching Techniques

▪ Consider the following scenario:


– In an online dictionary application, words are arranged in the alphabetic order
and grouped under alphabetic sections. Also the first and last word on each
page is written on top of that page.
▪ Identify the searching approach that you will employ to search for a word.
Solution to Activity 1
Solution to Activity - 1

▪ First, search for the section in which the word falls.


▪ Then, starting from the first page in that section, compare the word to be
searched with the first and last word on each page.
▪ If the word falls in the range of a particular page, then starting from the
first word on that page, compare each word to the word to be searched
until either the word is found or the end of the page is reached.
Types of Searching Techniques

▪ The most commonly used searching techniques are:


– Linear
– Binary
Performing Linear Search

▪ Given a list of items and an item to be searched in the list, linear search
would involve comparing the item sequentially with the elements in the
list.
▪ Consider a Scenario
– You need to search the record of a student, whose student ID is 120, from a
list of student records.
Performing Linear Search (Contd.)

▪ The algorithm to search for a student ID is:


1. Read the student ID to be searched
2. Set i = 0
3. Repeat step 4 until i > n or arr[i] = student ID
4. Increment i by 1
5. If i > n:
6. Display “Not Found”
7. Else
8. Display “Found”
Performing Binary Search

▪ Helps you search data in very few comparisons.


▪ To apply binary search algorithm, the list to be searched should be sorted
Performing Binary Search (Contd.)

▪ The algorithm to search for a desired element by using binary search is:
1. Accept the element to be searched
2. Set lowerbound = 0
3. Set upperbound = n – 1
4. Set mid = (lowerbound + upperbound)/2
5. If arr[mid] = desired element:
1. Display “Found” and Go to step 10
6. If desired element < arr[mid] then:
1. Set upperbound = mid – 1
7. If desired element > arr[mid] then:
1. Set lowerbound = mid + 1
8. If lowerbound <= upperbound then:
1. Go to step 4
9. Display “Not Found”
10. Exit
Performing Binary Search (Contd.)

▪ Performing binary search for the target value 83


Activity 2 - Performing Binary Search

▪ Identify the number of iterations required to search the target value 90 in


the given list using binary search. The following figure represents the list.
Determining Efficiency of Linear Search

▪ Efficiency of a searching algorithm is determined by the running time of the


algorithm
▪ Best case efficiency of linear search is O(1)
▪ Worst case efficiency of linear search is O(n).
▪ average number of comparisons for a linear search is 1/2(n + 1)
Determining Efficiency of Binary Search

▪ Best case efficiency of binary search is O(1)


▪ Worst case efficiency of binary search is O(log n)
Search Scenarios

▪ You are developing a Word Processor application and need to include a


search function. This function should enable a user to search for a word in
a page. Which searching technique will you use?
– In this scenario, applying linear search will be more efficient. A page will
typically contain around 30 words. For such small amount of data, using binary
search will carry the overhead of first sorting the data and then only
performing the search.
▪ You need to search for an item on a list containing one million items.
Which search technique will you use?
– In this scenario, linear search would take an average of five hundred thousand
steps to find an item, whereas binary search would take only 20 steps.
Need for Sorting

▪ Consider a scenario
– You need to retrieve the telephone number of a person named John in a
telephone directory, where the names in the telephone directory are stored
in a random order.
▪ What is the limitation of this approach and what can be the solution?
– In this approach, to retrieve the desired record, you need to sequentially
traverse the list of names one by one because the names are not sorted, which
is a tedious and time consuming activity.
– When you have to retrieve a record from a huge volume of data, this activity
becomes even more difficult.
▪ A simple solution to save time, and search data efficiently is sorting. Sorting
is the process of arranging data in some pre-defined order or sequence.
The order can be either ascending or descending.
– If the data is sorted, you can directly go to the section that stores the names
starting with ‘J’, thereby reducing the number of records to be traversed.
Selecting a Sorting Technique

▪ There are several sorting techniques


▪ Criteria to select a sorting technique:
– Execution time
– Storage space
– Programming approach
Selecting a Sorting Technique (Contd)

▪ Consider a scenario
– You have to sort 12 playing cards of spade starting from the Ace to the King.
▪ What criteria will you use to select a sorting technique?
▪ In this situation, all the sorting techniques will use a reasonable amount of
storage space. In addition, the sorting techniques will be executed in a
reasonable amount of time. Therefore the criteria for selecting the sorting
algorithm would be the programming effort involved. An algorithm that
requires less programming effort would be preferred over an algorithm
that requires more programming effort.
Selecting a Sorting Technique (Contd)

▪ Consider a scenario
– You have to sort 150,000 entries of a Yellow Page
▪ What will you consider before selecting a sorting technique?
▪ In this situation, the time taken by different algorithms may differ drastically
because of the difference in their orders of growth. For example, when
there are a large number of elements, an algorithm with a logarithmic
order of growth will execute much faster than an algorithm with a
quadratic order of growth. In addition, with increase in data, the space
requirement of different algorithms may also differ drastically. Therefore,
when the data is large, you need to select a sorting algorithm that makes
most efficient use of time or memory, depending upon the requirement.
Selecting a Sorting Technique (Contd)

▪ The various sorting techniques that you can use are:


– Bubble sort
– Selection sort
– Insertion sort
– Quick sort
Understanding Bubble Sort

▪ Bubble sort
– Popularly used to illustrate sorting
– Repeatedly steps through the list to be sorted
• For each pass, it compare each pair of adjacent items and swaps them if they are in
the wrong order
• This continues till the list is sorted
Activity 3

▪ Consider a scenario
– You are at a family gathering and you have hired a photographer to take a
photograph of your family members. Currently they are standing randomly in a
line. The photographer wants the family members to stand in a line ordered
from youngest to oldest.

▪ You need to apply the bubble sort technique to this problem


▪ Hint: Of the two members at the left find out which one is older. If the one on the right
of the pair is older, then do nothing, else ask them to swap positions. Continue
accordingly.
Understanding Selection Sort

▪ Selection sort
– Simple sorting algorithm is suitable for sorting short lists
– Involves multiple passes:
• Pass 1: Locate the smallest element from the list, and swap it with the element at
the first position in the list
• Pass 2: Locate the next smallest value, and swap it with the element placed at the
second position in the list.
• Repeat the steps until all the values are placed at the correct positions in the list
Understanding Selection Sort (Contd)
Selection Sort Algorithm

▪ The algorithm used to sort the list by using the selection sort is:
1. Repeat steps 2 and 3 varying j from 0 to n – 2 // Repeat for n – 1 passes
2. Find the index of the minimum value in arr[j] to arr[n – 1]
1. Set min_index = j
2. Repeat step c varying i from j + 1 to n – 1
3. If arr[i] < arr[min_index] then:
min_index = I
3. Swap arr[j] with arr[min_index]
Activity 4 - Selection Sort Algorithm

▪ Consider the following scenario:


– Arvind Jain is working for an organization that collects statistical data on
various sectors. Arvind has been provided data on the agricultural output of
28 states of India for the year 2010. Arvind needs to sort the data based on
amount of agricultural output in increasing order so that a statistical graph
similar to the following figure can be created.

▪ Provide the algorithm to sort the data using selection sort


Introducing Insertion Sort

▪ Insertion sort
– Similar to selection sort, the insertion sort has a quadratic order of growth
– More efficient if the list that needs to be sorted is nearly sorted
Understanding Insertion Sort
Understanding Insertion Sort (Contd)
Insertion Sort Algorithm

▪ The algorithm used to sort the list by using the insertion sort is:
1. Repeat steps 2, 3, 4, and 5 varying i from 1 to n – 1
2. Set temp = arr[i]
3. Set j = i – 1
4. Repeat until j becomes less than 0 or arr[j] becomes less than or equal to
temp:
1. Shift the value at index j to index j + 1
2. Decrement j by 1
5. Store temp at index j + 1
Introducing Quick Sort

▪ Quick sort
– Based on the divide and conquer approach
– Process:
• Selecting an element from the list called a pivot
• Partitioning the list into two parts based on the following conditions:
- All the elements towards the left end of the list are smaller than the pivot
- All the elements towards the right end of the list are greater than the pivot.
• The pivot positioned between the two sublists.
• This process is repeated for each of the two sublists until one element is left in
each sublist.
Quick Sort Algorithm

▪ Algorithm: QuickSort(low, high) // Low is the index of the first


//element in the list and high is the index of the last element in the list
1. If i <= j then: Go to step 5 // Continue the search
2. Set pivot = arr[low]
3. Set i = low + 1
4. Set j = high
5. Repeat step 6 until i > high or arr[i] > pivot // Search for an element greater
//than pivot
6. Increment i by 1
7. Repeat step 8 until j < low or arr[j] < pivot // Search for an element smaller
// than pivot
8. Decrement j by 1
9. If i < j then: // If greater element is on the left of smaller element
// Swap arr[i] with arr[j]
Quick Sort Algorithm (Contd)

10. If (low > high) then: Return


11. If low < j then: Swap arr[low] with arr[j] // Swap pivot with last element in
//first part of list
12. QuickSort(low, j – 1) // Apply quick sort on list left to pivot
13. QuickSort(j + 1, high) // Apply quick sort on list right to pivot
Activity 5

▪ Consider an unsorted list of numbers stored in an array named arr, as


shown in the following figure.

▪ You need to sort the preceding list by using the quick sort algorithm.
Summary

▪ In this module, you learned that:


– The most commonly used searching techniques are:
• Linear Search
• Binary Search
– The best case efficiency of linear search is O(1) and the worst case efficiency
of linear search is O(n).
– To apply binary search algorithm, you should ensure that the list to be
searched is sorted.
– The best case efficiency of binary search is O(1) and the worst case efficiency
of binary search is O(log n).
Using Data Structures to Solve Business
Cases
Agenda

1 Problem Solving Using Data Structures 2hrs

2 Problem Solving Using Linked List 3hrs

3 Problem Solving Using Stacks 3hrs


Module 1: Problem Solving Using Data
Structures
Objectives

▪ At the end of this module, you will be able to:


- Understand the need of data structures
- Identify the various types of data structures

Duration 2hrs
Module Overview

▪ Problem solving is an essential part of every scientific discipline.


▪ In today’s world, computers are widely used to solve the problems
pertaining to various domains, such as education, medicine, banking,
commerce, manufacturing, and transport.
▪ To solve a problem by using computers, one needs to write a program.
▪ A program consists of the following two components:
– Algorithm
– Data Structures
▪ Many different algorithms can be used to solve the same problems.
▪ Similarly, various types of data structures can be used to represent a
problem in a computer.
▪ In this module, we will discuss why data structures are required in
programming.
▪ In addition, we will discuss the various types of data structures.
Why Data Structure?
Understanding the Need of Data Structures

▪ Consider a scenario:
– Sam is employed at the ticket counter of the ABC stadium.
– He has been assigned a task to distribute free pass of IPL T20 to public.
– Now, when people got to know about this, all of them rush at the same time.
– Now, what will happen?

Public are in a mess !

Sam is in a mess !

He is unable to perform his task !


Sam is in mess because he had not
planned to organize or arrange
the public before distributing the
tickets.
Solution is to make the public
stand in a queue or in an order
so that Sam can approach them
smoothly and complete his task.
Understanding the Need of Data Structures
(Contd.)
▪ In the given scenario:
– The public can be considered as:
• Data
– Issuing the pass can be considered as:
• A Task (Data Processing)
▪ Thus, arranging the data or organization of data before performing any
task can be referred as Data Structure.
Understanding the Need of Data Structures
(Contd.)
▪ Data structure refers to the way in which various data elements are
organized in memory with respect to each other.
▪ Data structures are designed to hold a collection of data items.
▪ The appropriate usage of data structure allows us to overcome the
following programming challenges:
– Simplifying complex problems
– Creating standard, reusable code components
– Creating programs that are easy to understand and maintain
Now, the questions arise:
How to organize the data?
• On my own wish?
• On my own way?
• Or can I organize the data with the method I am familiar with?
Different Types of Data Structure

▪ Consider a scenario:
– There are Children and I want to play a small game with them.
– How do I do this?

Call all the children ask them to form a circle


I go to centre
Start the play
Different Types of Data Structure (Contd.)

▪ Consider another scenario:


– I want to take the children on the Road from one place to another
– How do I this?

Call the children ask them to stand three in a row


Like wise multiple row of same order.
Once the row formation is over,
Ask them to do march-past.
Different Types of Data Structure (Contd.)

▪ In the preceding scenario, if I consider that my children are good in


making a circle than the Rows.
▪ Now,
– Can I ask them to do a march-past on Road in Circle? Just because they are
good in circle formation.
▪ No, because it will result in traffic jam or an accident.
▪ Thus,
– You cannot organize the data:
• On your own wish
• On your own way
• On according to the method your are familiar with
– You need to select the suitable arrangement of Data that matches the task or
that suites the task.
Different Types of Data Structure (Contd.)

▪ For different organization, we need different types of arrangement data.


▪ Thus, the following standard data structures are designed which are being
used over the years to hold a collection of data items:
– Array
– Linked List
– Stacks
– Queues
– Trees
– Graphs
Let us see the usage of different data
structures in different situations.
Different Types of Data Structure (Contd.)

▪ Consider a scenario:
– In a Bank, there are thousands of customers.
– Each customer makes 100 -1000 transaction in a year.
– Therefore, lakh of transaction data is stored in a file.
▪ Now, you have been assigned a task to print a pass book of a Bank for a
particular customer.
▪ Problem to be faced while performing the preceding task:
– How to identify one customer transaction data among lakhs of transactions
data?
– Will you search one by one?
• Isn’t it inefficient and time consuming
What can be done to avoid such
problems?
Different Types of Data Structure (Contd.)

▪ While recording the transaction data of a customer, let it hold the address
of the next transaction of the same customer.
▪ Apply this strategy while recording the transaction data for other
customers.
▪ Now, when you need to print the pass book for a particular customer:
– You can pick up the first transaction of customer
– Start moving to other transaction using the address it holds without searching
▪ This will finish the job with in very less time.
▪ When one data holds the address of the other data for traversal, it forms a
Linked list.
▪ Hence, implementation of Linked List is the best solution for the given
scenario.
Different Types of Data Structure (Contd.)

▪ Consider a scenario where you need to design a Complier which works as


follows:
– There is a call for function f1() to execute
– Function f1() call function f2()
– Function f2() call function f3()
– And so on
Points to be kept in mind while
designing the desired compiler.
Different Types of Data Structure (Contd.)

▪ You need to take care that the last function should be executed first and
then the second last and so on.
▪ Recognize the next function that needs to be executed after the execution
of the existing function.
Different Types of Data Structure (Contd.)

▪ As the Function call comes:


– Start storing or arranging the call one above the other
– Once one function call is executed take the other call that is at the top
– And repeat the process till the first function call is executed.
▪ This will allow executing the function call on the basis of last come first
serve.
▪ Thus, Stack is the best suitable data structure to be implemented in the
given scenario.
Different Types of Data Structure (Contd.)

▪ Consider a scenario:
– You have been assigned a task to implement online Railway Reservation
System.
Let us first understand the workflow
of the online Railway Reservation
System?
Different Types of Data Structure (Contd.)

▪ A reservation request comes for the reservation, say Request A.


▪ Processing of Request A starts.
▪ While process Request A, many new reservation request comes, say
Request B, Request C and so on.
▪ The priority to the requests are given on the first come first basis.
▪ Now, the problem is:
– How to recognize which request came first and so on?
What can be done to avoid such
problems?
Different Types of Data Structure (Contd.)

▪ As the request comes:


– Start storing or arranging the request one behind the other.
– Once one request is processed take the other request that is at the front.
– Repeat the process once till the last request.
▪ This helps you to do first come first serve.
▪ Thus, Queue is the best suitable data structure for implementing the
online Railway Reservation system.
Activity 1- Types of Data Structure

▪ Stating the reason, identify the data structure to be used in the following
situations:
– Program X calls a subprogram Y, which calls the subprogram Z, and so on.
– An Elevator
Solution to Activity 1
Solution to Activity 1- Types of Data Structure

▪ Stack
▪ Queue
Different Types of Data Structure (Contd.)

▪ Depending upon the implementation of data structure, they can be


classified as:
– Static
– Dynamic
Activity 2 - Static Data Structure

▪ Stating an example:
– Explain how array is a static data structure.
– Explain how linked list is a dynamic data structure.
Solution to Activity 1
Solution to Activity 2 - Static Data Structure

▪ Suppose you declare an array of size 50, but store only 5 elements in it; the
memory space allocated for the remaining 45 elements will be wasted.
Similarly, if you have declared an array of size 50 but later on want to store
20 more elements, you will not be able to store these extra required
elements because of the fixed size of an array.
▪ An example of a dynamic data structure would be a list of items for which
memory is not allocated in advance. As and when items are added to the
list, memory is allocated for those elements. Similarly, when items are
removed from the list, memory allocated to those elements is deallocated.
Such a list is called a linked list.
Summary

▪ In this module, you learned that:


– Arranging data or organization of data before performing any task can be
referred as Data Structure.
– The appropriate usage of data structure allows us to overcome the following
programming challenges:
• Simplifying complex problems
• Creating standard, reusable code components
• Creating programs that are easy to understand and maintain
– The various type of data structure are:
• Arrays
• Linked List
• Stacks
• Queues
• Trees
• Graphs
Summary (Contd.)

– Data structures can be classified under the following two categories:


• Static
• Dynamic
Module 2: Problem Solving Using Linked List
Objectives

▪ At the end of this module, you will be able to:


– Understand the need of linked list
– Use doubly-linked list
– Use circular linked list
– Perform linked list operations
– Perform sorting and searching in linked list

Duration 3hrs
Module Overview

▪ A list is a set of items that are organized sequentially.


▪ List are commonly implemented in programs by using arrays.
▪ However, there are certain limitations associated with the use of arrays in
programs.
▪ Thus, to overcome these limitations we can implement a list as a linked
list.
▪ In this module, we will discuss how linked lists overcome the limitations
imposed by arrays and the various application areas of linked lists.
▪ In addition, we will be discussing the usage of various variants of linked list
that were introduced to improve the efficiency of a linked list.
Why Linked List?
Understanding the Need of Linked List

▪ Consider a scenario:
– You have been provided a database of a University containing the details of
two lakh students.You need to write a program to generate and display the
details of the Delhi based students from the given database.
▪ What if we use an array to accomplish the desired task?
– If you use array to store the details, the size of the array needs to be declared
in advance.
– However, the number of Delhi based student is not known in advance.
Therefore, to store the details of all the Delhi based students, you will have to
declare an array of an arbitrarily large size.
– In the worst case, you would declare an array of size two lacs. For instance,
you declared an array of size N.
– Now, if the number of Delhi based students is more than N, all Delhi based
student’s details cannot be stored.
– Similarly, if the number of Delhi based students is less than N, a lot of memory
space is wasted.
– Therefore, you cannot use an array for the preceding scenario.
Understanding the Need of Linked List
(Contd.)
▪ So, what will you do in such a scenario?
– To solve preceding or similar kind of problems, you can use a dynamic data
structure that does not require you to specify the size in advance, and allows
memory to be allocated as and when it is required.
– An example of such a data structure is a linked list.
Understanding the Need of Linked List
(Contd.)
▪ Linked list is a flexible data structure that provides a convenient way to
store data.
▪ You do not have to specify the size of the list in advance.
▪ Memory is allocated dynamically.
What are the application areas of
a Linked List?
Understanding the Need of Linked List
(Contd.)
▪ Linked lists offer various applications:
– They form the basis of various other data structures such as stacks, queues,
and binary trees.
– They are used in various gaming applications.
– They are used to implement internals of file system in various operating
systems.
– They offer a simple and convenient mechanism to perform various arithmetic
operations on polynomial expressions.
Understanding the Need of Linked List
(Contd.)
▪ A linked list is a chain of nodes in which each node consists of data as well
as a link to the next node.
▪ Depending upon how the various nodes are connected to each other, the
behavior of the linked list changes and thus, it is classified into the
following variants:

– Single-Linked List:

– Doubly-Linked List:

– Circular Linked List:


Activity 1- Array or Linked List?

▪ Consider the following scenario:


– In a DVD library, as the DVDs are reorganized, new DVDs are purchased and
inserted according to their Media Identification (MID) numbers and old DVDs
are replaced with new versions with different MID numbers.
– This requires frequent insertion and deletion of records.
▪ Identify in which of the following situations, you will use array and linked
list respectively:
– Sorting the details of DVDs.
– Retrieving the details of any DVD on the basis of its MID number.
Solution to Activity 1
Solution to Activity 1- Array or Linked List?

▪ Solution:
– For sorting the details of DVDs, it is better to use a linked list because
insertion and deletion is faster in linked lists as compared to arrays.
– To retrieve the details of any book on the basis of its MID number, arrays
would be a good choice. This is because, unlike linked lists, arrays allow both
sequential and random access.
Why Doubly-Linked List?
Using Doubly-Linked List

▪ Consider a scenario:
– You need to develop an application for the Cricket Board, to store the
personal details and scores till date, of all the cricketers playing in World Cup
2011 respectively.
– In addition, application should be able to display the scores in both ascending
and descending order.
▪ Identify which data structure will you use to solve the preceding problem
and why?
Using Doubly-Linked List (Contd.)

▪ To display the score of the crickets in the ascending order, you can simply
traverse the list starting from the first node.
▪ Now consider another case where you need to display these scores in a
descending order.
▪ This problem could be easily solved if you could traverse the list in the
reverse direction.
▪ However, because each node in a singly-linked list contains the address of
the next node in sequence, traversal is possible in the forward direction
only.
▪ To solve this problem, each node in a linked list can be made to hold the
reference of its preceding node in addition to its next node in sequence.
▪ Such type of linked list is known as doubly-linked list. In a doubly-linked list,
each node contains the address of its next node as well as its previous
node.
▪ This allows the flexibility to traverse in both directions.
Where else can we use
Doubly-Linked List?
Using Doubly-Linked List (Contd.)

▪ Situations using doubly-linked list:


– Applications that have an MRU list (a linked list of file names)
– The cache in your browser that allows you to hit the BACK button (a linked
list of URLs)
– Undo functionality in Photoshop or Word (a linked list of state)
How does the representation of
a node in a doubly-linked list
differ from that in a singly-linked
list?
Using Doubly-Linked List (Contd.)

▪ Unlike singly-linked list, in which each node stores the address of only the
next node in the list, each node in a doubly-linked list holds the address of
its previous node also.
Why Circular Linked List?
Using a Circular Linked List

▪ Consider a scenario:
– You need to develop a game in which the players are given a set of N number
of balls.
– Each ball appears on the screen after a specific time period.
– The player is required to select the ball within 10 seconds or else the ball
becomes unusable.
– Once the Nth ball is displayed, the ball that came first is displayed again, and
the sequence continues as before.
▪ Which data structure will you use to implement the preceding
requirements?
Using a Circular Linked List (Contd.)

▪ You can store the references of these balls in a single-linked list.


▪ Now, when the last ball is displayed, the pointer needs to be shifted back
to the first ball in the list.
▪ In a singly-linked list, once you reach the end of the list, you cannot move
further.
▪ Therefore to move back to the first ball, you need to reinitialize the
variable or pointer to the first node in the list.
▪ Therefore, a better approach is to link the last node with the first node in
the list.
▪ By doing so, you do not have to reinitialize the variable or pointer every
time you reach the end of the list.
▪ Such a type of list is known as a circular linked list.
Where else can we use Circular
Linked List?
Using a Circular Linked List (Contd.)

▪ Circular linked lists:


– Are usually sorted.
– Are useful for playing video and sound files in looping mode.
How circular linked List is
different from singly-linked list?
Using a Circular Linked List (Contd.)

▪ In a singly-linked list, the last node points to NULL. However, in


circular linked list, the last node point to the first node of the list
forming a circular structure.
Can a doubly-linked list be made
circular?
Using a Circular Linked List (Contd.)

▪ Yes, a doubly-linked list can be made circular by:


– Assigning the address of the first node in the next field of the last node.
– Assigning the address of the last node in the prev field of the first node.
Activity 2 - Implementing Circular Linked
List
▪ Consider a scenario:
– You have to design a scheduling technique in Operating System. In scheduling,
there will be number of jobs request coming to the Operating System like
Job1, Job2, job3, job4, job5, ... Job 10. The Operating System performs the
jobs concurrently using a technique called round robin scheduling.
– Here each job will be executed for a few nano seconds and then while taking
up the other job it see’s that all the jobs are executed simultaneously until
the respective job is completed.
▪ How will the Operating System come to know that which is the first job,
which is the second job, and which is the last job?
▪ How will it come back to the first job after the last job?
▪ Write an algorithm to implement it.
Solution to Activity 2
Solution to Activity 2 - Implementing
Circular Linked List
▪ Here the job needs to be organized with Circular Linked list:
– job1 will hold the address of job2
– job2 will hold the address of job3
– .............
– ………
– job9 will hold the address of job10
– job10 will hold the address of job1
▪ Now the OS will take the job1.
▪ Job1 will link to job2.
▪ Job10 will link to job1.
▪ This helps the Scheduling in a smooth way.
Solution to Activity 2 - Implementing
Circular Linked List (Contd.)
▪ The following algorithm is used to implement the scheduling:
Begin
Intialize first,last request to null
Read new Request
If there is a request
if it is first request
allocate node and store the request
first -> address of node
last -> address of node
else
allocate node and store the request
link last to new node
store the add of First in the new node
store the new address in the last
endif
else
Solution to Activity 2 - Implementing
Circular Linked List (Contd.)
Take the request and start processing
repeat the processing taking the address of next node
this goes in cyclic order.
Endif
End
Performing Linked List Operations

▪ The various operations implemented on linked lists are:


– Traversing
– Insertion
– Deletion
– Search
Performing Linked List Operations (Contd.)

▪ Consider a scenario:
– A program has been developed for recording the daily financial transaction at
FIN Bank by using the linked list.
▪ Consider the following table for SB transactions:

▪ The data in the preceding table is in a linked list manner.


▪ Observe Record # 01recorded for A/c no. 001.
▪ It is holding the address of other record so that we can travel transactions
held for A/c no. 001 very easily, that is from record 01 → record 04 →
record 07.
Performing Linked List Operations (Contd.)

▪ After recording, you realized that you have forgot to insert the transaction
held on 2/1/11 for the A/c No. 001.
▪ Now, you have to insert the transaction at the proper position.
▪ Therefore, to insert the transaction you have to push down all the records
from 3/1/11 and insert the transaction held on 2/1/11.
▪ But is there are lakhs of record available, it becomes very risky and may
cause damage to the hard disk.
▪ Now, the question is how to over come such a problem.
Performing Linked List Operations (Contd.)

▪ The best solution to such a problem is to use the insert node technique of
the linked list, i.e.:
1. Add record at bottom.
2. Take address of the new record.
3. Store the address in transaction of1/1/11.
4. Take the address that was earlier stored in 1/1/11.
5. Add it to the new record
Performing Linked List Operations (Contd.)

▪ After performing the preceding tasks, the table for the SB transaction
looks like:

▪ Now, if you travel the transaction for the A/c No. 001 it is:
– Record 01 → Record 10 → Record 04 → Record 07
▪ So the record will get inserted with pushing down the other transaction
or any physical damage.
Performing Linked List Operations (Contd.)

▪ Now, you want to delete a transaction held on 4/1/11 for the A/c No. 001.
▪ The problem to perform the deletion is that you have to push up all the
records recording after this transaction (4/1/11 for A/c No. 001), which
may cause a physical damage.
Performing Linked List Operations (Contd.)

▪ Thus, the linked list node deletion technique is best suitable in such
scenarios.
– Take the address for Record 07 (record no. for the transaction held
on 4/1/11)
– Go to its previous record that is Record 10.
– Here substitute the address.
Performing Linked List Operations (Contd.)

▪ After performing swapping, the table for the SB transaction looks like:

▪ Now if you travel transactions held for the A/c no. 001 it is:
– Record 01 → Record 10 → Record →07
▪ So record will get deleted with pushing up other transaction or any
physical damage
Now let us visit the algorithms
for performing various
operations on linked list.
Traversing a Linked List

▪ Traversing a linked list refers to the process of visiting each node of the list
starting from the beginning.
– Singly-linked lists allow traversal only in one direction.
– A doubly-linked list enables you to traverse the list in forward as well as
backward direction.
– In Circular linked list, you can traverse the list until the last node is reached.
Traversing a Singly-Linked List

▪ The following algorithm is used to traverse a singly-linked list:


1. Make currentNode point to the first node in the list.
2. Repeat step 3 and 4 until currentNode becomes NULL.
3. Display the information contained in the node marked as currentNode.
4. Make currentNode point to the next node in sequence.
Activity 3 -Traversing a Doubly-Linked List

▪ Write an algorithm to traverse a doubly-linked list.


Solution to Activity 3
Solution to Activity 3 -Traversing a Doubly-
Linked List (Contd.)
▪ A doubly-linked list enables you to traverse the list in forward as well as
backward direction.
– The algorithm for traversing a doubly-linked list in the forward direction is:
– Mark the first node in the list as currentNode.
– Repeat steps 3 and 4 until currentNode becomes NULL.
– Display the information contained in the node marked as currentNode.
– Make currentNode point to the next node in sequence.
▪ The algorithm for traversing a doubly-linked list in the backward direction
is:
– Mark the last node in the list as currentNode.
– Repeat steps 3 and 4 until currentNode becomes NULL.
– Display the information contained in the node marked as currentNode.
– Make currentNode point to the node preceding it.
– Write an algorithm to traverse a doubly-linked list.
Traversing a Circular Linked List

▪ The following algorithm is used to traverse a circular-linked list:


1. Make currentNode point to the successor of the node marked as LAST, such
that currentNode points to the first node in the list.
2. Repeat step 3 and 4 until currentNode = LAST.
3. Display the information contained in the node marked as currentNode.
4. Make currentNode point to the next node in its sequence.
5. Display the information contained in the node marked as LAST.
Inserting a Node in a Singly-Linked List

▪ Insertion in a singly-linked list refers to the process of adding a new node


in the list or creating a new linked list if one does not already exist.
▪ Therefore, to insert a node in a linked list, you need to first check whether
the list is empty or not.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ If the linked list is empty, the following algorithm can be used to insert a
node in the linked list:
1. Allocate memory for the new node.
2. Assign a value to the data field of the new node.
3. Make the next field of the new node point to NULL.
4. Make START point to the new node.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ If the linked list is not empty, you may need to insert a node at any of the
following positions in the list:
1. Beginning of the list
2. End of the list
3. Between two nodes in the list
Inserting a Node in a Singly-Linked List
(Contd.)
▪ The place where you insert an element in the list would depend on the
problem at hand.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ Inserting a node at the end of the list:
– If you had to write a program to generate and store a list of prime numbers
between 1 and 10,00,000, and then display them in the same order in which
they were generated, you would insert all nodes at the end of the list.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ To insert a node at the end of the linked list, you can use the following
algorithm:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. If START is NULL, then:
4. Make START point to the new node.
5. Go to step 6.
6. Locate the last node in the list, and mark it as currentNode. To locate the last
node in the list, execute the following steps:
7. Mark the first node as currentNode.
8. Repeat step c until the successor of currentNode becomes NULL.
9. Make currentNode point to the next node in sequence.
10. Make the next field of currentNode point to the new node.
11. Make the next field of the new node point to NULL.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ Inserting a node at the beginning of the list:
– If you had to write a program to generate and store a list of prime numbers
between 1 and 10,00,000, and then display them in the reverse order, you
would insert all nodes in the beginning of the list.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ To insert a node at the beginning of the linked list, you can use the
following algorithm:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. Make the next field of the new node point to the first node in the list.
4. Make START point to the new node.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ Inserting a node at any position in the list:
– Consider that you are given a list of student records that need to be stored in
the ascending order of their marks. In this case, you may need to insert a new
record at any position in the list, including the beginning of the list, end of the
list, or between two nodes in the list.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ Inserting a node between two nodes in a list:
– Consider that you have to store a set of student records in the increasing
order of their marks.
– In such a situation, you may need to insert the new node at any position in the
linked list.
Inserting a Node in a Singly-Linked List
(Contd.)
▪ The algorithm for inserting a node between two nodes in a singly-linked
list is as follows:
1. Identify the nodes between which the new node is to be inserted. Mark them
as previous and current. To locate previous and current, execute the following
steps:
a. Make current point to the first node.
b. Make previous point to NULL.
c. Repeat step d and step e until current.info becomes greater than newnode.info or
current becomes equal to NULL.
d. Make previous point to current.
e. Make current point to the next node in sequence.
2. Allocate memory for the new node.
3. Assign value to the data field of the new node.
4. Make the next field of the new node point to current.
5. Make the next field of previous point to the new node.
Activity 4 - Inserting a Node in a
Singly-Linked List
▪ Consider the linked list, as shown in the following figure.

▪ Write an algorithm to insert 16 in the given linked list.


Solution to Activity 4
Solution to Activity 4 - Inserting a Node in a
Singly-Linked List
▪ The following is an algorithm to insert 16 in the given linked list:
– Identify the nodes between which the new node is to be inserted. Mark them
as previous and current.

– Allocate memory and assign value to the data field of the new node.
Solution to Activity 4 - Inserting a Node in a
Singly-Linked List (Contd.)
▪ The following is an algorithm to insert 16 in the given linked list:
– Make the next field of new node point to current.

– Make the next field of previous point to the new node.


Inserting a Node in a Doubly-Linked List

▪ Insertion involves adding a new node to an existing list or creating a new


list if one does not already exist.
▪ Therefore, to insert a node in a doubly-linked list you need to first check
whether the list is empty or not.
▪ If the list is empty, the following algorithm can be used to insert a node in
the linked list:
1. Allocate memory for the new node.
2. Assign a value to the data field of the new node.
3. Make the next field of the new node point to NULL.
4. Make the prev field of the new node point to NULL.
5. Make START point to the new node.
▪ Once the first node is inserted, subsequent nodes can be inserted at any
of the following positions:
– Beginning of the list
– Between two nodes in the list
– End of the list
Inserting a Node in a Doubly-Linked List
(Contd.)
▪ Inserting a Node at the Beginning of the List:
– The algorithm for inserting a node in the beginning of the doubly-linked list is:
a. Allocate memory for the new node.
b. Assign value to the data field of the new node.
c. Make the next field of the new node point to the first node in the list.
d. Make the prev field of START point to the new node.
e. Make the prev field of the new node point to NULL.
f. Make START point to the new node.
Inserting a Node in a Doubly-Linked List
(Contd.)
▪ Inserting a Node at the End of the List:
– The algorithm for inserting a node in the end of the doubly-linked list is:
a. Allocate memory for the new node.
b. Assign value to the data field of the new node.
c. Make the next field of the node marked as LAST point to the new node.
d. Make the prev field of new node point to node marked LAST.
e. Make the next field of the new node point to NULL.
f. Mark the new node as LAST.
Activity 5 - Inserting a Node in a
Doubly-Linked List
▪ Write an algorithm to insert a node between two node in a doubly-linked
list.
Solution to Activity 5
Solution to Activity 5 - Inserting a Node in a
Doubly-Linked List
▪ To insert a node between two nodes, you first need to search the nodes
between which the new node is to be inserted, and mark them as previous
and current. The algorithm for inserting a node between two nodes in a
doubly-linked list is:
1. Identify the nodes between which the new node is to be inserted. Mark them
as previous and current respectively. To locate previous and current, execute
the following steps:
a. Make current point to the first node.
b. Make previous point to NULL.
c. Repeat step d and step e until current.info > newnode.info or current = NULL.
d. Make previous point to current.
e. Make current point to the next node in sequence.
2. Allocate memory for the new node.
3. Assign value to the data field of the new node.
4. Make the next field of the new node point to current.
5. Make the prev field of the new node point to previous.
Solution to Activity 5 - Inserting a Node in a
Doubly-Linked List (Contd.)
6. Make the prev field of current point to the new node.
7. Make the next field of previous point to the new node.
Inserting a Node in a Circular Linked List

▪ Insertion in a circular linked list refers to the process of adding a new


node in the list or creating a new linked list if one does not already exist.
▪ Therefore, to insert a node in a circular linked list, you need to first check
whether the list is empty or not.
Activity 6: Inserting a Node in a Circular
Linked List
▪ Write an algorithm to insert a node between two nodes in the circular
linked list.
Solution to Activity 6
Solution to Activity 6: Inserting a Node in a
Circular Linked List
▪ The following algorithm is used to insert a node between two nodes in a
circular linked list:
1. Identify the nodes between which the new node is to be inserted. Mark them
as previous and current. To locate previous and current, execute the following
steps:
a. Make current point to the first node.
b. Make previous point to NULL.
c. Repeat step d and step e until current.info > newnode.info or previous = LAST.
d. Make previous point to current.
e. Make current point to the next node in sequence.
2. Allocate memory for the new node.
3. Assign value to the data field of the new node.
4. Make the next field of the new node point to current.
5. Make the next field of the previous point to the new node.
Deleting a Node from a Singly-Linked List

▪ The following algorithm is used to delete a node from the beginning of the
list:
1. The algorithm to delete a node from the beginning of the list is as follows:
2. Mark the first node in the list as current.
3. Make START point to the next node in its sequence.
4. Release the memory for the node marked as current.
Deleting a Node from a Singly-Linked List

▪ The following algorithm is used to delete a node between two nodes in


the list:
1. To delete a node between two nodes in the list, you first need to search the
node to be deleted. The algorithm to delete a node between two nodes in the
list is:
2. Locate the node to be deleted. Mark the node to be deleted as current and
its predecessor as previous. To locate current and previous, execute the
following steps:
a. Set previous = START.
b. Set current = START.
c. Repeat steps d and e until either the node is found or current becomes NULL.
d. Make previous point to current.
e. Make current point to the next node in sequence.
3. Make the next field of previous point to the successor of current.
4. Release the memory for the node marked as current.
Activity 7: Deleting a Node from a
Doubly-Linked List
▪ Write an algorithm to delete a node from the middle of a doubly-linked
list.
Solution to Activity 7
Solution to Activity 7: Deleting a Node from
a Doubly-Linked List
▪ The following algorithm is used to delete a node from the middle of a
doubly-linked list:
1. Mark the node to be deleted as current and its predecessor as previous. To
locate previous and current, execute the following steps:
a. Make previous point to NULL. // Set previous = NULL
b. Make current point to the first node in the linked list. // Set current = START
c. Repeat steps d and e until either the node is found or current becomes NULL.
d. Make previous point to current.
e. Make current point to the next node in sequence.
2. Make the next field of previous point to the successor of current.
3. Make the prev field of the successor of current point to previous.
4. Release the memory of the node marked as current.
Deleting a Node from a Circular Linked List

▪ The following algorithm is used to delete a node from the beginning of the
list:
1. If the node to be deleted is the only node in the list:
a. Mark LAST as NULL
b. Exit
2. Make current point to the successor of LAST.
3. Release the memory of the node marked as current.
Activity 8 - Deleting a Node from a Circular
Linked List
▪ Write an algorithm to delete a node between two nodes in a circular
linked list.
Solution to Activity 8
Solution to Activity 8 - Deleting a Node
from a Circular Linked List
▪ The following algorithm is used to delete a node between two nodes in a
circular linked list:
1. Locate the node to be deleted. Mark the node to be deleted as current and
its predecessor as previous. To locate previous and current, execute the
following steps:
a. Make previous point to the successor of LAST.
b. Make current point to the successor of LAST.
c. Repeat steps d and e until either the node is found or previous = LAST.
d. Make previous point to current.
e. Make current point to the next node in sequence.
2. If previous = LAST
a. Display “NODE NOT FOUND”
b. Go to Step 5
3. Make the next field of previous point to the successor of current.
4. Release the memory of the node marked as current.
5. Exit.
Searching and Sorting in a Linked List

▪ Till now we have learned the following two searching techniques:


– Linear
– Binary
▪ As per the behavior of the preceding search techniques, the binary search
technique cannot be implemented on a sorted linked list (As there is no
way of indexing the middle element in the list.).
▪ So if you are sure that the given list is sorted, than you can perform the
binary search.
▪ Otherwise, you have to use linear search.
▪ Other option is that you first sort the list and then perform the search
operation.
Activity 9 - Performing Search on a Sorted
Linked List

▪ Consider a scenario:
– Let us assume that the data in LIST is sorted. We need to search for ELEMENT
in LIST by traversing the list using a pointer variable P and comparing the
ELEMENT with the contents INFO[P].
▪ Write an algorithm to perform a search on a sorted linked list LIST.
Solution to Activity 9
Solution to Activity 9 - Performing Search on
a Sorted Linked List
▪ SRCH(INFO, LINK, START, ELEMENT, LOCATION) The LIST is a sorted list.
The following algorithm finds the location (LOCATION) of the node where
ELEMENT first appears in the LIST, or sets LOCATION = NULL.
1. Set P: = START.
2. Repeat Step 3 while PTR ≠ NULL:
3. If ELEMENT<INFO[P], then:
Set P: = LINK[P]. //P now points to next node.
Else if ELEMENT = INFO[P], then:
Set LOCATION: = P, and Exit. // Search is successful.
Else:
Set LOCATION: = NULL, and Exit. // ELEMENT now exceeds INFO[P]
[End of If Structure]
[End of Step 2 Loop]
4. Set LOCATION: = NULL.
5. Exit.
Searching and Sorting in a Linked List

▪ Linked list can be used to implement various arithmetic operations on


polynomials.
▪ Sorting is an essential requirement for performing arithmetic operations
on polynomials represented as linked lists.
Activity 10 - Implementing Sorting in a
Linked List
▪ Write a pseudocode to add the following two polynomials:
– Polynomial 1: 4x5 + 5x4 + 2x3 + 3x2 + 7x
– Polynomial 2: 9x6+6x4+3x2
▪ The following figure shows the linked list representation of the two
polynomials.
Solution to Activity 10
Solution to Activity 10 - Implementing
Sorting in a Linked List
▪ To view the solution, click on the following embedded document:
Summary

▪ In this module, you learned that:


– In a singly-linked list, each node contains:
• The information
• The address of the next node in the list
– Singly-linked list can be traversed only in one direction.
– Insertion and deletion in a linked list is fast as compared to arrays. However,
accessing elements is faster in arrays as compared to linked lists.
– Linked lists offer various applications. For example:
• They form the basis of various other data structures such as stacks, queues, and
binary trees.
• They are used in various gaming applications.
• They are used to implement internals of file system in various operating systems.
• They offer a simple and convenient mechanism to perform various arithmetic
operations on polynomial expressions.
Summary (Contd.)

– In a doubly-linked list, each node needs to store:


• The information
• The address of the next node in sequence
• The address of the previous node
– Doubly-linked list enables you to traverse the list in forward as well as
backward direction.
– A singly-linked list can be made circular by making the last node in the list
point back to the first node in the list.
Module 3 - Problem Solving Using Stacks
Objectives

▪ At the end of the module, you will be able to:


– Understand the need of stack
– Perform operations on stack
– Use stack in various applications
– Perform searching and sorting in stack

Duration 3hrs
Module Overview

▪ In many scenarios, you would require to maintain a list of items. Consider


a situation where you need to maintain a list of employees in ascending
order of their names.
▪ To maintain such a list, you might need to insert or delete any records as
prompted by the user.
▪ However, there can be situations where you want to implement a list in
such a way that allows items to be inserted or deleted at one end of the
list only.
▪ This kind of list can be implemented by using a stack.
▪ In this session, we will discuss the need of stack, the various operations to
be performed on stack, and how stack is used to resolve the business
cases.
▪ In addition, we will discuss how to implement searching and sorting
techniques on a stack.
Understanding the Need of Stack

▪ Let’s have a look on the rules followed to play the most famous card game
Rummy:
– To start the game, a pile of 52 cards is divided into two piles:
• A stock pile
• A discard pile
– Both the piles, are kept in the center.
– The player 1 can draw the topmost card from any of the piles (stock or
discard).
– If the drawn card does not make a valid sequence in the player’s hand, the
player can discard the card by placing it on the top of the discard pile.
– Now, the player 2 has to draw a card.
– The player 2 can draw the topmost card from any of the piles, and so on.
Now what will you do to
represent and manipulate such
type of a discard pile in a
computer program?
Understanding the Need of Stack (Contd.)

▪ To represent and manipulate such type of a discard pile in a computer


program:
– You need a data structure that allows insertion and deletion at only one end,
the top most.
– The data structure should ensure that the last item inserted is the first one to
be removed.
▪ A data structure that implements this concept is called a stack.
Understanding the Need of Stack (Contd.)

▪ Stack is a collection of data items that can be accessed at only from the
top.
▪ It is called a Last-In-First-Out (LIFO) data structure.
▪ It is like an empty box containing CDs, which is just wide enough to hold
the CDs in one pile.
▪ The CDs can be placed as well as removed only from the top of the box.
▪ The CD most recently added to the pile is the first one to be taken out.
▪ The CD at the bottom is the first to be put inside the box and the last one
to be taken out.
What are the application areas
of a Stack?
Understanding the Need of Stack (Contd.)

▪ Stack offer various applications:


– Implementing function calls
– Checking the nesting of parenthesis in an expression
– Evaluating expressions
Operations on Stack

▪ The following two basic operations can be performed on a stack:


– PUSH:
• It refers to insertion.
– POP
• It refers to deletion.
Operations on Stack (Contd.)

▪ Consider an example of pile of bricks:


– You need to perform the following operations:
• PUSH brick 1 into an empty stack
• PUSH brick 2 into the stack
• POP a brick from the stack
• PUSH brick 3 into the stack
• PUSH brick 4 into the stack
• POP a brick from the stack
Let us see how PUSH and POP
operations are performed on a
pile of bricks.
Operations on Stack (Contd.)
Activity 1 - PUSH Operation on a Stack

▪ Write a pseudocode for the PUSH operation on a Stack.


Solution to Activity 1
Solution to Activity 1- PUSH Operation on a
Stack
▪ To implement the PUSH operation, you need to insert a node at the
beginning of the linked list. The algorithm for PUSH operation is:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. Make the next field of the new node point to top.
4. Make top point to the new node.
Activity 2 - POP Operation on a Stack

▪ Write a pseudocode for the POP operation on a Stack.


Solution to Activity 2
Solution to Activity 2 – POP Operation on a
Stack

▪ To implement the POP operation, you need to delete a node from the
beginning of the linked list. The algorithm for the POP operation is:
1. Make a variable/pointer tmp point to the topmost node.
2. Retrieve the value contained in the topmost node.
3. Make top point to the next node in sequence.
4. Release memory allocated to the node marked by tmp.
Using Stack

▪ Consider a scenario:
– In a medical store, the store keeper has maintained a pile of medicine boxes.
– The pile has been created according to the expiry days left.
– The medicine with least expiry days left are kept at the top.
– So, that the medicine with least expiry days can be issued first.
▪ Identify which data structure will you use for such data organization and
Why?
Using Stack (Contd.)

▪ A Stack is the best suitable data structure for the preceding scenario.
▪ Elements in stack are deleted on a LIFO basis.
▪ So, the medicine kept on the top will be used (delete) first.
(The medicines with least expiry days left are kept at the top and they
should be used first. )
Using Stack (Contd.)

▪ Stacks help in the conversion of a decimal number (base 10) to an


equivalent number in any other base.
▪ Consider an example:
– You need to convert the decimal number 24 into a binary number with
base 2.
Let us see how stack is used in
conversion of number base.
Using Stack (Contd.)

▪ The decimal number is divided by base 2, an then repeatedly dividing the


quotient of the division by 2 until a zero quotient is obtained.
▪ The remainders after each division are stored in a stack.
▪ Once the zero quotient is obtained, you need to pop the remainders one
by one to get the remainders in the reverse order.
▪ The following table represents the conversion process.
Where else the LIFO principle of
Stack is used?
Using Stack (Contd.)

▪ The following are the scenarios where LIFO principle of Stack is followed:
– When a person wear bangles the last bangle worn is the first one to be
removed and the first bangle would be the last to be removed.
– In a stack of plates, once can take out the plate from top or can keep plate at
the top. The plate that was placed first would be the last to take out.
– Batteries in the flashlight:
• You cant remove the second battery unless you remove the last in. So the battery
that was put in first would be the last one to take out. This follows the LIFO
principle of stack.
– Cars in a garage:
• In order to take out the car that was parked first you need to take out the car that
was parked last. So the car that was parked first would be the last to take out.
Sorting and Searching in a Stack

▪ A Stack works on the principle of LIFO.


▪ Thus, by sorting a stack it will be like going against its principle.
▪ Therefore, sorting in not recommended on a Stack.
Sorting and Searching in a Stack

▪ Stack acts as a one-way list.


▪ Therefore, one must perform a linear search on the queue.
Activity 3 - Searching in a Stack

▪ Write an algorithm to search a CD ID in a stack of CDs.


Solution to Activity 3
Solution to Activity 3 - Searching in a Stack

▪ The algorithm to search in a stack for a CD ID is:


1. Read the CD ID to be searched
2. Set i = 0
3. Repeat step 4 until i > n or arr[i] = CD ID
4. Increment i by 1
5. If i > n:
6. Display “Not Found”
7. Else
8. Display “Found”
Summary

▪ In this module, you learned that:


– A stack is a collection of data items that can be accessed at only one end.
– A stack is called a LIFO structure.
– The two basic operations that can be performed on stack are:
• PUSH
• POP
– Stacks are used in many applications. Some of the applications domains are:
• Implementing function calls
• Conversion of number bases
• Checking the nesting of parenthesis in an expression
• Evaluation expression
– Sorting is not recommended on a Stack as it violates its LIFO principle.
– Linear search is performed on a Stack.
© Problem Solving using Queue,
Do’s and Don’ts in
Programming and Problem
Solving Techniques
Agenda

1 Problem Solving Using Queue 3hrs

2 Do’s and Don’ts in Programming 2hrs

3 Problem Solving Technique 3hrs


Module 1: Problem Solving Using Queue
Module Overview

▪ In many scenarios, you would like to retrieve the items in the same order
in which they arrive.
▪ This means on the first come first basis.
▪ This kind of list can be implemented using queue.
▪ Queue provides a lot of practical applications in various fields such as
networking and internal working of computer systems.
▪ In this module, we will discuss the need of queue, various operations that
can be performed on queue, and various types of queue.
▪ In addition, we will discuss how to perform the searching and sorting on
queue.
Objectives

▪ At the end of this module, you will be able to:


– Understand the need of queue
– Perform operations on a queue
– Identify and use the different types of queue
– Perform searching and sorting in a queue

Duration 3hrs
Understanding the Need of Queue

▪ Consider a scenario of Metro Railways:


– The one way journey tokens are valid only on the day of purchase.
– In addition, its validity depends upon the time.
– For example, if the distance covered is 3 kms then the validity of the token is
20 mins.
– As the token is punched to enter the Metro Railway platform, the time is
recorded for that particular token.
▪ Let us assume that at 10:40 a.m. 5 tokens for the same destination were
issued to 5 passengers respectively.
▪ Now, as the passengers punch the token, the time is recorded for each
token respectively.
▪ The token punched first will be expired first.
Now, which data structure will you
use to record the status of the
token?
Understanding the Need of Queue (Contd.)

▪ To record the status of the token, you need a data structure that:
– Allows insertion at one end and deletion from the another end.
– Ensures that the first item inserted is the first one to be removed.
▪ A data structure that implements this concept is called a queue.
Understanding the Need of Queue (Contd.)

▪ A queue is a list of elements.


▪ It is called a Last-In-First-Out (LIFO) data structure.
▪ In a queue, the end at which:
- Elements are inserted is called the rear.
- Elements are deleted is called front.
▪ The following figure represents the structure of a queue.
Understanding the Need of Queue (Contd.)

▪ A queue can be implemented by using any one of the following:


– Array
– Linked List
Understanding the Need of Queue (Contd.)

▪ You should implement a queue using an array only if you are sure about
the maximum number of elements in the queue.
▪ Consider a scenario:
– MOVS cinemas have 50 seats in their GOLD CLASS section , starting from
seat numbers S1-S50.
– The following figure represent the sitting arrangement of the GOLD CLASS.

– You have to design an online Ticket Booking System for the GOLD CLASS for
MOVS cinemas such that the system automatically takes the booking on the
first come first basis.
– You need to ensure that it can accept only 50 bookings for GOLD CLASS.
Understanding the Need of Queue (Contd.)

▪ In the preceding scenario, we are aware of the total number of seats .


▪ In addition, we want to allocate the seat numbers on the first come first
basis.
▪ Therefore, the queue data structure using an array is best suitable.
Understanding the Need of Queue (Contd.)

▪ You should implement a queue using a linked list if you are not sure about
the maximum number of elements in the queue.
▪ Consider a scenario:
– At a radio show, the RJ announced the distribution of a free pass for a couple
holiday voucher worth rupees 75,000/- from ENJY Holidays.
– But the condition is, that the pass will be allocated to the first caller only.
▪ In the preceding scenario, you are not sure about how many listeners will
call simultaneously to get the voucher.
▪ In addition, we need to be sure that the call of the first caller should be
transferred to the RJ.
▪ Thus, in such a scenario the implementation of queue using linked list is
best suitable.
What are the application
areas of a Queue?
Understanding the Need of Stack (Contd.)

▪ Queue offers various applications:


– Printer spooling
– CPU scheduling
– Mail Service
– Elevator
– Keyboard buffering
Operations on a Queue

▪ The following two basic operations that can be performed on a queue are:
– Insert:
• It refers to the addition of an element in a queue.
• The elements are always inserted at the REAR of the queue.
• Suppose you wan to insert an element 6 in the following queue.

• After the insertion, of element 6, the 6 will become the rear end, shown in the
following figure:
Operations on a Queue (Contd.)

– Delete:
• It refers to the deletion of an element from a queue.
• The elements are always deleted from the FRONT of the queue.
• Suppose you want to perform delete operation on the following queue.

• After deletion, the 1 will become the FRONT as queue follows the First-In-First-
Out (FIFO) principle.
• The following figure represents the list after delete operation.
Let us see how insertion is
performed in a linked queue.
Operations on a Queue (Contd.)

▪ Continuing with the radio station scenario:


– You want that every new call should be added at the end of the last call:
• Call 1, Call2, Call 3,…………………………Call n.
– The insertion technique for linked queue is best suitable.
Activity 1- Performing Insertion on a Linked
Queue

▪ Write a pseudocode to insert a node at the rear end of a linked queue.


Solution to Activity 1
Solution to Activity 1 - Performing Insertion on a
Linked Queue

▪ An element is always inserted at the rear end of the queue. Therefore, you
need to insert a new node at the rear end of the linked queue. To insert a
node at the rear end of a linked queue, you can use the following
algorithm:
▪ Allocate memory for the new node.
▪ Assign value to the data field of the new node.
▪ Make the next field of the new node point to NULL.
▪ If the queue is empty, execute the following steps:
a. Make FRONT point to the new node
b. Make REAR point to the new node
c. Exit
▪ Make the next field of REAR point to the new node.
▪ Make REAR point to the new node.
Let us see how deletion is
performed in a linked queue.
Operations on a Queue (Contd.)

▪ Let us recall the scenario of radio station where the RJ has to distribute
the free holiday pass to the first caller.
▪ Now, let us assume that before the caller 1 call was transferred to the RJ,
the caller disconnected the call.
▪ In such case you want that automatically the caller 2 call should be
transferred to the RJ and so on.
▪ Thus, the delete technique used for deletion in the linked queue is best
suitable.
Activity 2 - Performing Deletion on a Linked
Queue

▪ Write a pseudocode to delete a node from the front end of a linked


queue.
Solution to Activity 2
Solution to Activity 2 - Performing Deletion on a
Linked Queue

▪ An element is always deleted from the front end of a queue.


▪ Therefore, you need to delete a node from the front end of the linked
queue.
▪ To delete a node from the front end of a linked queue, you can use the
following algorithm:
1. If the queue is empty: // FRONT = NULL
a. Display “Queue empty”
b. Exit
2. Mark the node marked FRONT as current
3. Make FRONT point to the next node in its sequence
4. Release memory for the node marked as current
Using Priority Queue

▪ Consider a scenario of the Operating System Scheduling were n number


of jobs request comes for processing.
▪ Each job has its on priority (high or low).
▪ The higher priority jobs should be processed first in comparison to the
existing tasks.
▪ But the problem is that there are different jobs with different priorities
already in a queue.
▪ Whenever a new job comes, it has to be placed according to its priority.
▪ May be that the job has to be placed in between the existing job.
▪ Now, the systems task is:
– How to detect or find the right place for the new job?
Using Priority Queue (Contd.)

▪ Thus, to solve the given scenario, the following task needs to be


followed:
– The Queue of the job has to arranged in descending order of the priority
from high to low.
– When the new job comes, identify the job priority.
– Move the lower priority job one step back.
– Place the new task in the gap
▪ All the preceding tasks can be implemented using the priority queue.
Using Priority Queue (Contd.)

▪ Priority queue is a collection of elements.


▪ Each element is assigned a priority.
▪ An element of the higher priority is processed before any element of
lower priority.
▪ Two elements with the same priority are processed according to the
order in which they were added to the queue.
Using Priority Queue (Contd.)

▪ The following algorithm is used for the priority queue:


Begin
Read the new task and its priority
Go to last
Repeat
if priority of the task in queue is less than new , than
move the task one step back (this creates a gap)
and go to next
Else
place the new task in the gap/ current position
end if
Until placement is over
End
Sorting and Searching in a Queue

▪ As Queue works on the principle of FIFO.


▪ Thus, by sorting a queue it will be like going against its principle.
▪ Therefore, sorting in not recommended on a queue.
Sorting and Searching in a Queue (Contd.)

▪ Queue acts as a one-way list.


▪ Therefore, one must perform a linear search on the queue.
Summary

▪ In this module, you learned that:


– A queue is a linear data structure in which the elements are inserted at the
rear end and deleted from the front.
– The various operations implemented on a queue are insertion and deletion.
– A queue can be implemented by using arrays or linked list.
– A queue implemented in the form of a circular array overcomes the problem
of unutilized space encountered in queues implemented by using a linear array.
– A queue implemented by using a linked list is called a linked queue.
– Queues offer large number of applications in various fields such as:
• Printer spooling
• CPU scheduling
• Mail service
• Keyboard buffering
• Elevator
Summary (Contd.)

– A priority queue is a collection of elements such that each element has been
assigned a priority.
– In a priority queue, an element of higher priority is processed before any
element of lower priority.
Module 2: Do’s and Don’ts in Programming
Objectives

▪ At the end of this module, you will be able to:


– Understand standards and guidelines
– Apply standards and guidelines
– Understand the difference between looping and recursion
– Identify scenarios applicable to time and space tradeoffs
– Identify the need of unit testing

Duration 2hrs
Why Programming
Standards ?
Understanding the Need of Programming
Standards

▪ Programming Standards, by definition is:


– A predetermined mark,
– A measure or model of quality.
– Both required and enforced
▪ Real life analogy of standards:
▪ ONLY Persons over 18 years can exercise their voting rights
▪ All Persons MUST purchase a ticket to travel by flight
▪ A Male MUST be 21 years to marry in India
▪ Standards applied to programming:
▪ Each code statement MUST end with a semicolon
▪ Class and function definitions MUST be enclosed in curly braces
▪ Variable, class, and function names CANNOT be the same as the built-in keywords
Benefits of Standards

▪ Benefits of standards:
– Improved productivity
– Code portability
– Code reusability
– Lesser defects
– Enhanced maintainability for other programmers
Criticism of Programming Standards

▪ Criticisms of standards:
– Imposition of standards removes the creative element of
programming.
– Standards force people to change their methods which are
perfectly alright as they are.
– Standards reduce productivity by forcing unnecessary actions.
– Standards do not prevent bugs.
Alternative to
Programming Standards ?
Alternative to Programming Standards

▪ Alternative to Programming standards are guidelines


▪ A Guideline:
– A directing principle that indicates the general direction that one should take
– Unlike standards, it is recommended, but not enforced
▪ Real life analogy of guidelines:
– Teachers telling students to regularly exercise for half an hour a day
– Parents telling their sons to drive slowly at night
▪ Guidelines applied to programming:
▪ There should be spaces between comments and code
▪ Variable and function naming should be meaningful
Basic Principles

▪ The fundamental purpose of these standards is to promote maintainability


of the code. This means the code must be readable, understandable,
testable and portable.
▪ The Four Cornerposts:
– Keep it simple. Break down complexity into simpler chunks. Clearly comment
necessary complexity.
– Be explicit. Avoid implicit or obscure features of the language. Say what you
mean.
– Be consistent. Use the same rules as broadly as possible.
– Minimize scope. This includes logical and visual scope. Be more explicit about
items with wider scope.
Other General Points (Contd.)

▪ Commenting:
– Keep code and comments visually separate.
– Use header comments for all files and functions. Smaller comments are ok for
smaller, private functions.
– Use block comments regularly. Use trailing comments for special items.
▪ Naming:
– Name separate words each with an initial capital (e.g. VariableName).
– Use abbreviations consistently, and document common usages (eg. 'Buf' for
buffer).
– Use two/three capitals plus underscore to show functional prefix on all global
items (functions and data) (e.g. XY_VariableName). Document prefixes used.
Other General Points (Contd.)

▪ Layout:
– Aim for one action per line.
– Use parentheses to emphasize chunks in expressions.
– Use precedence rules to guide wrapping of expressions.
▪ Usage:
– Use the appropriate construct for the appropriate situation.
– Avoid deep nesting (of statements, parentheses and structures). Aim for
normal maximum of three levels (deeper excursions should be short and
infrequent).
– Minimize use of conditional expressions.
– Don't use implicit evaluation order in equality-expressions (use separate
statements instead).
– Minimize use of comma operator.
Other General Points (Contd.)

▪ Make use of :
1. Indentation
2. White space around operators and keywords
3. Modular programming
4. Introduction section in the starting of program
5. Constructors and destructors functions
Activity 1

▪ Consider this code example


while(true)
{
//do something
if(<some condition>)
{
break;
}
}

State your opinions on this example.


Solution of Activity 1
Commenting Examples

While(!<some condition>)
{
//do something
}
Activity 2

▪ Write a pseudo code which inputs a series of characters from the


keyboard, terminated with a full-stop character, and then prints them
backwards on the screen.
Solution of Activity 2
Solution of Activity 2

---------------------------------------------------------------
Module name: Print Backward character
Developer name: John Smith
Last updated date: 11-Jan-2010
Version : 1.0
--------------------------------------------------------------
// A function to print the accepted letters in backward order
function print_backwards
{
// Initialize variable
declare character
Solution of Activity 2 (Contd.)

display “Enter a character ('.' to end program)”


accept character

if (character != '.')
{
print_backwards()
display character
}
}
Looping vs. Recursion

▪ Termination test:
– Iteration terminates when the loop-continuation condition fails.
– Recursion terminates when a base case is recognized.
▪ Infinite:
– An infinite loop occurs with iteration if the loop-continuation test never
becomes false.
– An infinite recursion occurs if the recursion step does not reduce the problem
in a manner that converges on the base case.
▪ Control structure:
– Iteration uses a repetition structure.
– Recursion uses a selection structure.
▪ Repetition:
– Iteration explicitly uses a repetition structure.
– Recursion achieves repetition through repeated method calls.
Looping vs. Recursion (Contd.)

▪ A recursive method is called with a base case. The method returns a result.
In case of complex problem, the method divides the problem into two or
more conceptual pieces: a piece that the method knows how to do and a
slightly smaller version of the original problem.
▪ To terminate, each time the recursion method calls itself with a slightly
simpler version of the original problem. The sequence of smallest problem
covers on the base case. When the method recognizes the base case, the
result is returned to the previous method call and a sequence of returns
ensures all the way up the line until the original call of the method
eventually returns the final result.
▪ Recursion repeatedly invokes the mechanism, and consequently the
overhead, of method calls. This can be expensive in both processor time
and memory space.
Activity 3

▪ Write a pseudo code for factorial using looping and recursion


techniques. Record the line of code (LOC) and time for both the
techniques.
Solution of Activity 3
Solution of Activity 3

Looping

factorial = 1
temp = n
while (temp > 0)
{
factorial = factorial * temp
temp = temp – 1
}
Print factorial
Solution of Activity 3 (Contd.)

Recursion

Factorial(n)
If n = 0, then: // Terminating condition
Return (1)
Return (n × Factorial(n – 1))
Determine the Efficiency of an Algorithm

▪ Factors which effect the efficiency of a program:


– Speed of the machine
– Compiler
– Operating system
– Programming language
– Size of the input
▪ Additional factors:
– The way data of a program is organized
– The algorithm used to solve the problem
▪ When there are several different ways to organize data and devise
algorithms, it becomes important to develop criteria to recommend a
choice. Therefore, you need to study the behavior of algorithms under
various conditions and compare their efficiency.
Time/Space Tradeoff

▪ The efficiency of an algorithm can be computed by determining the


amount of resources it consumes. The primary resources that an algorithm
consumes are:
– Time: The CPU time required to execute the algorithm
– Space: The amount of memory used by the algorithm for execution
▪ The lesser resources that an algorithm uses, the more efficient it is.
▪ Some of the algorithms may be extremely time-efficient and others
extremely space-efficient.
▪ If data is stored in a compressed form, the memory usage is less because
data compression reduces the amount of space required. However, it is
more time consuming because some additional time is required to run the
compression algorithm. Similarly, if data is stored in its uncompressed form,
the memory usage is more, but the running time is less.
▪ Memory is generally perceived to be extensible because you can increase
the memory of your computer. Time, however, is not extensible. Therefore,
time considerations generally override memory considerations.
Activity 4

▪ Consider the following scenario:


– Think of a GUI drop-down list box that displays a list of employees whose
names begin with a specified sequence of characters. If the employee database
is on a different machine, then there are two options:
• Option a: fire a SQL and retrieve the relevant employee names each time the list is
dropped down.
• Option b: keep the complete list of employees in memory and refer to it each time
the list is dropped down.
▪ In your opinion which is the preferred option and why?
Solution to Activity 4
Solution of Activity 4

▪ This example again does not have a unique solution. It depends on various
parameters which include:
– The number of employees
– The transmission time from the database server to the client machine
– The volume of data transmission each time
– The frequency of such requests.
– The network bandwidth
Solution of Activity 4

▪ Time and space tradeoff:


– Software solutions need to strike a compromise between memory
consumption and space usage
Activity 5

▪ Which one of the following problems consumes more memory?


– Design a computer program which produces an output 1, if the word is of
length 3n (n=0,1,2,…) and 0, otherwise
• Example: If the input is “aabcef” the output is 1
• If the input is “aabc” then the output is 0

▪ Design a computer program that sorts ( in Ascending order ) and outputs the
result for any input sequence a1,a2,…an of numbers, where n is any natural
number
Solution to Activity 5
Solution to Activity 5

▪ Program 1 always requires a constant amount of memory.


▪ Program 2 requires memory of arbitrary length.
Activity 6

▪ Identify the best approach to solve the following problems:


1. A file contains names, PAN number and much additional information. How
will you search the given name.
2. A file contains names, PAN number and much additional information. How
will you search the record using PAN number.
Solution to Activity 6
Solution to Activity 6

1. Sorting this file alphabetically and using a binary search is very efficient way to
find the record for a given name.
Solution to Activity 6 (Contd.)

2. Multiple solutions
• If we perform a linear search then it would be time consuming for a very large
number of records.
• Create another file which is sorted numerically according to PAN number. This
however, would double the space required for sorting the data.
• Sort the main file numerically by PAN number and have an auxillary array with
only two columns, the first column containing an alphabetized list of the names
and the second column containing pointers which gives the locations of the
corresponding records in the main file. This is one way of solving the problem
that is used frequently, since the additional space, containing only two columns, is
minimal for the amount of extra information it provides.
Note: Suppose a file is sorted numerically by PAN number. As new records are inserted
into the file, data must be constantly moved to new locations in order to maintain the
sorted order.
One simple way to minimize the movement of data is to have the PAN number serve as
the address of each record. Not only would there be no movement of data when records
are inserted, but there would be instant access to any record. However, this method of
sorting data would require one billion (10 raise to power 9) memory allocations for only
hundreds or possibly thousands of records. Clearly, this tradeoff of space for time is not
worth the expense.
What is Unit Test?

▪ There are various levels of testing:


– Unit Test:
• A unit can be an operation, a class, a software package, or a subsystem
– Integration Test:
• Interactions between units
– System Test:
• System verification and validation as a whole
▪ There are various types of testing based upon the intent of testing such as:
– Acceptance Testing
• Testing as a end user; Expected results from system
– Performance Testing
• Tests the retrieval time of the data
– Load Testing and Regression Testing
▪ Based on the Testing Techniques, testing can be classified as:
– Black box Testing and White box Testing
What can be tested in units?

▪ A functional requirement
▪ Given input that satisfies the precondition, whether the output satisfies the
post-condition
▪ A unit can be a member function, a class, a package or component or a
subsystem
▪ Automation is the key! Replace user interaction with the scripts, if
possible; replace some units with stubs
▪ A unit tested can still have bugs, but most trivial bugs should have been
found
How does Unit Testing fit into the Software
Development Life Cycle?

▪ This is the first and the most important level of testing. As soon as the
programmer develops a unit of code the unit is tested for various
scenarios.
▪ As the application is built, it is much more economical to find and eliminate
the bugs early on. Hence Unit Testing is the most important of all the
testing levels. As the software project progresses ahead it becomes more
and more costly to find and fix the bugs.
▪ In most cases it is the developer’s responsibility to deliver Unit Tested
Code.
– Unit Testing Tasks and Steps:
Step 1: Create a Test Plan
Step 2: Create Test Cases and Test Data
Step 3: If applicable create scripts to run test cases
Step 4: Once the code is ready, execute the test cases
Step 5: Fix the bugs if any and re test the code
Step 6: Repeat the test cycle until the “unit” is free of all bugs
What is a Unit Test Plan?

▪ This document describes the Test Plan, in other words how the tests will
be carried out.
▪ This will typically include the list of things to be Tested, Roles and
Responsibilities, prerequisites to begin Testing, Test Environment,
Assumptions, what to do after a test is successfully carried out, what to do
if test fails
What is a Test Case?

▪ Simply put, a Test Case describes exactly how the test should be carried
out.
For example the test case may describe a test as follows:
– Step 1: Type 10 characters in the Name Field
– Step 2: Click on Submit
▪ Test Cases clubbed together form a Test Suite
Test Case Sample

Test Case Expected


Test Case ID Input Data Actual Result Pass/Fail Remarks
Description Result

▪ Additionally, the following information may also be captured:


– Unit Name and Version Being tested
– Tested By
– Date
– Test Iteration (One or more iterations of unit testing may be performed)
Steps to Effective Unit Testing

Documentation
▪ Early on document all the Test Cases needed to test your code. A lot of
times this task is not given due importance.
▪ Document the Test Cases, actual Results when executing the Test Cases,
Response Time of the code for each test case.
▪ There are several important advantages if the test cases and the actual
execution of test cases are well documented:
– Documenting Test Cases prevents oversight
– Documentation clearly indicates the quality of test cases
– If the code needs to be retested we can be sure that we did not miss anything
– It provides a level of transparency of what was really tested during unit testing.
This is one of the most important aspects.
– It helps in knowledge transfer in case of employee attrition.
– Sometimes Unit Test Cases can be used to develop test cases for other levels
of testing
What should be tested when Unit Testing

Scope of testing
▪ A lot depends on the type of program or unit that is being created. It
could be a screen or a component or a web service.
▪ Broadly the following aspects should be considered:
– For a UI screen include test cases to verify all the screen elements that need
to appear on the screens
– For a UI screen include Test cases to verify the spelling/font/size of all the
“labels” or text that appears on the screen
– Create Test Cases such that every line of code in the unit is tested at least
once in a test cycle
– Create Test Cases such that every condition in case of “conditional
statements” is tested once
– Create Test Cases to test the minimum/maximum range of data that can be
entered. For example what is the maximum “amount” that can be entered or
the max length of string that can be entered or passed in as a parameter
– Create Test Cases to verify how various errors are handled
– Create Test Cases to verify if all the validations are being performed
Automate where Necessary

Automation of testing
▪ Time pressures/Pressure to get the job done may result in developers
cutting corners in unit testing.
▪ Sometimes it helps to write scripts, which automate a part of unit testing.
▪ This may help ensure that the necessary tests were done and may result in
saving time required to perform the tests.
Activity 7

Michel is working in G& G company as developer. He has created a GUI to


validate the customers credential before logging to the shopping site. His
manager John Smith has assigned him a task of preparing the test case report
for the same. Can you help him out?
Solution to Activity 7
Solution to Activity 7
Summary

▪ In this module, you learned that:


– A standard, by definition, is a predetermined mark, a measure or model of
quality.
– While writing a good program, a developer should keep following points in the
mind:
• Code should be indented properly so that it becomes understandable.
• White space should be used around operators and keywords
• While writing the code always use meaningful function, procedure and variable
names. So that its usage is clear.
• Instead of writing a lengthy program, use modular approach so that it is easy to
debug.
• Always write the meaningful comments in the program so that usage is clear.
• Always write introduction section in the starting of program to mention the name
of the module, last updated date of module, developer name and version of the
module.
• Write a separate function for allocation and de-allocation of variables.
• Iteration terminates when the loop-continuation condition fails.
– Recursion terminates when a base case is recognized.
Summary (Contd.)

– The efficiency of an algorithm can be computed by determining the amount of


resources it consumes.
– The primary resources that an algorithm consumes are:
• Time
• Space
– Time/space tradeoff refers to a situation where you can reduce the use of
memory at the cost of slower program execution, or reduce the running time
at the cost of increased memory usage.
– The following are the various levels of testing:
• Unit Test
• Integration Test
• System Test
Module 3: Problem Solving Techniques
Objectives

▪ At the end of this module, you will be able to:


– Use the divide and conquer algorithm
– Use pattern searching algorithm
– Understand the need of modular programming
– Understand recursive functions

Duration 3hrs
Introducing the Divide and Conquer Technique

▪ Divide and conquer: A technique for designing algorithms that:


– Divides the problem into sub-problems similar to original problem but smaller
in size
– Conquers the sub-problems recursively
– Combines solutions to create solution to original
Divide and Conquer Algorithms : Quick Sort

▪ Quick sort is one of the most powerful sorting algorithm. It works on the
Divide and Conquer design principle.
▪ Quick sort works by finding an element, called the pivot, in the given input
array and partitions the array into three sub arrays such that:
– The left sub array contains all elements which are less than or equal to the
pivot
– The middle sub array contains pivot
– The right sub array contains all elements which are greater than or equal to
the pivot
– Now the two sub arrays, namely the left sub array and the right sub array are
sorted recursively
Divide and Conquer Algorithms : Merge Sort

▪ Merge sort is yet another sorting algorithm which works on the Divide
and Conquer design principle
▪ Merge sort works by dividing the given array into two sub arrays of equal
size
▪ The sub arrays are sorted independently using recursion
▪ The sorted sub arrays are then merged to get the solution for the original
array
Activity 1

▪ Write the pseudo code to apply divide and conquer to merge sort an
array of numbers.
Solution of Activity 1
Solution to Activity 1

1. Merge-Sort A[1..n]
2. if n =1, done.
1. Recursively sort A[1..⎡n/2⎤ ] and A[⎡n/2⎤+1.. n ]
3. Merge the two sorted lists
Divide and Conquer Algorithms – Binary Search

▪ Binary Search works on the Divide and Conquer Strategy.


▪ Binary Search takes a sorted array as the input.
▪ It works by comparing the target (search key) with the middle element of
the array and terminates if it is the same, else it divides the array into two
sub arrays and continues the search in left (right) sub array if the target is
less (greater) than the middle element of the array.
Example - Binary Search

▪ Find an element in a sorted array:


– Divide: check middle element
– Conquer: recursively search 1 subarray
– Combine: trivial
Activity 2

▪ Consider the list as shown in the following figure:

▪ You need to find the minimum value of the list by applying divide and
conquer algorithm.
Solution of Activity 2
Solution to Activity 2

▪ To find the minimum value, divide the list into two halves, as shown in the
following figure.

▪ Again, divide each of the two lists into two halves, as shown in the
following figure:

▪ Now, there are only two elements in each list. At this stage, compare the
two elements in each list to find the minimum of the two. The minimum
value from each of the four lists is shown in the following figure:
Solution to Activity 2 (Contd.)

▪ Again, compare the first two minimum values to determine their minimum.
Also compare the last two minimum values to determine their minimum.
The two minimum values thus obtained are shown in the following figure:

▪ Compare the two final minimum values to obtain the overall minimum
value, which is 1 in the preceding example.
Introducing Pattern Searching Algorithm

▪ Pattern Searching Algorithm:


– Determines whether or not a given string pattern appears in a string text
– Can be based on the brute force and Boyer-Moore algorithms.
▪ Application:
– Find function of Microsoft Word
Introducing Brute Force Algorithm

▪ Brute force:
1. Start at the first (leftmost) character in the text.
2. Compare from left-to-right, each character in the pattern to those in the text.
• If all of the characters are the same, you have found a match.
• Otherwise, if you have reached the end of the text, there can be no more matches
• If neither of the preceding results occur, move the pattern along one character to
the right and repeat from step 2.
Example of Brute Force Algorithm

▪ Text: Algorithm Design


▪ Pattern: gor
▪ First Attempt:
– Compare gor with Algorithm Design: No match
▪ Second Attempt:
– Compare gor with Algorithm Design: No match
– Third Attempt:
– Compare gor with Algorithm Design: Match Found
Activity 3

▪ Write a pseudo code of brute force algorithm.


Solution to Activity 3
Solution of Activity 3

BruteForceMatch(T, P)
Input text T of size n and pattern P of size m
Output starting index of a substring of T equal to P or -1 if no such substring
exists
for i <- 0 to n - m
{ test shift i of the pattern }
j <- 0
while j < m ^ T[i + j] = P[j]
j <- j + 1
if j <- m
return i {match at i}
else
break while loop {mismatch}
return -1 {no match anywhere}
Boyer-Moore Algorithm

▪ Boyer-Moore algorithm:
– Forms the basis for some of the fastest pattern searching algorithms currently
available.
– Removes many of the redundant matching moves that occurs in brute force
algorithm.
Boyer Moore Pseudocode

BOYER_MOORE_MATCHER (T, P)
Input: Text with n characters and Pattern with m characters
Output: Index of the first substring of T matching P
Compute function last
i ← m-1
j ← m-1
Repeat
If P[j] = T[i] then
if j=0 then
return i // we have a match
else
i ← i -1
j ← j -1
else
i ← i + m - Min(j, 1 + last[T[i]])
j ← m -1
until i > n -1
Return "no match"
Introducing Modular Programming

▪ Modular Programming:
– Design technique where an application is broken down into modules.
▪ Modules are self contained.
▪ Modules can be independently developed and tested.
▪ Modules are finally integrated to create the final application.
Modular Programming Advantages

▪ Advantages of modular programming:


– Debug modules independently
– Divide work among multiple teams
– Reuse code
Activity 4

▪ Consider the following scenario:


– Earnest Solutions Inc. is a multinational organization that provides Internet
Technology (IT) hardware products and services across 15 countries. The
management at Earnest Solutions Inc. is planning to further increase their
operations in other countries.
– For this, the management wants to make their current system robust enough
to support the new challenges. After a thorough analysis, the team found that
the employees of their Sales department are segregated divisions based on the
products or solutions that they are assigned to sell. Therefore, sales personal
are restricted only to the knowledge of the product they are responsible to
sell for their division.
– For example, sales personal of the Kiosks division are trained on Kiosks
specifications and selling strategies specific to Kiosks. Similarly, sales personal
of the printer division are imparted the knowledge required to sell the
different types of printers that Earnest Solutions manufacture.
– As a result, the team has realized that whenever customers queries for
products, sales personals cannot provide convincing information if the product
is of a different division.
Activity 4 (Contd.)

– The team has realized the importance of eliminating the current information
silo and has proposed to create a centralized training solution that will enable
enhancing the skills of the sales personals.
– To address the current limitations, your team has proposed to create an
Online Assessment Management (OAM) application that can be accessed by
the trainers and sales personal over the Internet.
– The application in the first phase should enable trainers to create and publish
assessments online to test the knowledge of a user on information across
different products and services of Earnest Solutions.
– In this phase, the application should also create and publish a Percentile Rank
(PR) Web service to calculate percentile of a user who has completed the
assignment. The OAM application should have a client component that should
access the PR Web service to fetch the percentile rank of a user and persist it
to the database.
– How will you implement modular programming in this scenario and what
advantages will it provide?
Solution of Activity 4
Solution of Activity 4

▪ The OAM application provided in the scenario can be broken down into
the following independent modules:
– Login module: To manage user logins
– Create assessment module: To manage the process of creating and
publishing assessments
– Take assessment module: To manage the process of completing an
assessment.
– Report generation module: To generate assessment scores based on a
user, date, or assessment name
– Percentile rank module: To create a Web service and a client program to
access it.
▪ Advantages:
▪ Each of the modules can be assigned to five developers or teams
▪ Each team can create, debug, and test their own modules
▪ Each team can be independently managed and monitored
▪ The login module and percentile rank modules can be reused in other applications
Introducing Recursive Function

▪ Recursion
– Technique of defining a process in terms of itself
– Break a problem into smaller versions of itself, and then build up a solution for
the entire problem
– Is implemented in a program by using a recursive procedure or function
– A recursive procedure is a function that invokes itself.
The Tower of Hanoi

▪ One of the most common and interesting problems that can be solved by
using recursion is the Tower of Hanoi problem.
▪ Tower of Hanoi is a classical problem, which consists of n different sized
disks and three pins over which these disks can be mounted. All the disks
are placed on the first pin with the largest disk at the bottom and the
remaining disks in decreasing order of their size, as shown in the following
figure.
The Tower of Hanoi (Contd.)

▪ One of the most common and interesting problems that can be solved by
using recursion is the Tower of Hanoi problem.
▪ The objective of the game is to move all disks from the first pin to the
third pin in the least number of moves by using the second pin as an
intermediary. To play this game, you need to follow the following rules:
– Only one disk can be moved at a time.
– A larger disk cannot be placed over a smaller one.
The Tower of Hanoi (Contd.)

▪ Let n be the number of the discs. If n = 3, it will require seven steps to


transfer all discs from pin one to pin three, as shown :
– Step 1: Move top disc from pin1 to pin 3
– Step 2: Move top disc from pin 1 to pin 2
– Step 3: Move top disc from pin 3 to pin 2
– Step 4: Move top disc from pin 1 to pin 3
– Step 5: Move top disc from pin 2 to pin 1
– Step 6: Move top disc from pin 2 to pin 3
– Step 7: Move top disc from pin 1 to pin 3
The Tower of Hanoi (Contd.)

▪ The following figure illustrates the seven steps for the tower of Hanoi
problem :
Activity 5

▪ For the Tower of Hanoi problem, write the algorithm to move the top n
discs from the first pin START to the final pin FINISH through the
temporary pin TEMP:
Solution to Activity 5
Solution to Activity 5

MOVE (n, START, TEMP, FINISH)


When n = 1:
MOVE a disc from START to FINISH
Return
Move the top n – 1 discs from START to TEMP using FINISH as an
intermediary
[MOVE (n – 1, START, FINISH, TEMP)]
Move the top disc from START to FINISH
Move the top n – 1 discs from TEMP to FINISH using START as an
intermediary
[MOVE (n – 1, TEMP, START, FINISH)]
Understanding Recursive Function

▪ Consider function f (n), which is the sum of the first n natural number
▪ In Mathematics, the function can be defined as:
– f(n) = 1 + 2 + 3 + 4 + 5 +...+ n
▪ The same function can be defined in a recursive manner
f(n) = f(n – 1) + n
Where n > 1; and f(1) = 1
Understanding Recursive Function (Contd.)

▪ Consider a factorial function. A factorial function is defined as:


– n! = 1 × 2 × 3 × 4 × … × n
▪ This same factorial function can be redefined as:
– n! = (n – 1)! × n where n > 1; and 0! = 1
Scope and Limitation of Recursive Function

▪ Scope:
– Recursive function divide the problem into same problem of subtypes and
hence replaces complex nesting code.
– Certain algorithms are recursive by nature
– Recursion can allow you to implement immutability
▪ Limitation:
– If the depth of the recursion is very large, the algorithm may require large
amounts of memory
Summary

▪ In this module, you learned that:


– Divide and conquer is a technique for designing algorithms that divides a
problems into D sub-problems, resolves the sub problems, and combines the
solutions to create the solution to original
– Quick sort, merge sort, and binary search algorithms are based on the Divide
and Conquer design principle
– Pattern searching algorithm is used to decide whether or not a given string
pattern appears in a string text.
– Pattern searching algorithm can be based on the brute force and Boyer-Moore
algorithms.
– Brute force overlays the text with the pattern, starting from the left-hand side
and continuing to slide the pattern right one character until a match is found:
– The Boyer-Moore algorithm scans the characters of the pattern from right to
left beginning with the rightmost character.
Summary (Contd.)

– Modular programming is a design technique where instead of creating a large


monolithic application, an application is broken down into modules.
– Advantages of modular programming:
• Debug modules independently
• Divide work among multiple teams
• Reuse code
– A recursive procedure is a function that invokes itself.
– One of the most common and interesting problems that can be solved by
using recursion is the Tower of Hanoi problem.
– Recursive function enables solving problems in easy way.
– Recursion can allow you to implement immutability.
– If the depth of the recursion is very large, the algorithm may require large
amounts of memory
Thank You

View publication stats

You might also like