SlideShare a Scribd company logo
1 of 56
Data Structures and Alglorithms
Prepared by: Afaq Mansoor Khan
BSSE III- Group A
Session 2017-21
IMSciences, Peshawar.
Course Details
• Course Title: Data Structures
• Credit Hours: 3 + 1
• Course Objectives:
The course is designed to teach students
structures and schemes, which allow them to
write programs to efficiently manipulate,
store, and retrieve data.
Course Description
• In recent years the subject of computer programming
has been recognized as a discipline whose mastery is
fundamental and crucial to the success of many
engineering projects and which is close to scientific
treatment and presentation.
• It has advanced from a skill to an academic discipline
• it is abundantly clear that a systematic and scientific
approach to program construction primarily has a
bearing in the case of large, complex programs which
involve complicated sets of data.
• Hence, a methodology of programming is also bound to
include all aspects of data structuring.
Course Objectives
• To extend and deepen the student's knowledge and
understanding of algorithms and data structures
• To examine previously studied algorithms and data
structures more rigorously and introduce the
students to "new" algorithms and data structures.
• It focuses the student's attention on the design of
program structures that are correct, efficient in both
time and space utilization, and defined in terms of
appropriate abstractions.
Course Goals
• Upon completion of this course, a successful student will
be able to:
▫ Describe the strengths and limitations of linear data
structures, trees, graphs
▫ Select appropriate data structures for a specified problem
▫ Compare and contrast the basic data structures used in
Computer Science: lists, stacks, queues, trees and graphs
▫ Describe classic sorting techniques
▫ Recognize when and how to use the following data
structures: arrays, linked lists, stacks, queues and binary
trees.
▫ Identify and implement the basic operations for
manipulating each type of data structure
Course Goals
• Upon completion of this course, a successful student
will be able to:
▫ Perform sequential searching, binary searching and hashing
algorithms.
▫ Apply various sorting algorithms including bubble,
insertion, selection and quick sort.
▫ Understand recursion and be able to give examples of its
use
▫ Use dynamic data structures
Course Outline - I
• Introduction to data structures
• Linear and non-linear data structures
• Arrays and pointers
• List data structure
• Singly linked list
• Doubly linked list
• Circular linked list
• Stack; Implementation of stack using arrays and
linked list
• Applications of a stack
Course Outline - II
• Infix to postfix conversion
• Evaluation of postfix expressions
• Queues; Implementation of queues using arrays and
linked list
• Circular Queues; Priority Queues;
• Trees; Tree traversals; Binary search trees and
implementation
• Heaps and Heap sort;
• Graphs; Minimum spanning trees;
• Hashing
• Files
Recommended Books
Textbook:
• Robert L. Kruse, Alexander J. Ryba, Data Structures & Program Design in C++,
Prentice Hall, New Jersey, USA
Reference Books:
• Debasis Samanta, Classic Data Structures, 2nd Edition, Prentice Hall India,
2009
• ISRD Group, Data Structures Using C, Tata McGraw-Hill Publishing Company,
New Delhi, India, 2006.
Marks Distribution of Course
 Assignments ……….……… 10%
 Quizzes ..…………….. 10%
 Midterm Exam .………….….. 30%
 Final Exam .……………… 50%
Objectives Overview for this Lecture
• Introduction to Data Structures & Algorithms
• One Dimensional Arrays
• Two Dimensional Arrays
12
What is it all about?
• Solving problems
▫ Get me from home to work
▫ Balance my checkbook
▫ Simulate a jet engine
▫ Graduate from SPU
• Using a computer to help solve problems
▫ Designing programs (architecture, algorithms)
▫ Writing programs
▫ Verifying programs
▫ Documenting programs
13
Data Structures and Algorithms
• Algorithm
▫ Outline, the essence of a computational procedure,
step-by-step instructions
• Program – an implementation of an algorithm in
some programming language
• Data structure
▫ Organization of data needed to solve the problem
14
Overall Picture
• This course is not about:
▫ Programming languages
▫ Computer architecture
▫ Software architecture
▫ Software design and implementation principles
 Issues concerning small and large scale programming
• We will only touch upon the theory of complexity
and computability
What is Data Structures?
• Example:library
▫ is composed of elements
(books)
▫ Accessing a particular book
requires knowledge of the
arrangement of the books
▫ Users access books only
through the librarian
the logical arrangement of data
elements, combined with
the set of operations we need to access
the elements.
Basic Data Structures
• Structures include
▫ linked lists
▫ Stack, Queue
▫ binary trees
▫ …and others
What is Algorithm?
• Algorithm:
▫ A computable set of steps to achieve a desired result
▫ Ralationship to Data Structure
 Example: Find an element
1 2 3 4 5 6 7
1
2
3
4
5
6
7
Introducing Arrays
Array is a data structure that represents a collection
of the same types of data.
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
double[] myList = new double[10];
myList reference
An Array of 10
Elements
of type double
Declaring Array Variables
• datatype[] arrayname;
Example:
double[] myList;
• datatype arrayname[];
Example:
double myList[];
Creating Arrays
arrayName = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
Declaring and Creating in One Step
• datatype[] arrayname = new
datatype[arraySize];
double[] myList = new double[10];
• datatype arrayname[] = new
datatype[arraySize];
double myList[] = new double[10];
The Length of Arrays
• Once an array is created, its size is fixed. It
cannot be changed. You can find its size using
arrayVariable.length
For example,
myList.length returns 10
Initializing Arrays
• Using a loop:
for (int i = 0; i < myList.length; i++)
myList[i] = i;
• Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one statement.
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
CAUTION
Using the shorthand notation, you have to
declare, create, and initialize the array all in
one statement. Splitting it would cause a
syntax error. For example, the following is
wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
Testing Arrays
• Objective: The program receives 6 numbers from
the keyboard, finds the largest number and
counts the occurrence of the largest number
entered from the keyboard.
Suppose you entered 3, 5, 2, 5, 5, and 5, the
largest number is 5 and its occurrence count is 4.
TestArray Run
Assigning Grades
• Objective: read student scores (int) from the
keyboard, get the best score, and then assign
grades based on the following scheme:
▫ Grade is A if score is >= best–10;
▫ Grade is B if score is >= best–20;
▫ Grade is C if score is >= best–30;
▫ Grade is D if score is >= best–40;
▫ Grade is F otherwise.
AssignGrade
Run
Passing Arrays as Arguments
• Objective: Demonstrate differences of
passing primitive data type variables
and array variables.
TestPassArray Run
Example
swapFirstTwoInArray(a)
swapFirstTwoInArray(array)
Pass by value (Reference value)
a Reference
:
a[0]
a[1]
array Reference
swap(a[0], a[1])
swap( n1, n2)
Pass by value
a[0] 1 2
n1 n21 2
a[1]
Copying Arrays
In this example, you will see that a simple
assignment cannot copy arrays in the
following program. The program simply
creates two arrays and attempts to copy one
to the other, using an assignment statement.
TestCopyArray Run
Copying Arrays
Contents
of list1
list1
Contents
of list2
list2
Before the assignment
list2 = list1;
Contents
of list1
list1
Contents
of list2
list2
After the assignment
list2 = list1;
Garbage
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArrays.length; i++)
targetArray[i] = sourceArray[i];
Multidimensional Arrays
Declaring Variables of Multidimensional Arrays and Creating
Multidimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;
for (int i=0; i<matrix.length; i++)
for (int j=0; j<matrix[i].length; j++)
{
matrix[i][j] = (int)(Math.random()*1000);
}
double[][] x;
Multidimensional Array Illustration
0 1 2 3 4
0
7
0 1 2 3 4
1
2
3
4
0
1
2
3
4
matrix[2][1] = 7;matrix = new int[5][5];
3
7
0 1 2
0
1
2
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
1 2 3
4 5 6
8 9
10 11 12
Declaring, Creating, and Initializing Using Shorthand
Notations
You can also use a shorthand notation to declare, create and initialize a two-dimensional
array. For example,
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
This is equivalent to the following statements:
int[][] array = new int[4][3];
array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
Lengths of Multidimensional Arrays
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
array.length
array[0].length
array[1].length
array[2].length
Definition – Pointer
• A value indicating the number of (the first byte of)
a data object
▫ Also called an Address or a Location
• Used in machine language to identify which data
to access
 E.g., stack pointer is address of most recent entry of The Stack
• Usually 2, 4, or 8 bytes, depending upon machine
architecture
∙∙∙
2n-10 1 2 3 4 5 6 7 8 9 10 11
11
Memory Addressing
0x00000000
0xFFFFFFFF
address space
program code
(text)
static data
heap
(dynamically allocated)
stack
(dynamically allocated)
PC
SP
Declaring Pointers in C
• int *p; — a pointer to an int
• double *q; — a pointer to a double
• char **r; — a pointer to a pointer to a
char
• type *s; — a pointer to an object of
type type
 E.g, a struct, union, function, something defined by a typedef, etc.
Declaring Pointers in C (continued)
• Pointer declarations:–read from right to left
• const int *p;
 p is a pointer to an integer constant
 I.e., pointer can change, thing it points to cannot
• int * const q;
 q is a constant pointer to an integer variable
 I.e., pointer cannot change, thing it points to can!
• const int * const r;
 r is a constant pointer to an integer constant
Pointer Operations in C
• Creation
& variable Returns variable’s memory address
• Dereference
* pointer Returns contents stored at address
• Indirect assignment
• pointer = val Stores value at address
• Of course, still have...
• Assignment
pointer = ptr Stores pointer in another variable
Using Pointers
int i1;
int i2;
int *ptr1;
int *ptr2;
i1 = 1;
i2 = 2;
ptr1 = &i1;
ptr2 = ptr1;
*ptr1 = 3;
i2 = *ptr2;
i1:
i2:
ptr1:
0x1000
0x1004
0x1008
…
ptr2:
…
0x100C
0x1010
0x1014
1
2
0x1000
0x1000
3
3
Pointer Arithmetic
• int *p, *q;
q = p + 1;
▫ Construct a pointer to the next integer after *p and
assign it to q
• double *p, *r;
int n;
r = p + n;
▫ Construct a pointer to a double that is n doubles beyond
*p, and assign it to r
▫ n may be negative
Pointer Arithmetic (continued)
• long int *p, *q;
p++; q--;
▫ Increment p to point to the next long int; decrement q to
point to the previous long int
• float *p, *q;
int n;
n = p – q;
▫ n is the number of floats between *p and *q; i.e., what
would be added to q to get p
Pointer Arithmetic
pointer + number pointer – number
E.g., pointer + 1 adds 1 something to a pointer
char *p;
char a;
char b;
p = &a;
p += 1;
int *p;
int a;
int b;
p = &a;
p += 1;In each, p now points to b
(Assuming compiler doesn’t
reorder variables in memory)
Adds 1*sizeof(char) to
the memory address
Adds 1*sizeof(int) to
the memory address
Pointer arithmetic should be used cautiously
46
Pass-by-Reference
void
set_x_and_y(int *x,
int *y)
{
*x = 1001;
*y = 1002;
}
void
f(void)
{
int a = 1;
int b = 2;
set_x_and_y(&a,&b);
}
1
2
a
b
x
y
1001
1002
Arrays and Pointers
• Arrays and pointers are closely related in C
▫ In fact, they are essentially the same thing!
▫ Esp. when used as parameters of functions
• int A[10];
int *p;
▫ Type of A is int *
▫ p = A; and A = p; are legal assignments
▫ *p refers to A[0]
*(p + n) refers to A[n]
▫ p = &A[5]; is the same as p = A + 5;
Arrays and Pointers (continued)
• double A[10]; vs. double *A;
• Only difference:–
▫ double A[10] sets aside ten units of memory, each large
enough to hold a double
▫ double *A sets aside one pointer-sized unit of memory
 You are expected to come up with the memory elsewhere!
▫ Note:– all pointer variables are the same size in any given
machine architecture
 Regardless of what types they point to
Note
• C does not assign arrays to each other
• E.g,
▫ double A[10];
double B[10];
A = B;
 assigns the pointer value B to the pointer value A
 Contents of array A are untouched
Arrays as Function Parameters
• void init(float A[], int arraySize);
void init(float *A, int arraySize);
• Are identical function prototypes!
• Pointer is passed by value
• I.e. caller copies the value of a pointer to float into the
parameter A
• Called function can reference through that pointer to
reach thing pointed to
Arrays as Function Parameters (continued)
• void init(float A[], int arraySize){
int n;
for(n = 0; n < arraySize; n++)
A[n] = (float)n;
} //init
• Assigns values to the array A in place
▫ So that caller can see the changes!
Examples
while ((rc = scanf("%lf", &array[count])) !=EOF && rc==0)
…
double getLargest(const double A[], const int sizeA) {
double d;
if (sizeA > 0) {
d = getLargest(&A[1], sizeA-1);
return (d > A[0]) ? d : A[0];
} else
return A[0];
} // getLargest
Result
• Even though all arguments are passed by value to
functions …
• … pointers allow functions to assign back to data of
caller
• Arrays are pointers passed by value
Safety Note
• When passing arrays to functions, always specify const
if you don’t want function changing the value of any
elements
• Reason:– you don’t know whether your function would
pass array to another before returning to you
 Exception – many software packages don’t specify const in
their own headers, so you can’t either!
Summary
• Introduction to Data Structures & Algorithms
• One Dimensional Arrays:
• Multi Dimensional Arrays:
▫ Declaration
▫ Initialization
▫ Representation
▫ Operations
▫ Arrays and functions
• Pointers
▫ Declaration, Initialization
▫ Arrays and pointers
References
• www.cse.ust.hk/~liao/comp102/PPT/array.ppt
• https://www.geeksforgeeks.org/array-data-
structure/
• http://www.cplusplus.com/doc/tutorial/arrays/
• https://cs.nyu.edu/courses/fall03/V22.0101-
002/05slide.ppt
• https://processing.org/tutorials/arrays/

More Related Content

What's hot

Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptxSyed Zaid Irshad
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithmPratik Mota
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 
Data Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxData Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxEllenGrace9
 
Algorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IAlgorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IMohamed Loey
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1Kumar
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]DEEPIKA T
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structureAbrish06
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its FundamentalsHitesh Mohapatra
 
Data structure power point presentation
Data structure power point presentation Data structure power point presentation
Data structure power point presentation Anil Kumar Prajapati
 

What's hot (20)

Queue ppt
Queue pptQueue ppt
Queue ppt
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Python list
Python listPython list
Python list
 
Data Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxData Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptx
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
Algorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IAlgorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms I
 
Array in c#
Array in c#Array in c#
Array in c#
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Data structure power point presentation
Data structure power point presentation Data structure power point presentation
Data structure power point presentation
 

Similar to DS Algorithms Course Overview

Data structure and algorithm.
Data structure and algorithm. Data structure and algorithm.
Data structure and algorithm. Abdul salam
 
Algorithms and Data Structures
Algorithms and Data StructuresAlgorithms and Data Structures
Algorithms and Data Structuressonykhan3
 
DSA 1- Introduction.pdf
DSA 1- Introduction.pdfDSA 1- Introduction.pdf
DSA 1- Introduction.pdfAliyanAbbas1
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptxclassall
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptxclassall
 
b,Sc it data structure.ppt
b,Sc it data structure.pptb,Sc it data structure.ppt
b,Sc it data structure.pptclassall
 
Data Structure and Algorithms
Data Structure and AlgorithmsData Structure and Algorithms
Data Structure and Algorithmsiqbalphy1
 
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...DrkhanchanaR
 
Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01shaziabibi5
 
Intro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsIntro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsAkhil Kaushik
 
data structures and its importance
 data structures and its importance  data structures and its importance
data structures and its importance Anaya Zafar
 
Data Structures - Lecture 1 - Unit 1.pptx
Data Structures  - Lecture 1 - Unit 1.pptxData Structures  - Lecture 1 - Unit 1.pptx
Data Structures - Lecture 1 - Unit 1.pptxDanielNesaKumarC
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionOUM SAOKOSAL
 
Data Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxData Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxGIRISHKUMARBC1
 

Similar to DS Algorithms Course Overview (20)

Data structure and algorithm.
Data structure and algorithm. Data structure and algorithm.
Data structure and algorithm.
 
Algorithms and Data Structures
Algorithms and Data StructuresAlgorithms and Data Structures
Algorithms and Data Structures
 
DSA 1- Introduction.pdf
DSA 1- Introduction.pdfDSA 1- Introduction.pdf
DSA 1- Introduction.pdf
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptx
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptx
 
b,Sc it data structure.ppt
b,Sc it data structure.pptb,Sc it data structure.ppt
b,Sc it data structure.ppt
 
Data Structure and Algorithms
Data Structure and AlgorithmsData Structure and Algorithms
Data Structure and Algorithms
 
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
 
Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01
 
Intro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsIntro to Data Structure & Algorithms
Intro to Data Structure & Algorithms
 
data structures and its importance
 data structures and its importance  data structures and its importance
data structures and its importance
 
Data Structures - Lecture 1 - Unit 1.pptx
Data Structures  - Lecture 1 - Unit 1.pptxData Structures  - Lecture 1 - Unit 1.pptx
Data Structures - Lecture 1 - Unit 1.pptx
 
Intro_2.ppt
Intro_2.pptIntro_2.ppt
Intro_2.ppt
 
Intro.ppt
Intro.pptIntro.ppt
Intro.ppt
 
Intro.ppt
Intro.pptIntro.ppt
Intro.ppt
 
Lecture 1 (bce-7)
Lecture   1 (bce-7)Lecture   1 (bce-7)
Lecture 1 (bce-7)
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 
Data Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxData Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptx
 
algo 1.ppt
algo 1.pptalgo 1.ppt
algo 1.ppt
 
Data structure
Data structureData structure
Data structure
 

More from Afaq Mansoor Khan

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingAfaq Mansoor Khan
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in PakistanAfaq Mansoor Khan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAfaq Mansoor Khan
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An OverviewAfaq Mansoor Khan
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design DecisionsAfaq Mansoor Khan
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinAfaq Mansoor Khan
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - AsteroidsAfaq Mansoor Khan
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsAfaq Mansoor Khan
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked ListsAfaq Mansoor Khan
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & DeletionAfaq Mansoor Khan
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked ListsAfaq Mansoor Khan
 

More from Afaq Mansoor Khan (20)

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language Processing
 
WiFi vs LiFi - A Comparison
WiFi vs LiFi - A ComparisonWiFi vs LiFi - A Comparison
WiFi vs LiFi - A Comparison
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in Pakistan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and Strategies
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An Overview
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design Decisions
 
How to Design an Algorithm
How to Design an AlgorithmHow to Design an Algorithm
How to Design an Algorithm
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and Linkedin
 
Quick sort
Quick sortQuick sort
Quick sort
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - Asteroids
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
Binary tree
Binary treeBinary tree
Binary tree
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked Lists
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 

Recently uploaded

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 

Recently uploaded (20)

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 

DS Algorithms Course Overview

  • 1. Data Structures and Alglorithms Prepared by: Afaq Mansoor Khan BSSE III- Group A Session 2017-21 IMSciences, Peshawar.
  • 2. Course Details • Course Title: Data Structures • Credit Hours: 3 + 1 • Course Objectives: The course is designed to teach students structures and schemes, which allow them to write programs to efficiently manipulate, store, and retrieve data.
  • 3. Course Description • In recent years the subject of computer programming has been recognized as a discipline whose mastery is fundamental and crucial to the success of many engineering projects and which is close to scientific treatment and presentation. • It has advanced from a skill to an academic discipline • it is abundantly clear that a systematic and scientific approach to program construction primarily has a bearing in the case of large, complex programs which involve complicated sets of data. • Hence, a methodology of programming is also bound to include all aspects of data structuring.
  • 4. Course Objectives • To extend and deepen the student's knowledge and understanding of algorithms and data structures • To examine previously studied algorithms and data structures more rigorously and introduce the students to "new" algorithms and data structures. • It focuses the student's attention on the design of program structures that are correct, efficient in both time and space utilization, and defined in terms of appropriate abstractions.
  • 5. Course Goals • Upon completion of this course, a successful student will be able to: ▫ Describe the strengths and limitations of linear data structures, trees, graphs ▫ Select appropriate data structures for a specified problem ▫ Compare and contrast the basic data structures used in Computer Science: lists, stacks, queues, trees and graphs ▫ Describe classic sorting techniques ▫ Recognize when and how to use the following data structures: arrays, linked lists, stacks, queues and binary trees. ▫ Identify and implement the basic operations for manipulating each type of data structure
  • 6. Course Goals • Upon completion of this course, a successful student will be able to: ▫ Perform sequential searching, binary searching and hashing algorithms. ▫ Apply various sorting algorithms including bubble, insertion, selection and quick sort. ▫ Understand recursion and be able to give examples of its use ▫ Use dynamic data structures
  • 7. Course Outline - I • Introduction to data structures • Linear and non-linear data structures • Arrays and pointers • List data structure • Singly linked list • Doubly linked list • Circular linked list • Stack; Implementation of stack using arrays and linked list • Applications of a stack
  • 8. Course Outline - II • Infix to postfix conversion • Evaluation of postfix expressions • Queues; Implementation of queues using arrays and linked list • Circular Queues; Priority Queues; • Trees; Tree traversals; Binary search trees and implementation • Heaps and Heap sort; • Graphs; Minimum spanning trees; • Hashing • Files
  • 9. Recommended Books Textbook: • Robert L. Kruse, Alexander J. Ryba, Data Structures & Program Design in C++, Prentice Hall, New Jersey, USA Reference Books: • Debasis Samanta, Classic Data Structures, 2nd Edition, Prentice Hall India, 2009 • ISRD Group, Data Structures Using C, Tata McGraw-Hill Publishing Company, New Delhi, India, 2006.
  • 10. Marks Distribution of Course  Assignments ……….……… 10%  Quizzes ..…………….. 10%  Midterm Exam .………….….. 30%  Final Exam .……………… 50%
  • 11. Objectives Overview for this Lecture • Introduction to Data Structures & Algorithms • One Dimensional Arrays • Two Dimensional Arrays
  • 12. 12 What is it all about? • Solving problems ▫ Get me from home to work ▫ Balance my checkbook ▫ Simulate a jet engine ▫ Graduate from SPU • Using a computer to help solve problems ▫ Designing programs (architecture, algorithms) ▫ Writing programs ▫ Verifying programs ▫ Documenting programs
  • 13. 13 Data Structures and Algorithms • Algorithm ▫ Outline, the essence of a computational procedure, step-by-step instructions • Program – an implementation of an algorithm in some programming language • Data structure ▫ Organization of data needed to solve the problem
  • 14. 14 Overall Picture • This course is not about: ▫ Programming languages ▫ Computer architecture ▫ Software architecture ▫ Software design and implementation principles  Issues concerning small and large scale programming • We will only touch upon the theory of complexity and computability
  • 15. What is Data Structures? • Example:library ▫ is composed of elements (books) ▫ Accessing a particular book requires knowledge of the arrangement of the books ▫ Users access books only through the librarian the logical arrangement of data elements, combined with the set of operations we need to access the elements.
  • 16. Basic Data Structures • Structures include ▫ linked lists ▫ Stack, Queue ▫ binary trees ▫ …and others
  • 17. What is Algorithm? • Algorithm: ▫ A computable set of steps to achieve a desired result ▫ Ralationship to Data Structure  Example: Find an element 1 2 3 4 5 6 7 1 2 3 4 5 6 7
  • 18. Introducing Arrays Array is a data structure that represents a collection of the same types of data. myList[0] myList[1] myList[2] myList[3] myList[4] myList[5] myList[6] myList[7] myList[8] myList[9] double[] myList = new double[10]; myList reference An Array of 10 Elements of type double
  • 19. Declaring Array Variables • datatype[] arrayname; Example: double[] myList; • datatype arrayname[]; Example: double myList[];
  • 20. Creating Arrays arrayName = new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.
  • 21. Declaring and Creating in One Step • datatype[] arrayname = new datatype[arraySize]; double[] myList = new double[10]; • datatype arrayname[] = new datatype[arraySize]; double myList[] = new double[10];
  • 22. The Length of Arrays • Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayVariable.length For example, myList.length returns 10
  • 23. Initializing Arrays • Using a loop: for (int i = 0; i < myList.length; i++) myList[i] = i; • Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
  • 24. Declaring, creating, initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
  • 25. CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};
  • 26. Testing Arrays • Objective: The program receives 6 numbers from the keyboard, finds the largest number and counts the occurrence of the largest number entered from the keyboard. Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its occurrence count is 4. TestArray Run
  • 27. Assigning Grades • Objective: read student scores (int) from the keyboard, get the best score, and then assign grades based on the following scheme: ▫ Grade is A if score is >= best–10; ▫ Grade is B if score is >= best–20; ▫ Grade is C if score is >= best–30; ▫ Grade is D if score is >= best–40; ▫ Grade is F otherwise. AssignGrade Run
  • 28. Passing Arrays as Arguments • Objective: Demonstrate differences of passing primitive data type variables and array variables. TestPassArray Run
  • 29. Example swapFirstTwoInArray(a) swapFirstTwoInArray(array) Pass by value (Reference value) a Reference : a[0] a[1] array Reference swap(a[0], a[1]) swap( n1, n2) Pass by value a[0] 1 2 n1 n21 2 a[1]
  • 30. Copying Arrays In this example, you will see that a simple assignment cannot copy arrays in the following program. The program simply creates two arrays and attempts to copy one to the other, using an assignment statement. TestCopyArray Run
  • 31. Copying Arrays Contents of list1 list1 Contents of list2 list2 Before the assignment list2 = list1; Contents of list1 list1 Contents of list2 list2 After the assignment list2 = list1; Garbage
  • 32. Copying Arrays Using a loop: int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];
  • 33. Multidimensional Arrays Declaring Variables of Multidimensional Arrays and Creating Multidimensional Arrays int[][] matrix = new int[10][10]; or int matrix[][] = new int[10][10]; matrix[0][0] = 3; for (int i=0; i<matrix.length; i++) for (int j=0; j<matrix[i].length; j++) { matrix[i][j] = (int)(Math.random()*1000); } double[][] x;
  • 34. Multidimensional Array Illustration 0 1 2 3 4 0 7 0 1 2 3 4 1 2 3 4 0 1 2 3 4 matrix[2][1] = 7;matrix = new int[5][5]; 3 7 0 1 2 0 1 2 int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; 1 2 3 4 5 6 8 9 10 11 12
  • 35. Declaring, Creating, and Initializing Using Shorthand Notations You can also use a shorthand notation to declare, create and initialize a two-dimensional array. For example, int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; This is equivalent to the following statements: int[][] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
  • 36. Lengths of Multidimensional Arrays int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length array[0].length array[1].length array[2].length
  • 37. Definition – Pointer • A value indicating the number of (the first byte of) a data object ▫ Also called an Address or a Location • Used in machine language to identify which data to access  E.g., stack pointer is address of most recent entry of The Stack • Usually 2, 4, or 8 bytes, depending upon machine architecture ∙∙∙ 2n-10 1 2 3 4 5 6 7 8 9 10 11 11
  • 38. Memory Addressing 0x00000000 0xFFFFFFFF address space program code (text) static data heap (dynamically allocated) stack (dynamically allocated) PC SP
  • 39. Declaring Pointers in C • int *p; — a pointer to an int • double *q; — a pointer to a double • char **r; — a pointer to a pointer to a char • type *s; — a pointer to an object of type type  E.g, a struct, union, function, something defined by a typedef, etc.
  • 40. Declaring Pointers in C (continued) • Pointer declarations:–read from right to left • const int *p;  p is a pointer to an integer constant  I.e., pointer can change, thing it points to cannot • int * const q;  q is a constant pointer to an integer variable  I.e., pointer cannot change, thing it points to can! • const int * const r;  r is a constant pointer to an integer constant
  • 41. Pointer Operations in C • Creation & variable Returns variable’s memory address • Dereference * pointer Returns contents stored at address • Indirect assignment • pointer = val Stores value at address • Of course, still have... • Assignment pointer = ptr Stores pointer in another variable
  • 42. Using Pointers int i1; int i2; int *ptr1; int *ptr2; i1 = 1; i2 = 2; ptr1 = &i1; ptr2 = ptr1; *ptr1 = 3; i2 = *ptr2; i1: i2: ptr1: 0x1000 0x1004 0x1008 … ptr2: … 0x100C 0x1010 0x1014 1 2 0x1000 0x1000 3 3
  • 43. Pointer Arithmetic • int *p, *q; q = p + 1; ▫ Construct a pointer to the next integer after *p and assign it to q • double *p, *r; int n; r = p + n; ▫ Construct a pointer to a double that is n doubles beyond *p, and assign it to r ▫ n may be negative
  • 44. Pointer Arithmetic (continued) • long int *p, *q; p++; q--; ▫ Increment p to point to the next long int; decrement q to point to the previous long int • float *p, *q; int n; n = p – q; ▫ n is the number of floats between *p and *q; i.e., what would be added to q to get p
  • 45. Pointer Arithmetic pointer + number pointer – number E.g., pointer + 1 adds 1 something to a pointer char *p; char a; char b; p = &a; p += 1; int *p; int a; int b; p = &a; p += 1;In each, p now points to b (Assuming compiler doesn’t reorder variables in memory) Adds 1*sizeof(char) to the memory address Adds 1*sizeof(int) to the memory address Pointer arithmetic should be used cautiously
  • 46. 46 Pass-by-Reference void set_x_and_y(int *x, int *y) { *x = 1001; *y = 1002; } void f(void) { int a = 1; int b = 2; set_x_and_y(&a,&b); } 1 2 a b x y 1001 1002
  • 47. Arrays and Pointers • Arrays and pointers are closely related in C ▫ In fact, they are essentially the same thing! ▫ Esp. when used as parameters of functions • int A[10]; int *p; ▫ Type of A is int * ▫ p = A; and A = p; are legal assignments ▫ *p refers to A[0] *(p + n) refers to A[n] ▫ p = &A[5]; is the same as p = A + 5;
  • 48. Arrays and Pointers (continued) • double A[10]; vs. double *A; • Only difference:– ▫ double A[10] sets aside ten units of memory, each large enough to hold a double ▫ double *A sets aside one pointer-sized unit of memory  You are expected to come up with the memory elsewhere! ▫ Note:– all pointer variables are the same size in any given machine architecture  Regardless of what types they point to
  • 49. Note • C does not assign arrays to each other • E.g, ▫ double A[10]; double B[10]; A = B;  assigns the pointer value B to the pointer value A  Contents of array A are untouched
  • 50. Arrays as Function Parameters • void init(float A[], int arraySize); void init(float *A, int arraySize); • Are identical function prototypes! • Pointer is passed by value • I.e. caller copies the value of a pointer to float into the parameter A • Called function can reference through that pointer to reach thing pointed to
  • 51. Arrays as Function Parameters (continued) • void init(float A[], int arraySize){ int n; for(n = 0; n < arraySize; n++) A[n] = (float)n; } //init • Assigns values to the array A in place ▫ So that caller can see the changes!
  • 52. Examples while ((rc = scanf("%lf", &array[count])) !=EOF && rc==0) … double getLargest(const double A[], const int sizeA) { double d; if (sizeA > 0) { d = getLargest(&A[1], sizeA-1); return (d > A[0]) ? d : A[0]; } else return A[0]; } // getLargest
  • 53. Result • Even though all arguments are passed by value to functions … • … pointers allow functions to assign back to data of caller • Arrays are pointers passed by value
  • 54. Safety Note • When passing arrays to functions, always specify const if you don’t want function changing the value of any elements • Reason:– you don’t know whether your function would pass array to another before returning to you  Exception – many software packages don’t specify const in their own headers, so you can’t either!
  • 55. Summary • Introduction to Data Structures & Algorithms • One Dimensional Arrays: • Multi Dimensional Arrays: ▫ Declaration ▫ Initialization ▫ Representation ▫ Operations ▫ Arrays and functions • Pointers ▫ Declaration, Initialization ▫ Arrays and pointers
  • 56. References • www.cse.ust.hk/~liao/comp102/PPT/array.ppt • https://www.geeksforgeeks.org/array-data- structure/ • http://www.cplusplus.com/doc/tutorial/arrays/ • https://cs.nyu.edu/courses/fall03/V22.0101- 002/05slide.ppt • https://processing.org/tutorials/arrays/