0% found this document useful (0 votes)
16 views93 pages

Week 1 Cs 2

Dr. Summaira Jabeen introduces a Computer Science II course focused on algorithms and data structures, emphasizing the importance of respect, response, and the right approach to learning. The course will cover topics such as linear and non-linear data structures, programming languages, and the program development cycle, with a strong focus on C++. The objective is to enhance problem-solving skills and prepare students for real-world applications of programming and algorithms.

Uploaded by

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

Week 1 Cs 2

Dr. Summaira Jabeen introduces a Computer Science II course focused on algorithms and data structures, emphasizing the importance of respect, response, and the right approach to learning. The course will cover topics such as linear and non-linear data structures, programming languages, and the program development cycle, with a strong focus on C++. The objective is to enhance problem-solving skills and prepare students for real-world applications of programming and algorithms.

Uploaded by

somi somi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Chapter 1 Tutorial

Introduction.
第一章 (1) 绪论

Computer Science II (Algorithms)


计算机科学 II (算法分析与设计)
Self Introduction ( 自我介绍 )
• Good morning, everyone! I hope you’re as excited as I am to embark on this
incredible learning journey together. My name is Dr. Summaira Jabeen.
• Masters : From Comsats university Islamabad.
• PHD degree : From Zhejiang University Hangzhou, where I have published six
research articles on Computer vision.
• While pursuing my education, I also worked as a Lecturer CS. I have a teaching
experience of more than 10 years.
Continue…

• I am absolutely thrilled to be your teacher this year. With a passion for education
and a commitment to your success, I am here to guide, support, and inspire you
every step of the way. Get ready for engaging lessons, thought-provoking
discussions, and a whole lot of fun as we explore the fascinating world of data
structure and algorithms with CPP, your potential, discover new horizons, and
make this a year to remember.

• Buckle up, because the adventure starts now!


Rules for Classroom!

• I want to set some rules from the get go…These are three R’s…
1. Respect
2. Response
3. Right
• Respect is mandatory rule to carry out fruitful learning process. So we should all respect each
other during the class.
• Response is the process in which we all abide by in the classroom when either asking a question
or answering.
• Right approach to learning is getting the students to understand the benefits of learning and how
this impact their future.
Evaluation Criteria
Course Outline

• Introduction to Data Structure And Algorithm


• Linear Data Structure and its Types With the implementation in C++.
• Arrays And Linked List and its operations
• Stacks and Queues And its basic Operations
• String data type and its types
• Non- Linear Data structure with explanation of Trees and its types
• Graphs in detail with the implementation in C++
• Basic concepts and classifications of searching algorithms
• Basic concepts and classifications of internal sorting
Computers and Programming

• A computer is just a machine (the hardware) for


executing programs (the software)
• Hence, the software rules the hardware!

• The process of creating software is called


programming, and it is the focus of this course

• Virtually, anyone can learn how to program


computers
• It requires only some grit!
Why Learn
Programming?
• Computers have become commonplace in our modern life
• Understanding the strengths and limitations of computers requires
some understanding of programming

• Programming can be loads of fun!


• It is an intellectually engaging activity that
Astronomy allows you to express
Ubiquitous
Computing
yourself through remarkably beautiful creations
Smaller,
Faster,
• Programming develops valuable problem-solving skills,
Cheaper
Sensors
especially ones thatGene
pertain to analysis, design and
implementation Sequencing
and
Biotechnology


Why Learn Programming?

• Computers have become commonplace in our modern life


• Applying ideas in different fields requires programming

• Programming can be loads of fun!


• It is an intellectually engaging activity that allows you to
express yourself through remarkably beautiful constructs
and structures

• Programming develops valuable problem-solving skills,


especially ones that pertain to analysis, design and
implementation

Programmers are in great demand!


Programming
Languages
A program is just a sequence of instructions telling the computer
what to do

Obviously, we need to provide these instructions in a language that


computers can understand
• We refer to this kind of a language as a programming language
• Python, Java, C and C++ are examples of programming
languages

Every structure in a programming language has an exact form (i.e.,


syntax) and a precise meaning (i.e., semantic)
Machine Languages

• Python, Java, C, and C++ are, indeed, examples of high-level languages

• Strictly speaking, computer hardware can only understand a very low-level


language known as machine language

• If you want a computer to add two numbers, the instructions that the CPU
will carry out might be something like this:

Load the number from memory location 2001 into the CPU
Load the number from memory location 2002 into the CPU A Lot of
Add the two numbers in the CPU Work!
Store the result into location 2003
High-Level to Low-Level
Languages
• In a high-level language like Python or C++, the addition of two numbers
can be expressed more naturally:

c=a+b Much Easier!


• But, we need a way to translate the high-level language into a machine
language that a computer can execute
• To this end, high-level language can either be compiled or interpreted
Compiling a High-Level
Language
• A compiler is a complex software that takes a program written in a high-level
language and translates it into an equivalent program in the machine language of
some computer

Source Code Machine


Compiler
(Program) Code

C++ is a compiled language because


it uses a compiler to translate the Running
Inputs Outputs
source code into an object code. This Program
object code is converted to the
executable for the end-users to run.
Interpreting a High-Level
Language
• An interpreter is a software that analyzes and executes the source code
instruction-by-instruction (on-the-fly) as necessary

Source Code
(Program)
Computer
Running An Outputs
Interpreter
Inputs

• E.g., Python is an interpreted language


Program Development Cycle

Many programmers follow a sequence of Steps to create their programs.


1. Analyze – Define the Problem
Make sure that you understand what the program should do. What should the
user be able to enter? How? How does the program come up with an answer?
What does the program output? How?
 User – a person who uses a computer program.
 End User – the user that the program was made for.
2. Design – Plan a Solution for the Problem
Develop a PRECISE sequence of steps to solve the problem
 An algorithm is a precise sequence of steps to solve a problem.
Develop an Algorithm

• Imagine you want a program that tells a user how many stamps they
need in order to mail a certain number of pages.
• You need one stamp for every 3 pages
• 6 pages = 2 stamps
• 9 pages = 3 stamps
•…
• Write an algorithm (the steps needed) to solve this problem
Program Development Cycle – Design
(Continued)

• Typically a program follows three general steps


1. Input
2. Processing (Formulas)
3. Output
Develop an Algorithm, 2nd
Attempt

OK, with this knowledge, Lets try writing the


algorithm !
Program Development Cycle – Design
(Continued)
• Are those three steps enough?
• What about if the user enters “Banana” instead of a number of sheets?
• The program does not know how to find the number of stamps required to mail “Banana” number of
sheets
• In order for the program to run without crashing, our algorithm must make sure that the user inputs some
valid data.
 There are two main ways of doing this:
1. Prevention – Making sure that the user is not physically able to enter in invalid data.
2. Validation – Allowing the user to enter invalid data, but checking it to make sure it is valid
before processing.
• So, there are really 4 general steps most programs follow:
1. Input
1. Read Input
2. Validate Input
2. Process
3. Output
Develop an Algorithm, 3rd
Attempt
• OK, now with THAT information, try developing the algorithm
• One good algorithm developed could look like this:
1. Request the number of sheets of paper from the user; call it Sheets
(Input/Read)
2. Make sure Sheets is a positive whole number (Input/Validation)
3. Divide Sheets by 3 (Processing)
4. Round the result from step 3 up to the highest whole number; call it Stamps
(Processing)
5. Reply with the number Stamps (Output)
Programming Tools

• Flowcharts – A chart that consists of symbols connected by arrows. Within each symbol is a
phrase presenting the activity at that step. The shape of the symbol indicates the type of operation
that is to occur.
• Hierarchy Charts – A chart that shows the overall program structure. These charts describe what
each part, or module, does and how they are related. These modules intentionally omit details of
how they work.
• Pseudocode – an abbreviated plain English version of actual computer code. Kind of a mix
between English and code. THERE IS NO OFFICIAL SYNTAX TO PSEUDOCODE.
Flow Charts

• Flow Line - indicates the flow of logic

• Terminal – indicates the start or end of a task

• Input/Output – used for input or output operations. What is to be input or output should be in the
figure.
Flow Charts

• Processing - used to show a processing step. The instructions are displayed in the figure.

• Decision – used to show when a decision needs to be made. Lines for yes and no come out of it.
The question is displayed in the figure.

• Connector – Used to join flow lines.


Stamps Flowchart Start

Read Sheets

Display Error No Is sheets a


positive whole
Message number?

Yes
Set Stamps =
Sheets/3

Round Stamps to nearest


whole number

Display
Stamps

End
Hierarchy Chart
Postage Stamp
Program

Calculate Display
Input
Stamps Stamps

Round Stamps to
Read Validate Set Stamps the next whole
Sheets Sheets = Sheets/3 number
Program Development Cycle

Write the Code – Implement a solution


 The instructions in a programming language collectively called code.
 Your code should be a translation of your algorithm developed into the
programming language.
• In this class we will use C++, but there are many other programming
languages: C, C++, Java, Ruby, Python, Visual Basic, etc.
• This is the major focus of this course, but note that you need to be able to
think algorithmically in order to do this.
• Meaning, you need to be able to logically solve the problem in order to
write a program for it.
Program Development Cycle

Testing and Debugging – Locate and remove any errors in the program
 Testing is the process of finding errors in a program
 Debugging is the process of removing errors in a program.
An error in a program is called a bug.
We will talk more specifically about the kinds of errors that can occur in a program
once we start programming.
Complete All Documentation – Organize the material that describes the program.
 Documentation is any material whose purpose is to allow another person or programmer to use
or understand the program
 Two kinds of documentation:
1. External Documentation – Material outside of the code files that describe the program.
2. Internal Documentation – Lines inside of a code file that do nothing except describe
details of the program. In C++, these are called comments.
ADD A FOOTER 28
Course objectives

• Learn basic data structures and algorithms


• data structures – how data is organized
• algorithms – unambiguous sequence of steps to compute something
• algorithm analysis – determining how long an algorithm will take to solve a
problem

• Become a better software developer


• "Data Structures + Algorithms = Programs"
-- Niklaus Wirth, author of Pascal language

29
Continue…

• Be familiar with problem solving.


• Be able to develop (and implement) algorithms in Cpp.
• Be able to trace algorithms.
• Be able to select appropriate data structures and algorithms for given problems.
31
Computer Science is more than
coding

• Computer scientists build amazing things in the real world using in-depth theories and core
concepts of computer science.
• Without a doubt, they need to be good at data structures and algorithms as it’s the core concept
in the world of programming.

So, if your goal is to build new things and become a computer scientist, you simply can’t reach
that level without expertise in Data Structure and Algorithm.

32
Real-Life Example

If you need to search your roll number in 20000 pages of PDF document (roll numbers are arranged
in increasing order)
how would you do that?

33
Real-Life Example
• If you will try to search it randomly or in a sequential manner it will take too much time. You
might get frustrated after some time.

• Using Data Structures and Algorithm to solve real-life scenario.


• You can try another solution as:
• Go to page no. 10000
• If your roll no. is not there, but all other roll no. in that page are lesser than your than
• Go to page no. 15000
• Still if your roll no. is not there. but this time all other roll no. is greater than your.
• Go to page no. 12500
• Continue the same process and within few minutes you will find your roll number.
• Congratulations… you just have used the Binary Search algorithm unintentionally.. 34
Implementation of Data Structures and Algorithms
To Solve Some Real-World Complex Problems

• Have you ever been scolded by your parents when you were unable to find your book or clothes in
your messed-up room?
Definitely yes…
• Your parents are right when they give the advice to keep everything in the right place so the next
time you can get your stuff easily.

• Here you need to arrange and keep everything (data) in such a structure that whenever you need to
search for something you get that easily and as soon as possible.
• This example gives a clear idea that how important it is to arrange or structure the data in real life.

35
Implementation of Data Structures and Algorithms
To Solve Some Real-World Complex Problems

Example: Library

If you need to find a book on Set Theory from a library,


 you will go to the Math's section first,
 then the Set Theory section.
 If these books are not organized in this manner and just distributed randomly then it will be
frustrating to find a specific book.

 If these books are sorted in each section of library then it is easy to find the required book
quickly.

These examples illustrates the importance of data structures and algorithms in


our daily life. Data structures and Algorithms are difficult to implement
But 36

Can ease our life.


Implementation of Data Structures and Algorithms
To Solve Some Real-World Complex Problems

• Facebook (Yes… we are talking about your favorite application). Can you just imagine
that your friends on Facebook, friends of friends, mutual friends they all can be
represented easily by Graph? Relax….sit for a couple of moments and think again…you
can apply a graph to represent friends’ connections on Facebook.
• If you need to keep a deck of cards and arrange it properly how would you do that? You
will throw it randomly or you will arrange the cards one over another and from a proper
deck. You can use Stack here to make a proper arrangement of cards one over another.
• If you need to search for a word in the dictionary, what would be your approach? Do
you go page by page or do you open some page and if the word is not found you open a
page prior to/later to one opened depending upon the order of words to the current page
(Binary Search).

• All the above examples give you a clear understanding that how the organization of data
37
is really important in our day-to-day life.
Motivation

Data Structures 1. Data Structures define how


Algorithms data is stored in RAM
2. Many variations, each with
advantages and
disadvantages
3. Strongly coupled to algorithmic
complexity

38
Motivation

● Data 1. Everything running on your


Structures computer is an algorithm
2. Analysing them is paramount
Algorithms to writing, maintaining and
improving them
3. Several tools exist to help
achieve this

39
•A review of Previous Knowledge

ADD A FOOTER 40
What is data?

• Data
• A collection of facts from which conclusion may be drawn.
• e.g. Data: Temperature 35°C; Conclusion: It is hot.
• Types of data
• Textual: For example, your name (Zhang)
• Numeric: For example, your ID (090254)
• Audio: For example, your voice
• Video: For example, your voice and picture
• (...)
Data Types

• Applications/programs read data, store data temporarily, process it and


finally output results.
• What is data? Numbers, Characters, etc.

Data Application/ Information


Program

42
Data Types

• Data is classified into data types. e.g. char, float, int, etc.
• A data type is (i) a domain of allowed values and (ii) a set of operations on these
values.
• Compiler signals an error if wrong operation is performed on data of a certain type.
For example, char x,y,z; z = x*y is not allowed.

43
Data Types

• Simple Data types: also known as atomic data types  have no


component parts. E.g. int, char, float, etc.

21 3.14 ‘a’

44
Data Types & Data Structures

• Structured Data types: can be broken into component parts. E.g. an


object, array, set, file, etc. Example: a student object.

Name A H M A D

Age 20
C S C
Branch

45
Need of Data Structures in Computer
Science

• As applications are becoming more complex and the amount of data is increasing day by day,
• which may cause problems with processing speed, searching data, handling multiple requests
etc.
• Data structure provides a way of organizing, managing, and storing data efficiently.
• Data structures enable programmers to represent real-world entities and relationships accurately.
• For instance,
• A linked list can be used to represent a chain of connected elements,
• While a graph can model complex networks.
• By leveraging appropriate data structures, programmers can develop more intuitive and
maintainable code.

46
Need of Data Structures in Computer
Science

Why Learn Data Structure?

• Data structure and algorithms are two of the most important aspects
of computer science.
• Learning data structure and algorithms will help you become a better
programmer.
• You will be able to write code that is more efficient and more reliable.
• You will also be able to solve problems more quickly and more
effectively.

47
Introduction to Data Structures

• A Data Structure (DS) is a collection of data values and the relationships between them.
• DS allow programs to store and process data effectively.
• It is a collection of data objects that allows storing, organizing, and retrieving data on systems.
• Different DS are designed for specific purposes and have varying performance characteristics.
• The data structure isn’t a programming language like C, C++, Java, etc. It is a set of algorithms
that can be used in any programming language to organize the data in the memory.
• Some of the most common data structures are
• Arrays,
• Lists,
• Stacks
• Trees, and
• Graphs.
48
Types of Data Structures
There are 2 types of Data Structure :
• Primitive Data Structure &
• Non – Primitive Data Structure

ADD A FOOTER 49
Types of Data Structures-
contd..
Primitive Data Structure:
• Primitive Data Structures directly operate according to the machine instructions.
• These are the primitive data types.
• Data types like int, char, float, double, and pointer are primitive data structures that
can hold a single value.
Non - Primitive Data Structure:
• Non-primitive data structures are complex data structures that are derived from
primitive data structures.
• Non – Primitive data types are further divided into two categories.
• Linear Data Structure
• Non – Linear Data Structure
50
Types of Data Structures-
contd..
Linear DS
Linear Data Structure:
• Linear Data Structure consists of data elements arranged in a Static Dynamic
sequential manner where every element is connected to its
previous and next elements.
• This connection helps to traverse a linear arrangement in a single Array
Linked
List Stack Queue

level and in a single run.


Non – Linear Data Structure:
• Non-linear Data Structures do not have any set sequence of
connecting all its elements and every element can have multiple
paths to attach to other elements. Non Linear DS

• Such data structures support multi-level storage and sometimes


Tree Graph
can’t be traversed in a single run.
• Such data structures aren’t easy to implement but are more 51

efficient in utilizing memory.


Working of some key data structures

Arrays:
• An array is a data structure used to store the elements of the same data type
such as integers or strings.
• Arrays store multiple data elements of the same type in adjacent memory
locations.
Applications:
• Book titles in a Library Management Systems. 1D Array 2D Array
• Online ticket booking.
3 2 3 1 9 2
• Contacts on a cell phone. or
2 2 5 3
• For CPU scheduling in computer.
• To store the possible moves of chess on a chessboard.
52
Working of some key data structures

Stacks:
• Stack is a linear sequence of elements that follows a particular order.
• In stacks, the addition of elements and the removal of elements both happen at the same end.
Applications:
• History of visited websites.
• Message logs and all messages you get are arranged in a stack.
• Call logs, E-mails, Google photos’ any gallery, YouTube downloads, Notifications ( latest appears
first ).
• Media playlist. To play previous and next song

53
Working of some key data structures

Queue:
• A queue is majorly similar to stacks in the sense that it’s an abstract data structure (ADS), the only
difference being- Queues are open at both ends.
• We use one end of the queue to insert data (Enqueuing) and the other end to remove
data (Dequeuing).
Applications:
• Operating System uses queues for job
scheduling.
• To handle congestion in the networking
queue can be used.
• Data packets in communication are arranged
in queue format.
• Sending an e-mail, it will be queued. 54
• Handle website traffic
• CPU scheduling
Working of some key data structures

Linked List:
• A linked list is also a linear data structure (just like arrays), but it’s different in the
way that the elements aren’t stored in contiguous locations.
• Instead, they’re connected through links. Each node contains its data and a link to
the next node.
Applications:
• Images are linked with each other. So, an image viewer software uses a linked list
to view the previous and the next images using the previous and next buttons.
• Web pages can be accessed using the previous and the next URL links which are
linked using a linked list.
• The music players also use the same technique to switch between music.
• History of visited pages.
55
• To perform undo operation.
Working of some key data structures

Graph:
• Graphs are a non-linear data structure that represents the relationship between elements.
• Each graph consists of nodes (elements) and edges (links between elements).
• Take the example of a social media network, where each individual is a node and they’re
interconnected with networks/lines that are called edges.

Applications:
• Facebook’s Graph API uses the structure of Graphs.
• Google’s Knowledge Graph also has to do something with
Graph.
• The GPS navigation system also uses shortest path APIs.
• Networking components have a huge application for graph.
• Google map to find nearest location.
• Facebook to suggest mutual friends. 56
Advantages of Data Structures

• Data structures allow storing the information on hard disks.


• An appropriate choice of ADT (Abstract Data Type) makes the program more efficient.
• Data Structures are necessary for designing efficient algorithms.
• It provides reusability and abstraction.
• Using appropriate data structures can help programmers save a good amount of time while
performing operations such as storage, retrieval, or processing of data.
• Manipulation of large amounts of data is easier.

57
Applications of Data
Structures
 Organization of data in a computer’s memory
 Representation of information in databases
 Algorithms that search through data (such as a search engine)
 Algorithms that manipulate data (such as a word processor)
 Algorithms that analyze data (such as a data miner)
 Algorithms that compress and decompress data (such as a zip utility)
 Algorithms that encrypt and decrypt data (such as a security system)
 Software that manages files and directories (such as a file manager)

58
Continue…

• Databases: Rapid data retrieval and indexing


• (e.g., B-trees, hash tables)
• Operating Systems: Efficient process, file, and memory management
• Network Protocols: Streamlined data transmission and routing
• Artificial Intelligence: Optimized data representation and manipulation

These structures serve as the foundation for efficient information management,


problem-solving, and system optimization.

59
Importance of Data Structure

The importance of Data Structure are:-


 Optimizing Data Access and Manipulation
 Quick and efficient search, insertion, and deletion of information
 Improved processing times and overall system performance
 Organizing Complex Datasets
 Logical and structured arrangement of data elements
 Facilitating accurate information retrieval and processing
 Efficient Problem Solving
 Utilizing appropriate data structures to design efficient algorithms
 Speeding up tasks such as sorting, searching, and graph traversal
 Reducing computational resources required
60
Importance of Data Structure

 Improved performance –
Data structures can help improve the performance of your code by reducing the time
and space complexity of algorithms.
For example, using a binary search tree instead of a linear search can
significantly reduce the time it takes to find a specific element in a large
dataset.
 Better problem solving –
Data structures can help you solve complex problems by breaking them down into
smaller, more manageable parts.
For example, using a graph data structure can help you solve problems
related to network flow or finding the shortest path between two points.
 Reusability –
Data structures can be used in many different algorithms and applications, making
them a useful tool in your programming toolbox
61
Choosing right Data
Structures

62
Choosing right Data
Structures
Before picking a data structure, consider your application's data, obligations, and environment.
While going with your choice, think about the following elements:
• Time Complexity: The performance of your application might be significantly impacted by the
time complexity of your data structure. If your application requires frequent search or retrieval
operations, use a data structure with reduced time complexity, like a hash table.
• Space Complexity: The data structure's space complexity is another important consideration. If
your application is memory-intensive, choose a data structure with less space complexity, such as
an array. If space is not a concern, you may use a data structure with a greater space complexity,
such as a tree.
• Read vs. Write Operations: If your application utilizes a lot of write operations, pick a data
structure with a quicker insertion performance, like a hash table. If your application calls for many
read operations, pick a data structure with a quicker search speed, such as a binary search tree.
63
Continue…

• Type of Data: The data you're dealing with might also impact your chosen data
structure.
• For instance, you may use a tree-based data structure if your data is hierarchical. If
you have simple data that needs to be accessed randomly, choosing an array-based
data structure can be your best option.

• Available Libraries: Consider the libraries that are readily accessible for the
data structure you are considering. It could be easier to execute and maintain if
your programming language has built-in libraries available for a certain data
structure.
Choosing right Data
Structures
However, using the proper data structure can make the difference between a program running in a
few seconds and one requiring many days. For example, searching for a given record in a hash table
is much faster than searching for it in an unsorted array.
When selecting a data structure to solve a problem, you should follow these steps.
• Analyze your problem to determine the basic operations that must be supported.
• Examples of basic operations include inserting a data item into the data structure, deleting a data item
from the data structure, and finding a specified data item.
• Quantify the resource constraints for each operation.
• Select the data structure that best meets these requirements.

65
Algorithms

• An Algorithm refers to a set of steps used to complete a certain task or to get a


desired output.
• Or step-by-step procedures or instructions for solving a specific problem.
• They define the logic and sequence of operations required to transform the input
data into the desired output.
• It is like building blocks for programming that allows smartphones, computers,
or websites to function smoothly and make decisions.
• Each code a programmer writes is a collective form of algorithms navigating
what to do.
• Algorithms are well-defined procedures that help computers to solve problems.
• Algorithms can be as simple as sorting a list of numbers or as complex as
training a machine learning model.
66
Algorithms

• If we want to search a location in GPS system,


• GPS uses an algorithm to search for multiple available routes.
• Also, for checking the current traffic, GPS uses the different algorithms.
• Based on the collective information, it provides the best available route for you.
• Search engines employ sophisticated algorithms to quickly retrieve relevant search results
from vast amounts of web data e.g. Bing, google etc.
• Recommendation systems use algorithms to analyze user behavior and suggest
personalized content e.g. Clothing recommender system.
• By understanding algorithms, programmers can develop intelligent and efficient systems
that provide valuable services to users e.g. Maps and Navigation, Facial Detection and
Recognition etc

67

• Computer use algorithms to calculate things much faster than humans.


What is algorithm?

 A finite set of instructions which accomplish a particular task


 A method or process to solve a problem
 Transforms input of a problem to output
Algorithm = Input + Process + Output

Algorithm development is an art – it needs practice, practice and only


practice!
Relationship between “Data
Structure” & “Algorithm”

• Both DATA STRUCTURE and ALGORITHM are interrelated and complement


each other.
• Data structures and algorithms are closely intertwined and rely on each other to
achieve optimal results.
• An algorithm applied to a particular data structure while using the right data
structure helps drastically improve an algorithm’s performance.
• Hence, we can’t detach data structures and algorithms.

69
Relationship between “Data
Structure” & “Algorithm”

Following are the main categories of algorithms in relation to data structures.


• Search: This algorithm helps in finding an item in a data structure.
• Insert: To Insert an item in a data structure; this algorithm is applicable
• Sort: This algorithm helps to sort items in a specific order.
• Update: The update algorithm is useful for updating an existing item in a data
structure.
• Delete: In order to delete an existing item from a data structure, you can use the
delete algorithm.

70
What is a good algorithm?
It must be correct
It must be finite (in terms of time and size)
 It must terminate
 It must be unambiguous
 Which step is next?
 It must be space and time efficient

A program is an instance of an algorithm, written in some specific


programming language
A simple algorithm

Problem: Find maximum of a, b, c


Algorithm
 Input = a, b, c
 Output = max
 Process
o Let max = a
o If b > max then
• max = b
o If c > max then
• max = c
o Display max
• Order is very important!!!
Algorithm development: Basics

 Clearly identify:
 what output is required?
 what is the input?
 What steps are required to transform input into output
o The most crucial bit
o Needs problem solving skills
o A problem can be solved in many different ways
o Which solution, amongst the different possible solutions is optimal?
How to Express an Algorithm?

• A sequence of steps to solve a problem


• We need a way to express this sequence of steps
1. Natural language (NL) is an obvious choice, but not a good choice. Why?
o NLs are notoriously ambiguous (unclear)
2. Programming language (PL) is another choice, but again not a good choice. Why?
o Algorithm should be PL independent

So, We need some balance


o We need PL independence
o We need clarity
o Pseudo-code provides the right balance
74
What are Pseudo code?

• Pseudo-code is a short hand way of describing a computer program


• Rather than using the specific syntax of a computer language, more general
wording is used
• It is a mixture of NL and PL expressions, in a systematic way
• Using pseudo-code, it is easier for a non-programmer to understand the general
workings of the program
Pseudo-code: General Guidelines

• Use PLs construct that are consistent with modern high level languages, e.g. C+
+, Java, ...
• Use appropriate comments for clarity
• Be simple and precise
Components of Pseudo-Code(Continue…)
• Decision structures (if-then-else logic)

 if condition then
true-actions
[else

false-actions]
 We use indentation to indicate what actions should be included in the true-actions and false-actions
 For example

if marks > 50 then


print “Congratulation, you are passed!”
else
print “Sorry, you are failed!”
end if
What will be the output if marks are equal to 75?
What will be the output if marks are equal to 45?
Components of Pseudo-code (cont.)

• Loops (Repetition)
• Pre-condition loops Initialization Decision Increment
o For loops
• for variable-increment-definition do actions
• For example
for counter ← 0; counter < 5; counter ← counter + 2 do
print “Welcome to CS2163!”
end for

What will be the output?


Components of Pseudo-code (cont.)

• Loops (Repetition)
• Pre-condition loops Initialization is done before the loop
o While loops starts
• while condition do actions
• We use indentation to indicate what actions should be included in the loop
actions
Decision
• For example
counter = 0 Increment
while counter < 5 do
print “Welcome to CS2163!”
counter ← counter + 1
end while

What will be the output if counter is initialised to 7?


Components of Pseudo-code (cont.)

• Loops (Repetition)
 Post-condition loops
o Do loops Action
• do actions while condition
• For example
do Increment
print “Welcome to CS204!”
counter ← counter + 1 Decision
while counter < 5

What will be the output, if counter was initialised to 10?

The body of a post-condition loop must execute at least once


While loop Vs Do-While loop

Flowchart of while Loop Flowchart of do-while Loop


Components of Pseudo-code (cont.)

 Comments
• /* Multiple line comments go here */
• // Single line comments go here
• Some people prefer braces {}, for comments
 Arrays
• A[i] represents the ith cell in the array A.
• The cells of an n-celled array A are indexed from A[0] to A[n − 1].
Algorithm Design: Practice

Example 1: Determining even/odd number


o A number divisible by 2 is considered an even number, while a number which is
not divisible by 2 is considered an odd number. Write pseudo-code to display first
N odd/even numbers.
Even/ Odd Numbers

• Input range
• for num←0; num<=range; num←num+1 do
• if num % 2 = 0 then
• print num is even
• else
• print num is odd
• endif
• endfor
•Programming Examples

ADD A FOOTER 85
Demonstration of If-Else in C+
+
Example:
Program to check whether an integer is
positive or negative

Output:

86
Demonstration of For-Loop in
C++
Example1:
Printing Numbers From 1 to 5

Output:

87
Demonstration of For-Loop in
C++
Example2:
Display a text 5 times

Output:

88
Demonstration of While-Loop
in C++
Example1:
Display Numbers from 1 to 5

Output:

89
What will be the output if “i” is initialised to 6?
Demonstration of Do-While Loop in C+
+

Example1:
Display Numbers from 1 to 5

Output:

90
What will be the output if “i” is initialised to 6?
Assignment #1


1. Write a C++ program to find grading (A, B, C, and F) of
a student according to following conditions

 If the numbers of student is above 80, assign grade A


 If the numbers of student is above 70, assign grade B
 If the numbers of student is above 50, assign grade C
 And if the numbers of student is less than 50, assign grade F

somi.mscs2013@[Link]
Deadline: 3rd November, 2023
93

You might also like