SlideShare a Scribd company logo
Arrays
Prof. Khuram Chattha
2
Two's complement representation
For negative n (–n):
(1) Find w-bit base-2 representation of n
(2) Complement each bit.
(3) Add 1
Example: –88
1. 88 as a 16-bit base-two number 0000000001011000
Same as
sign mag.
For nonnegative n:
Use ordinary base-two representation with leading (sign) bit 0
2. Complement this bit
string
3. Add 1
1111111110100111
1111111110101000
(Flip all bits from rightmost 0 to the
end)
3
Data Type, Data Structure, and Abstract Data Types
 Data Type
 Set of values that the variable may assume
 E.g., boolean = {false, true}, digit = {0, 1, 2, …., 9}
 Abstract Data Type
 A mathematical model, together with various operations defined on the model
 Algorithms are designed in terms of ADTs and implemented in terms of the data
types and operators supported by the programming language
 Data Structures
 Physical implementation of an ADT
 Data structures used in implementations are provided in a language (primitive or
built-in) or are built from the language constructs (user-defined)
 Each operation associated with the ADT is implemented by one or more
subroutines in the implementation
4
Separation of interface and implementation
 Think of ADT as a black box
 ADT is represented by an interface and implementation
is hidden from the user
 This means that the ADT can be implemented in various ways,
as long as it adheres to interface
 For example, a ListADT can be represented using an array
based implementation or a linked list implementation
5
Linear list data structure
 Def: An ordered collection of elements
 some examples are an alphabetized list of students, a list of gold
medal winners ordered by year, etc.
 With these examples in mind, we feel the need to perform the
following operations on a linear list
 Determine whether the list is empty
 Determine the size of list
 Find the element with a given index
 Find the index of a given element
 Delete an element given its index
 Insert a new element
6
ADT – linear List
 The ADT specification is independent of any representation and programming
language
AbstractDataType linearList
{
elements
ordered finite collection of zero or more elements
operations
empty(): return true if the list is empty
size(): return the list size
get(index): return the indexth element
indexOf(x): return the index of the first occurance of x in
the list, returns -1, if x is not in the list
erase(index): delete the indexth element, element with higher
index have their index reduced by 1
insert(index, x): insert x as the indexth element
output(): output the list elements from left to right
7
Array representation
 [5, 2, 4, 8,1]
 Some of the implementations can be
1
8
4
2
5
location(i) = i
5
2
4
8
1
location(i) = 9- i
4
2
5
1
8
location(i) = (7+i)%10
C++ Style Data Structures:
Arrays(1)
• An ordered set (sequence) with a fixed
number of elements, all of the same
type,
where the basic operation is
direct access to each element in the
array so values can be retrieved from
or stored in this element.
C++ Style Data Structures: Arrays (2)
Properties:
 Ordered so there is a first element, a second one, etc.
 Fixed number of elements — fixed capacity
 Elements must be the same type (and size);
 use arrays only for homogeneous data sets.
 Direct access: Access an element by giving its location
 The time to access each element is the same for all elements,
regardless of position.
 in contrast to sequential access (where to access an element,
one must first access all those that precede it.)
Declaring arrays in C++
where
element_type is any type
array_name is the name of the array — any valid identifier
CAPACITY (a positive integer constant) is the number of
elements in the array
score[0]
score[1]
score[2]
score[3]
score[99]
.
.
.
.
.
.
element_type array_name[CAPACITY];
e.g., double score[100];
The elements (or positions) of the array are indexed
0, 1, 2, . . ., CAPACITY - 1.
Can't input the capacity,
Why?
The compiler reserves a block of “consecutive”
memory locations, enough to hold CAPACITY values
of type element_type.
indices numbered 0, 1, 2, . . ., CAPACITY -
1
How well does C/C++ implement an array ADT?
As an ADT In C++
ordered
fixed size
same type
elements
direct access
element_type is the type of elements
CAPACITY specifies the capacity of the array
subscript operator
[]
an array literal
Array Initialization
Example:
double rate[5] = {0.11, 0.13, 0.16, 0.18, 0.21};
Note 1: If fewer values supplied than array's capacity, remaining
elements assigned 0.
double rate[5] = {0.11, 0.13, 0.16};
Note 2: It is an error if more values are supplied than the declared size of the
array.
How this error is handled, however, will vary from one compiler to
another.
rate
0 1 2 3 4
0.11 0.13 0.16 0 0
rate
0 1 2 3 4
0.11 0.13 0.16 0.18 0.21
In C++, arrays can be initialized when they are declared.
Numeric arrays:
element_type num_array[CAPACITY] = {list_of_initial_values};
Note 1: If fewer values are supplied than the declared size of the array,
the zeroes used to fill un-initialized elements are interpreted as
the null character '0' whose ASCII code is 0.
const int NAME_LENGTH = 10;
char collegeName[NAME_LENGTH]={'C', 'a', 'l', 'v', 'i', 'n'};
vowel
0 1 2 3 4
A E I O U
char vowel[5] = {'A', 'E', 'I', 'O', 'U'};
Character Arrays:
Character arrays may be initialized in the same manner as numeric
arrays.
declares vowel to be an array of 5 characters and initializes it as
follows:
collegeName
0 1 2 3 4 5 6 7 8 9
C a l v i n 0 0 0 0
Addresses
When an array is declared, the address of the first byte (or word) in the
block of memory associated with the array is called the base address of
the array.
Each array reference must be translated into an offset from this base
address.
For example, if each element of array score will be stored in 8 bytes and
the base address of score is 0x1396. A statement such as
cout << score[3] << endl;
requires that array reference
score[3]
be translated into a memory address:
0x1396 + 3 * sizeof
(double)
= 0x1396 + 3 * 8
= 0x13ae
The contents of the memory word with this
address 0x13ae can then be retrieved and
displayed.
An address translation like this is carried out
each time an array element is accessed.
score[3] 
[0]
[1]
[2]
[3]
[99]
.
.
.
.
.
.
score  0x1396
0x13ae
What will be the
time complexity
The value of array_name is actually the base address of array_name
array_name + index is the address of array_name[index].
An array reference array_name[index]
is equivalent to
For example, the following statements of pseudocode are
equivalent:
print score[3]
print *(score + 3)
Note: No bounds checking of indices is done!
* is the dereferencing operator
*ref returns the contents of the memory location with
address ref
*(array_name + index)
What will happen
incase
of going overboard
Problems with Arrays
1. The capacity of Array can NOT change during program
execution.
What is the problem?
Memory wastage
Out of range errors
2. Arrays are NOT self contained objects
What is the problem?
No way to find the last value stored.
Not a self contained object as per OOP principles.
C++ Style Multidimensional
Arrays
Most high level languages support arrays with more than one
dimension.
2D arrays are useful when data has to be arranged in tabular form.
Higher dimensional arrays appropriate when several
characteristics associated with data.
Test 1 Test 2 Test 3 Test 4
Student 1 99.0 93.5 89.0 91.0
Student 2 66.0 68.0 84.5 82.0
Student 3 88.5 78.5 70.0 65.0
: : : : :
: : : : :
Student-n 100.0 99.5 100.0 99.0
For storage and processing, use a two-dimensional
array.
Example: A table of test scores for several different
students on
several different tests.
Declaring Two-Dimensional
Arrays
Standard form of declaration:
element_type array_name[NUM_ROWS][NUM_COLUMNS];
Example:
const int NUM_ROWS = 30,
NUM_COLUMNS = 4;
double scoresTable[NUM_ROWS][NUM_COLUMNS];
Initialization
 List the initial values in braces, row by row;
 May use internal braces for each row to improve readability.
Example:
double rates[][] = {{0.50, 0.55, 0.53}, // first row
{0.63, 0.58, 0.55}}; // second row
[0]
[1]
[2]
[3]
[29]
[0] [[1] [2] [3]
Processing Two-Dimensional
Arrays
 Remember: Rows (and) columns are numbered from zero!!
 Use doubly-indexed variables:
scoresTable[2][3] is the entry in row 2 and column 3

row index column index
 Use nested loops to vary the two indices, most often in a rowwise
manner.
Counting
from 0
Higher-Dimensional Arrays
The methods for 2D arrays extend in the obvious way to 3D arrays.
Example: To store and process a table of test scores for several different
students on several different tests for several different semesters
const int SEMS = 10, STUDENTS = 30, TESTS = 4;
typedef double ThreeDimArray[SEMS][STUDENTS][TESTS];
ThreeDimArray gradeBook;
gradeBook[4][2][3]
is the score of 4th
semester for student 2 on test 3
// number of semesters, students and tests all counted from zero!!
Arrays of Arrays
double scoresTable[30][4];
Declares scoresTable to be a one-dimensional array containing
30 elements, each of which is a one-dimensional array of 4 real numbers; tha
scoresTable is a one-dimensional array of rows , each of which has 4
real values. We could declare it as
typedef double RowOfTable[4];
RowOfTable scoresTable[30];
[0]
[1]
[2]
[3]
[29]
[0] [[1] [2] [3]
[0] [[1] [2] [3]
[0]
[1]
[2]
[3]
[29]
scoresTable[i] is the i-th row of the table
Address Translation:
Address Translation:
The array-of-arrays structure of multidimensional arrays explains
address translation.
Suppose the base address of scoresTable is 0x12348:
scoresTable[10] 0x12348 + 10*(sizeof RowOfTable)
In general, an n-dimensional array can be viewed (recursively) as a
one-dimensional array whose elements are (n - 1)-dimensional arrays.
In any case:
scoresTable[i][j] should be thought of as (scoresTable[i])[j]
that is, as finding the j-th element of scoresTable[i].

scoresTable[10]
[3]  base(scoresTable[10]) + 3*(sizeof double)
scoresTable[10]
[4]
[3]
[0]
[1]
[9]
[10]
= 0x12348 + 10 * (4 * 8) + 3 * 8
= 0x124a0
= 0x12348 + 10 * (4 * 8)
Implementing Multidimensional
Arrays
More complicated than one dimensional arrays.
Memory is organized as a sequence of memory locations, and is
thus 1D
How to use a 1D structure to store a MD structure?
A B C D
E F G H
I J K L
A character requires a single byte
Compiler instructed to reserve 12 consecutive bytes
Two ways to store consecutively i.e. rowwise and columnwise.
Implementing Multidimensional
Arrays
A B C D
E F G H
I J K L
Row
Wise
A
B
C
D
E
F
G
H
I
J
K
L
Column Wise
A
E
I
B
F
J
C
G
K
D
H
L
A B C D
E F G H
I J K L
A B C D
E F G H
I J K L
Ad

More Related Content

Similar to Arrays and vectors in Data Structure.ppt (20)

Ch08
Ch08Ch08
Ch08
Arriz San Juan
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
Dushmanta Nath
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
Munazza-Mah-Jabeen
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Arrays
ArraysArrays
Arrays
Chirag vasava
 
Array
ArrayArray
Array
hjasjhd
 
Arrays
ArraysArrays
Arrays
Trupti Agrawal
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
AnisZahirahAzman
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
nikshaikh786
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
array-191103180006.pdf
array-191103180006.pdfarray-191103180006.pdf
array-191103180006.pdf
HEMAHEMS5
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
2D Array
2D Array 2D Array
2D Array
Ehatsham Riaz
 
Arrays
ArraysArrays
Arrays
Neeru Mittal
 
Learn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & ArraysLearn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & Arrays
Eng Teong Cheah
 
Lesson 18-20.pptx
Lesson 18-20.pptxLesson 18-20.pptx
Lesson 18-20.pptx
MIZANURRAHMANTUSHAR1
 

Recently uploaded (20)

Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Ad

Arrays and vectors in Data Structure.ppt

  • 2. 2 Two's complement representation For negative n (–n): (1) Find w-bit base-2 representation of n (2) Complement each bit. (3) Add 1 Example: –88 1. 88 as a 16-bit base-two number 0000000001011000 Same as sign mag. For nonnegative n: Use ordinary base-two representation with leading (sign) bit 0 2. Complement this bit string 3. Add 1 1111111110100111 1111111110101000 (Flip all bits from rightmost 0 to the end)
  • 3. 3 Data Type, Data Structure, and Abstract Data Types  Data Type  Set of values that the variable may assume  E.g., boolean = {false, true}, digit = {0, 1, 2, …., 9}  Abstract Data Type  A mathematical model, together with various operations defined on the model  Algorithms are designed in terms of ADTs and implemented in terms of the data types and operators supported by the programming language  Data Structures  Physical implementation of an ADT  Data structures used in implementations are provided in a language (primitive or built-in) or are built from the language constructs (user-defined)  Each operation associated with the ADT is implemented by one or more subroutines in the implementation
  • 4. 4 Separation of interface and implementation  Think of ADT as a black box  ADT is represented by an interface and implementation is hidden from the user  This means that the ADT can be implemented in various ways, as long as it adheres to interface  For example, a ListADT can be represented using an array based implementation or a linked list implementation
  • 5. 5 Linear list data structure  Def: An ordered collection of elements  some examples are an alphabetized list of students, a list of gold medal winners ordered by year, etc.  With these examples in mind, we feel the need to perform the following operations on a linear list  Determine whether the list is empty  Determine the size of list  Find the element with a given index  Find the index of a given element  Delete an element given its index  Insert a new element
  • 6. 6 ADT – linear List  The ADT specification is independent of any representation and programming language AbstractDataType linearList { elements ordered finite collection of zero or more elements operations empty(): return true if the list is empty size(): return the list size get(index): return the indexth element indexOf(x): return the index of the first occurance of x in the list, returns -1, if x is not in the list erase(index): delete the indexth element, element with higher index have their index reduced by 1 insert(index, x): insert x as the indexth element output(): output the list elements from left to right
  • 7. 7 Array representation  [5, 2, 4, 8,1]  Some of the implementations can be 1 8 4 2 5 location(i) = i 5 2 4 8 1 location(i) = 9- i 4 2 5 1 8 location(i) = (7+i)%10
  • 8. C++ Style Data Structures: Arrays(1) • An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation is direct access to each element in the array so values can be retrieved from or stored in this element.
  • 9. C++ Style Data Structures: Arrays (2) Properties:  Ordered so there is a first element, a second one, etc.  Fixed number of elements — fixed capacity  Elements must be the same type (and size);  use arrays only for homogeneous data sets.  Direct access: Access an element by giving its location  The time to access each element is the same for all elements, regardless of position.  in contrast to sequential access (where to access an element, one must first access all those that precede it.)
  • 10. Declaring arrays in C++ where element_type is any type array_name is the name of the array — any valid identifier CAPACITY (a positive integer constant) is the number of elements in the array score[0] score[1] score[2] score[3] score[99] . . . . . . element_type array_name[CAPACITY]; e.g., double score[100]; The elements (or positions) of the array are indexed 0, 1, 2, . . ., CAPACITY - 1. Can't input the capacity, Why? The compiler reserves a block of “consecutive” memory locations, enough to hold CAPACITY values of type element_type.
  • 11. indices numbered 0, 1, 2, . . ., CAPACITY - 1 How well does C/C++ implement an array ADT? As an ADT In C++ ordered fixed size same type elements direct access element_type is the type of elements CAPACITY specifies the capacity of the array subscript operator []
  • 12. an array literal Array Initialization Example: double rate[5] = {0.11, 0.13, 0.16, 0.18, 0.21}; Note 1: If fewer values supplied than array's capacity, remaining elements assigned 0. double rate[5] = {0.11, 0.13, 0.16}; Note 2: It is an error if more values are supplied than the declared size of the array. How this error is handled, however, will vary from one compiler to another. rate 0 1 2 3 4 0.11 0.13 0.16 0 0 rate 0 1 2 3 4 0.11 0.13 0.16 0.18 0.21 In C++, arrays can be initialized when they are declared. Numeric arrays: element_type num_array[CAPACITY] = {list_of_initial_values};
  • 13. Note 1: If fewer values are supplied than the declared size of the array, the zeroes used to fill un-initialized elements are interpreted as the null character '0' whose ASCII code is 0. const int NAME_LENGTH = 10; char collegeName[NAME_LENGTH]={'C', 'a', 'l', 'v', 'i', 'n'}; vowel 0 1 2 3 4 A E I O U char vowel[5] = {'A', 'E', 'I', 'O', 'U'}; Character Arrays: Character arrays may be initialized in the same manner as numeric arrays. declares vowel to be an array of 5 characters and initializes it as follows: collegeName 0 1 2 3 4 5 6 7 8 9 C a l v i n 0 0 0 0
  • 14. Addresses When an array is declared, the address of the first byte (or word) in the block of memory associated with the array is called the base address of the array. Each array reference must be translated into an offset from this base address. For example, if each element of array score will be stored in 8 bytes and the base address of score is 0x1396. A statement such as cout << score[3] << endl; requires that array reference score[3] be translated into a memory address: 0x1396 + 3 * sizeof (double) = 0x1396 + 3 * 8 = 0x13ae The contents of the memory word with this address 0x13ae can then be retrieved and displayed. An address translation like this is carried out each time an array element is accessed. score[3]  [0] [1] [2] [3] [99] . . . . . . score  0x1396 0x13ae What will be the time complexity
  • 15. The value of array_name is actually the base address of array_name array_name + index is the address of array_name[index]. An array reference array_name[index] is equivalent to For example, the following statements of pseudocode are equivalent: print score[3] print *(score + 3) Note: No bounds checking of indices is done! * is the dereferencing operator *ref returns the contents of the memory location with address ref *(array_name + index) What will happen incase of going overboard
  • 16. Problems with Arrays 1. The capacity of Array can NOT change during program execution. What is the problem? Memory wastage Out of range errors 2. Arrays are NOT self contained objects What is the problem? No way to find the last value stored. Not a self contained object as per OOP principles.
  • 17. C++ Style Multidimensional Arrays Most high level languages support arrays with more than one dimension. 2D arrays are useful when data has to be arranged in tabular form. Higher dimensional arrays appropriate when several characteristics associated with data. Test 1 Test 2 Test 3 Test 4 Student 1 99.0 93.5 89.0 91.0 Student 2 66.0 68.0 84.5 82.0 Student 3 88.5 78.5 70.0 65.0 : : : : : : : : : : Student-n 100.0 99.5 100.0 99.0 For storage and processing, use a two-dimensional array. Example: A table of test scores for several different students on several different tests.
  • 18. Declaring Two-Dimensional Arrays Standard form of declaration: element_type array_name[NUM_ROWS][NUM_COLUMNS]; Example: const int NUM_ROWS = 30, NUM_COLUMNS = 4; double scoresTable[NUM_ROWS][NUM_COLUMNS]; Initialization  List the initial values in braces, row by row;  May use internal braces for each row to improve readability. Example: double rates[][] = {{0.50, 0.55, 0.53}, // first row {0.63, 0.58, 0.55}}; // second row [0] [1] [2] [3] [29] [0] [[1] [2] [3]
  • 19. Processing Two-Dimensional Arrays  Remember: Rows (and) columns are numbered from zero!!  Use doubly-indexed variables: scoresTable[2][3] is the entry in row 2 and column 3  row index column index  Use nested loops to vary the two indices, most often in a rowwise manner. Counting from 0
  • 20. Higher-Dimensional Arrays The methods for 2D arrays extend in the obvious way to 3D arrays. Example: To store and process a table of test scores for several different students on several different tests for several different semesters const int SEMS = 10, STUDENTS = 30, TESTS = 4; typedef double ThreeDimArray[SEMS][STUDENTS][TESTS]; ThreeDimArray gradeBook; gradeBook[4][2][3] is the score of 4th semester for student 2 on test 3 // number of semesters, students and tests all counted from zero!!
  • 21. Arrays of Arrays double scoresTable[30][4]; Declares scoresTable to be a one-dimensional array containing 30 elements, each of which is a one-dimensional array of 4 real numbers; tha scoresTable is a one-dimensional array of rows , each of which has 4 real values. We could declare it as typedef double RowOfTable[4]; RowOfTable scoresTable[30]; [0] [1] [2] [3] [29] [0] [[1] [2] [3] [0] [[1] [2] [3] [0] [1] [2] [3] [29]
  • 22. scoresTable[i] is the i-th row of the table Address Translation: Address Translation: The array-of-arrays structure of multidimensional arrays explains address translation. Suppose the base address of scoresTable is 0x12348: scoresTable[10] 0x12348 + 10*(sizeof RowOfTable) In general, an n-dimensional array can be viewed (recursively) as a one-dimensional array whose elements are (n - 1)-dimensional arrays. In any case: scoresTable[i][j] should be thought of as (scoresTable[i])[j] that is, as finding the j-th element of scoresTable[i].  scoresTable[10] [3]  base(scoresTable[10]) + 3*(sizeof double) scoresTable[10] [4] [3] [0] [1] [9] [10] = 0x12348 + 10 * (4 * 8) + 3 * 8 = 0x124a0 = 0x12348 + 10 * (4 * 8)
  • 23. Implementing Multidimensional Arrays More complicated than one dimensional arrays. Memory is organized as a sequence of memory locations, and is thus 1D How to use a 1D structure to store a MD structure? A B C D E F G H I J K L A character requires a single byte Compiler instructed to reserve 12 consecutive bytes Two ways to store consecutively i.e. rowwise and columnwise.
  • 24. Implementing Multidimensional Arrays A B C D E F G H I J K L Row Wise A B C D E F G H I J K L Column Wise A E I B F J C G K D H L A B C D E F G H I J K L A B C D E F G H I J K L

Editor's Notes

  • #1: Prof. Khuram Chattha
  • #5: Prof. Khuram Chattha
  • #7: Prof. Khuram Chattha
  • #14: Prof. Khuram Chattha
  • #23: Prof. Khuram Chattha