Data Structure
Data Structure
net/publication/341219052
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:
All content following this page was uploaded by Hitesh Mohapatra on 07 May 2020.
DATA STRUCTURE
HITESH MOHAPATRA
Programming Structure
and Methodology
Agenda
Introduction to Programming
1
Structure and Methodology 2hrs
What is your
job as a
programmer
going to be?
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.)
– 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.)
Lack of extensibility
Lack of modularity
Tight coupling
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!
•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…?
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?
▪ 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?
– 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
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.)
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?
▪ 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.)
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
▪ Scalar data
▪ Vector data
▪ Associated array
Scalar 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
1. False
2. False
3. True
Input/Output/Process
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
/ Divide the left operand by the X=y/z Divides y by z and stores the
right operand result in x
|| 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
▪ 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
Start
Initialize a variable
desig
Enter designation
No
Yes
▪ 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
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.)
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
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
▪ 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
Case
grade
Case
grade
Case
grade
Case
grade
Case conditions
= “S” = “A” = “B” = “C”
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.)
Case D
runs = runs
Case conditions
Stop
Summary
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
▪ 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
▪ 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
▪ 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
▪ 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
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
▪ 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
▪ 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
▪ 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
▪ 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
▪ 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
▪ 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 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.)
▪ 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
▪ 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)
▪ 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.
▪ 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
▪ 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
▪ You need to sort the preceding list by using the quick sort algorithm.
Summary
Duration 2hrs
Module Overview
▪ 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?
Sam is in a mess !
▪ Consider a scenario:
– There are Children and I want to play a small game with them.
– How do I do this?
▪ 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.)
▪ 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.)
▪ 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.)
▪ 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.)
▪ 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
Duration 3hrs
Module Overview
▪ 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:
▪ 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.)
▪ 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.)
▪ 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:
▪ 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
– 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.
▪ 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 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
▪ 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
Duration 3hrs
Module Overview
▪ 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.)
▪ 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.)
▪ 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.)
▪ 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
▪ 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
Duration 3hrs
Understanding the Need of Queue
▪ 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.)
▪ 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.)
▪ 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.)
▪ 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.)
▪ 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
– 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
Duration 2hrs
Why Programming
Standards ?
Understanding the Need of Programming
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
▪ 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
While(!<some condition>)
{
//do something
}
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.)
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
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
▪ 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
▪ 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
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?
▪ 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
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
Duration 3hrs
Introducing the Divide and Conquer Technique
▪ 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
▪ 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
▪ 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
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
– 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.)
▪ 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
▪ 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.)
▪ 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