Week 1 Cs 2
Week 1 Cs 2
Introduction.
第一章 (1) 绪论
• 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.
• 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
•
Why Learn Programming?
• 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:
Source Code
(Program)
Computer
Running An Outputs
Interpreter
Inputs
• 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)
• 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
• 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.
Read Sheets
Yes
Set Stamps =
Sheets/3
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
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
29
Continue…
• 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.
• 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 these books are sorted in each section of library then it is easy to find the required book
quickly.
• 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
38
Motivation
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
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
21 3.14 ‘a’
44
Data Types & Data Structures
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
• 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
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
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…
59
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
67
69
Relationship between “Data
Structure” & “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
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?
• 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
• 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
• 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
• 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
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
• 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
somi.mscs2013@[Link]
Deadline: 3rd November, 2023
93