SlideShare une entreprise Scribd logo
1  sur  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/

Contenu connexe

Tendances

Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Introduction to Data Structure and Algorithm
Introduction to Data Structure and AlgorithmIntroduction to Data Structure and Algorithm
Introduction to Data Structure and AlgorithmSagacious IT Solution
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST Kathirvel Ayyaswamy
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort AlgorithmLemia Algmri
 
Major issues in data mining
Major issues in data miningMajor issues in data mining
Major issues in data miningYashwant Rautela
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesAndrew Ferlitsch
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure pptNalinNishant3
 
Data structure and algorithm
Data structure and algorithmData structure and algorithm
Data structure and algorithmTrupti Agrawal
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functionsAmrit Kaur
 

Tendances (20)

Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Introduction to Data Structure and Algorithm
Introduction to Data Structure and AlgorithmIntroduction to Data Structure and Algorithm
Introduction to Data Structure and Algorithm
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Major issues in data mining
Major issues in data miningMajor issues in data mining
Major issues in data mining
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Computer Science-Data Structures :Abstract DataType (ADT)
Computer Science-Data Structures :Abstract DataType (ADT)Computer Science-Data Structures :Abstract DataType (ADT)
Computer Science-Data Structures :Abstract DataType (ADT)
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
stack & queue
stack & queuestack & queue
stack & queue
 
NUMPY
NUMPY NUMPY
NUMPY
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Data Structure and Algorithms
Data Structure and AlgorithmsData Structure and Algorithms
Data Structure and Algorithms
 
Heaps
HeapsHeaps
Heaps
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
Data structure and algorithm
Data structure and algorithmData structure and algorithm
Data structure and algorithm
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
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.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 

Dernier (20)

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
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
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 

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/