SlideShare a Scribd company logo
Arrays
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 ascout << 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; that is,
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
RowWise
A
B
C
D
E
F
G
H
I
J
K
L
ColumnWise
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

What's hot (20)

C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
طارق بالحارث
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
Rajendran
 
arrays in c
arrays in carrays in c
arrays in c
vidhi mehta
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
sandhya yadav
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
Neeru Mittal
 
ARRAYS
ARRAYSARRAYS
ARRAYS
muniryaseen
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
2D Array
2D Array 2D Array
2D Array
Ehatsham Riaz
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
Arrays
ArraysArrays
Arrays
Chirag vasava
 
Arrays in c
Arrays in cArrays in c
Arrays in c
CHANDAN KUMAR
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
أحمد محمد
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
Dr.Subha Krishna
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Kumar Boro
 
Arrays in c
Arrays in cArrays in c
Arrays in c
Jeeva Nanthini
 
Array
ArrayArray
Array
PRN USM
 
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
 
Array and string
Array and stringArray and string
Array and string
prashant chelani
 
Arrays
ArraysArrays
Arrays
Chukka Nikhil Chakravarthy
 

Viewers also liked (13)

C++ arrays part1
C++ arrays part1C++ arrays part1
C++ arrays part1
Subhasis Nayak
 
Array
ArrayArray
Array
Hajar
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
Mohammad Shaker
 
Csc1100 lecture12 ch08_pt2
Csc1100 lecture12 ch08_pt2Csc1100 lecture12 ch08_pt2
Csc1100 lecture12 ch08_pt2
IIUM
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08
Terry Yoast
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
Neveen Reda
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
EngineerBabu
 
Arrays
ArraysArrays
Arrays
archikabhatia
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
Mohamed Loey
 
Lecture17 arrays.ppt
Lecture17 arrays.pptLecture17 arrays.ppt
Lecture17 arrays.ppt
eShikshak
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
Awais Alam
 
Array in C
Array in CArray in C
Array in C
Kamal Acharya
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
Mandy Suzanne
 
Array
ArrayArray
Array
Hajar
 
Csc1100 lecture12 ch08_pt2
Csc1100 lecture12 ch08_pt2Csc1100 lecture12 ch08_pt2
Csc1100 lecture12 ch08_pt2
IIUM
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08
Terry Yoast
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
Neveen Reda
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
EngineerBabu
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
Mohamed Loey
 
Lecture17 arrays.ppt
Lecture17 arrays.pptLecture17 arrays.ppt
Lecture17 arrays.ppt
eShikshak
 
Ad

Similar to Algo>Arrays (20)

Arrays and vectors in Data Structure.ppt
Arrays and vectors in Data Structure.pptArrays and vectors in Data Structure.ppt
Arrays and vectors in Data Structure.ppt
mazanali7145
 
Arrays
ArraysArrays
Arrays
Trupti Agrawal
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
Arrays
ArraysArrays
Arrays
Notre Dame of Midsayap College
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
Ashim Lamichhane
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
Princess Sam
 
2 arrays
2   arrays2   arrays
2 arrays
trixiacruz
 
Ch08
Ch08Ch08
Ch08
Arriz San Juan
 
Array
ArrayArray
Array
Rokonuzzaman Rony
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
ajajkhan16
 
Arrays
ArraysArrays
Arrays
Steven Wallach
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
SajalFayyaz
 
Arrays
ArraysArrays
Arrays
VenkataRangaRaoKommi1
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
Md. Imran Hossain Showrov
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
Anurag University Hyderabad
 
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
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
AnisZahirahAzman
 
Ad

More from Ain-ul-Moiz Khawaja (17)

Algo>Queues
Algo>QueuesAlgo>Queues
Algo>Queues
Ain-ul-Moiz Khawaja
 
Application of Stacks
Application of StacksApplication of Stacks
Application of Stacks
Ain-ul-Moiz Khawaja
 
Algo>Stacks
Algo>StacksAlgo>Stacks
Algo>Stacks
Ain-ul-Moiz Khawaja
 
Analysis of Algorithum
Analysis of AlgorithumAnalysis of Algorithum
Analysis of Algorithum
Ain-ul-Moiz Khawaja
 
Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
Ain-ul-Moiz Khawaja
 
Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
Ain-ul-Moiz Khawaja
 
Algorithum Analysis
Algorithum AnalysisAlgorithum Analysis
Algorithum Analysis
Ain-ul-Moiz Khawaja
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Sorting algos > Data Structures & Algorithums
Sorting algos  > Data Structures & AlgorithumsSorting algos  > Data Structures & Algorithums
Sorting algos > Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Huffman > Data Structures & Algorithums
Huffman > Data Structures & AlgorithumsHuffman > Data Structures & Algorithums
Huffman > Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Graphs > Discrete structures , Data Structures & Algorithums
Graphs > Discrete structures , Data Structures & AlgorithumsGraphs > Discrete structures , Data Structures & Algorithums
Graphs > Discrete structures , Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Data Structures & Algorithms
Data Structures & AlgorithmsData Structures & Algorithms
Data Structures & Algorithms
Ain-ul-Moiz Khawaja
 
Turn over
Turn overTurn over
Turn over
Ain-ul-Moiz Khawaja
 
Attribution Theories
Attribution TheoriesAttribution Theories
Attribution Theories
Ain-ul-Moiz Khawaja
 
Attribution Theory
Attribution TheoryAttribution Theory
Attribution Theory
Ain-ul-Moiz Khawaja
 
Absenteeism
AbsenteeismAbsenteeism
Absenteeism
Ain-ul-Moiz Khawaja
 
HRM Employee Turnover
HRM Employee TurnoverHRM Employee Turnover
HRM Employee Turnover
Ain-ul-Moiz Khawaja
 

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
 
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
 
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
 
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
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
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
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
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
 
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)
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
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
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
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
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
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
 
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
 
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
 
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
 
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
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
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
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
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
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
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
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
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
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
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
 

Algo>Arrays

  • 2. 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.
  • 3. 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.)
  • 4. 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.
  • 5. 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 []
  • 6. 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};
  • 7. 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
  • 8. 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 ascout << 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
  • 9. 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
  • 10. 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.
  • 11. 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.
  • 12. 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]
  • 13. 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
  • 14. 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!!
  • 15. 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; that is, 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]
  • 16. 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)
  • 17. 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.
  • 18. Implementing Multidimensional Arrays A B C D E F G H I J K L RowWise A B C D E F G H I J K L ColumnWise 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