SlideShare a Scribd company logo
1 of 40
1
Data Structures and Abstract
Data Types
Chapter 2
2
Chapter Contents
1 Data Structures, Abstract Data Types and
Implementations
2 Static Arrays
3 Multidimensional Arrays (optional)
4 Dynamic Arrays
5 C-Style Structs (optional)
6 Procedural Programming
3
Chapter Objectives
• Look at ADTs, implementations in detail
• Introduce arrays as ADTs
• See arrays implemented as C++ static arrays
• (Optional) Describe multidimensional arrays
• Extend pointers to use in dynamic arrays
• (Optional) Show use of C++ structs to model
objects with multiple attributes
• Show example of procedural programming
paradigm
4
Data Structures, Abstract Data
Types, and Implementations
• Consider example of an airplane flight with
10 seats to be assigned
• Tasks
– List available seats
– Reserve a seat
• How to store, access data?
– 10 individual variables
– An array of variables
5
Data Structures, Abstract Data
Types, and Implementations
• Implementation consists of
– Storage (data) structures
– Algorithms for basic operations
• Note following figure
– C++ provides large collection of data types and
structures
6
C++ Data TypesC++ Data Types
structured
array struct union class
address
pointer reference
simple
integral enum
char short int long bool
floating
float double long double
Structured Data Type
7
A structured data type is a type that
– Stores a collection of individual
components with one variable name
– And allows individual components
to be stored and retrieved by their
position within the collection
8
Arrays
• Collection of data elements
– All of same type
– Each accessed by specifying position
• Static array
– Compiler determines how memory allocated
• Dynamic array
– Allocation takes place at run time
9
Single Dimension Arrays
• Syntax:
ElementType arrayName [CAPACITY];
ElementType arrayName [CAPACITY] =
{ initializer_list };
• Example:
int b [10];
• Elements accessed by
– name and [ ] operation b[5]
10
Character Arrays
• Elements of an array may be of any type
– Including characters
• Example:
char name [NAME_CAPACITY] =
"John Doe";
• If array initialized shorter than specs
– extra locations filled with null character
11
Subscript Operation
• We have said elements
accessed by name and [ ]
numList[5]
• Consider the [ ] to be an
operator
– The subscript operator
– Performs address
translation
• Name of the array is a
pointer constant
– The base address
Declare variables to
store and total 3 blood pressures
12
int bp1, bp2, bp3;
int total;
40024000 4004
bp2bp1 bp3
cin >> bp1 >> bp2 >> bp3;
total = bp1 + bp2 + bp3;
What if you wanted to store and
total 1000 blood pressures?
13
int bp[1000];
// Declares an array of 1000 int values
bp[0] bp[1] bp[2] . . . . bp[999]
5000 5002 5004 5006
. . . .
One-Dimensional Array
Definition
14
An array is a structured collection of components
(called array elements), all of the same data type,
given a single name, and stored in adjacent
memory locations
The individual components are accessed by using
the array name together with an integral valued
index in square brackets
The index indicates the position of the component
within the collection
Another Example
15
• Declare an array called temps which will
hold up to 5 individual float values
float temps[5]; // Declaration allocates memory
temps[0] temps[1] temps[2] temps[3] temps[4]
7000 7004 7008 7012 7016
number of elements in the array
indexes or subscripts
Base Address
Declaration of an Array
16
• The index is also called the subscript
• In C++, the first array element always has
subscript 0, the second array element has
subscript 1, etc.
• The base address of an array is its
beginning address in memory
SYNTAX
DataType ArrayName[ConstIntExpression];
Yet Another Example
17
• Declare an array called name which will hold
up to 10 individual char values
char name[10]; // Declaration allocates memory
number of elements in the array
name[0] name[1] name[2] name[3] name[4] . . . . . name[9]
6000 6001 6002 6003 6004 6005 6006 6007 6008 6009
Base Address
Assigning Values to
Individual Array Elements
18
float temps[5]; int m = 4; // Allocates memory
temps[2] = 98.6;
temps[3] = 101.2;
temps[0] = 99.4;
temps[m] = temps[3] / 2.0;
temps[1] = temps[3] - 1.2;
// What value is assigned?
temps[0] temps[1] temps[2] temps[3] temps[4]
7000 7004 7008 7012 7016
99.4 ? 98.6 101.2 50.6
What values are assigned?
19
float temps[5]; // Allocates memory
int m;
for (m = 0; m < 5; m++)
{
temps[m] = 100.0 + m * 0.2 ;
}
temps[0] temps[1] temps[2] temps[3] temps[4]
7000 7004 7008 7012 7016
? ? ? ? ?
Now what values are printed?
20
float temps[5]; // Allocates memory
Int m;
. . . . .
for (m = 4; m >= 0; m--)
{
cout << temps[m] << endl;
}
temps[0] temps[1] temps[2] temps[3] temps[4]
7000 7004 7008 7012 7016
100.0 100.2 100.4 100.6 100.8
Variable Subscripts
21
float temps[5]; // Allocates memory
int m = 3;
. . . . . .
What is temps[m + 1] ?
What is temps[m] + 1 ?
temps[0] temps[1] temps[2] temps[3] temps[4]
7000 7004 7008 7012 7016
100.0 100.2 100.4 100.6 100.8
A Closer Look at the Compiler
22
float temps[5]; // Allocates memory
To the compiler, the value of the identifier temps is
the base address of the array
We say temps is a pointer (because its value is an
address); it “points” to a memory location
temps[0] temps[1] temps[2] temps[3] temps[4]
7000 7004 7008 7012 7016
100.0 100.2 100.4 100.6 100.8
Initializing in a Declaration
23
int ages[5] ={ 40, 13, 20, 19, 36 };
for (int m = 0; m < 5; m++)
{
cout << ages[m];
}
ages[0] ages[1] ages[2] ages[3] ages[4]
6000 6002 6004 6006 6008
40 13 20 19 36
Passing Arrays as Arguments
24
• In C++, arrays are always
passed by reference
• Whenever an array is passed as
an argument, its base address is
sent to the called function
In C++,
No Aggregate Array Operations
25
• The only thing you can do with an
entire array as a whole (aggregate)
is to pass it as an argument to a
function
• Exception: aggregate I/O is
permitted for C strings (special
kinds of char arrays)
Using Arrays as
Arguments to Functions
26
Generally, functions that work with
arrays require 2 items of information
– The beginning memory address of the
array (base address)
– The number of elements to process in the
array
Example with Array Parameters
27
#include <iomanip>
#include <iostream>
void Obtain (int[], int); // Prototypes here
void FindWarmest (const int[], int , int&);
void FindAverage (const int[], int , int&);
void Print (const int[], int);
using namespace std;
int main ( )
{
// Array to hold up to 31 temperatures
int temp[31]
int numDays;
int average;
int hottest;
int m;
27
Example continued
28
cout << “How many daily temperatures? ”;
cin >> numDays;
Obtain(temp, numDays);
// Call passes value of numDays and address temp
cout << numDays << “ temperatures“ << endl;
Print (temp, numDays);
FindAverage (temp, numDays, average);
FindWarmest (temp, numDays, hottest);
cout << endl << “Average was: “ << average
<< endl;
cout << “Highest was: “ << hottest << endl;
return 0;
}
28
Memory Allocated for Array
29
temp[0] temp[1] temp[2] temp[3] temp[4] . . . . . temp[30]
6000
Base Address
50 65 70 62 68 . . . . . .
int temp[31];// Array to hold up to 31 temperatures
30
void Obtain ( /* out */ int temp[] ,
/* in */ int number )
// User enters number temperatures at keyboard
// Precondition:
// number is assigned && number > 0
// Postcondition:
// temp[0 . . number -1] are assigned
{
int m;
for (m = 0; m < number; m++)
{
cout << “Enter a temperature : “;
cin >> temp[m];
}
} 30
31
void Print ( /* in */ const int temp[],
/* in */ int number )
// Prints number temperature values to screen
// Precondition:
// number is assigned && number > 0
// temp[0 . . number -1] are assigned
// Postcondition:
// temp[0 . . number -1] printed 5 per line
{
int m;
cout << “You entered: “;
for (m = 0; m < number; m++)
{
if (m % 5 == 0)
cout << endl;
cout << setw(7) << temp[m];
}
}
31
32
Using Arrays
• Accessing array for output
– See Fig. 1
• Accessing array for input from keyboard
– See Fig. 2
• Note use of arrays as parameters
– Must specify number of elements of array being
used
Figure1:Array Output
Function
void display(int theArray[], int numValues)
/*-----------------------------------------------------------------
Display values in an array of integers. Precondition: 0 <=
numValues < capacity of theArray. Postcondition: The
first numValues integers stored in theArray have been
output to cout.
-------------------------------------------------------------------------*/
{
for (int i = 0; i < numValues; i++)
cout « theArray[i] « 00 " .
cout « endl;
} 33
Figure 2: Array Input Function
#include <cassert>
void read(IntArray theArray, int capacity, int numValues)
/*-------------------------------------------------------------------------
Input values into an array of integers from the keyboard.
Preconditions: 0 <= numValues < capacity, which is the capacity
of theArray. Postcondition: numValues integers entered from the
keyboard have been stored in the first NumValues positions of
theArray
-------------------------------------------------------------------------/*
{
assert (numValues >= 0 && numValues <= capacity);
for (int i = 0; i < numValues; i++)
cin » theArray[i] ;
}
34
35
#include <iostream>
using namespace std;
void main()
{
int Nums[4];
int Sum=0;
cout<<"Enter 4 Numbers :n";
for(int i=0;i<4;i++)
cin>>Nums[i];
for(int j=0;j<4;j++)
Sum+=Nums[j];
cout<<"Sum = "<<Sum<<endl;
}
36
Multidimensional Arrays
• Consider multiple pages of the student grade
book
const int NUM_ROWS = 10, NUM_COLS = 5,
NUM_RANKS = 10;
typedef double
ThreeDimArray[NUM_ROWS][NUM_COLS][NUM_RANKS];
. . .
Example on Multidimensional Arrays
• #include <iostream> using namespace std;
• int main()
• {
• // A 2-Dimensional array
• double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};
• // Scan the array from the 3rd to the 7th member
• cout << "Members of the array";
• cout << "nDistance [0][0]" << ": " << distance[0][0];
• cout << "nDistance [0][1]" << ": " << distance[0][1];
• cout << "nDistance [0][2]" << ": " << distance[0][2];
• cout << "nDistance [0][3]" << ": " << distance[0][3];
• cout << "nDistance [1][0]" << ": " << distance[1][0];
• cout << "nDistance [1][1]" << ": " << distance[1][1];
• cout << "nDistance [1][2]" << ": " << distance[1][2];
• cout << "nDistance [1][3]" << ": " << distance[1][3];
• cout << endl; return 0;
• }
• This would produce: Members of the array
• Distance [0][0]: 44.14 Distance [0][1]: 720.52
• Distance [0][2]: 96.08 Distance [0][3]: 468.78
• Distance [1][0]: 6.28 Distance [1][1]: 68.04
• Distance [1][2]: 364.55 Distance [1][3]: 6234.12 37
38
Array of Array Declarations
• An array of arrays
– An array whose elements are other arrays
39
Array of Array Declarations
• Each of the rows is itself a one dimensional
array of values
scoresTable[2]
is the whole row numbered 2
scoresTable[2]
is the whole row numbered 2
scoresTable [1][3]scoresTable [1][3]
40
Memory Allocation in
2-Dimensional Arrays
• Elements
stored in
rowwise order
• Also called
column major
order
location [0][4] is followed in
memory by location [1][0]
location [0][4] is followed in
memory by location [1][0]

More Related Content

What's hot

The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184Mahmoud Samir Fayed
 
Simple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialSimple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialJin-Hwa Kim
 
snarks <3 hash functions
snarks <3 hash functionssnarks <3 hash functions
snarks <3 hash functionsRebekah Mercer
 
The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184Mahmoud Samir Fayed
 
How To Crack RSA Netrek Binary Verification System
How To Crack RSA Netrek Binary Verification SystemHow To Crack RSA Netrek Binary Verification System
How To Crack RSA Netrek Binary Verification SystemJay Corrales
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6Megha V
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonLifna C.S
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
Scientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanWei-Yuan Chang
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7Megha V
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202Mahmoud Samir Fayed
 
Algorithms devised for a google interview
Algorithms devised for a google interviewAlgorithms devised for a google interview
Algorithms devised for a google interviewRussell Childs
 
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...Alex Pruden
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Megha V
 

What's hot (18)

The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212
 
The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184
 
Simple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialSimple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorial
 
snarks <3 hash functions
snarks <3 hash functionssnarks <3 hash functions
snarks <3 hash functions
 
The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
 
How To Crack RSA Netrek Binary Verification System
How To Crack RSA Netrek Binary Verification SystemHow To Crack RSA Netrek Binary Verification System
How To Crack RSA Netrek Binary Verification System
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
Scientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuan
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202
 
Algorithms devised for a google interview
Algorithms devised for a google interviewAlgorithms devised for a google interview
Algorithms devised for a google interview
 
Scapy
ScapyScapy
Scapy
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
 

Viewers also liked

Midyear Review Chicago 2012 (3)
Midyear Review Chicago 2012 (3)Midyear Review Chicago 2012 (3)
Midyear Review Chicago 2012 (3)dougaljeppe
 
Escaneo nos vamos de feria
Escaneo nos vamos de feriaEscaneo nos vamos de feria
Escaneo nos vamos de feriaLuz Marina
 
Weekly news update4
Weekly news update4Weekly news update4
Weekly news update4Puneet Kaur
 
The role of softening in the numerical analysis of RC framed structures
The role of softening in the numerical analysis of RC framed structuresThe role of softening in the numerical analysis of RC framed structures
The role of softening in the numerical analysis of RC framed structuresFranco Bontempi
 
Weekly news update4
Weekly news update4Weekly news update4
Weekly news update4Puneet Kaur
 
Corso di dottorato su Ottimizzazione Strutturale: ROBUSTEZZA STRUTTURALE - Gk...
Corso di dottorato su Ottimizzazione Strutturale: ROBUSTEZZA STRUTTURALE - Gk...Corso di dottorato su Ottimizzazione Strutturale: ROBUSTEZZA STRUTTURALE - Gk...
Corso di dottorato su Ottimizzazione Strutturale: ROBUSTEZZA STRUTTURALE - Gk...Franco Bontempi
 
Pemrograman berorientasi objek ii 13 mengakses sql server melalui visual basic
Pemrograman berorientasi objek ii   13 mengakses sql server melalui visual basicPemrograman berorientasi objek ii   13 mengakses sql server melalui visual basic
Pemrograman berorientasi objek ii 13 mengakses sql server melalui visual basicEdri Yunizal
 
Presentacion de la profe doris
Presentacion de la profe dorisPresentacion de la profe doris
Presentacion de la profe dorisRIOSYULEIDYS
 
The man whose name is blotted out
The man whose name is blotted outThe man whose name is blotted out
The man whose name is blotted outDavid Nandigam
 
Infograhpic on the Top Trends that will Shape Digital Marketing
Infograhpic on the Top Trends that will Shape Digital MarketingInfograhpic on the Top Trends that will Shape Digital Marketing
Infograhpic on the Top Trends that will Shape Digital MarketingEthinos Digital Marketing
 
Mailcamp: Dave Worsell, GovDelivery (Driving Standards Agency)
Mailcamp: Dave Worsell, GovDelivery (Driving Standards Agency)Mailcamp: Dave Worsell, GovDelivery (Driving Standards Agency)
Mailcamp: Dave Worsell, GovDelivery (Driving Standards Agency)Helpful Technology
 

Viewers also liked (18)

Midyear Review Chicago 2012 (3)
Midyear Review Chicago 2012 (3)Midyear Review Chicago 2012 (3)
Midyear Review Chicago 2012 (3)
 
Guide book
Guide bookGuide book
Guide book
 
Escaneo nos vamos de feria
Escaneo nos vamos de feriaEscaneo nos vamos de feria
Escaneo nos vamos de feria
 
Weekly news update4
Weekly news update4Weekly news update4
Weekly news update4
 
The role of softening in the numerical analysis of RC framed structures
The role of softening in the numerical analysis of RC framed structuresThe role of softening in the numerical analysis of RC framed structures
The role of softening in the numerical analysis of RC framed structures
 
Weekly news update4
Weekly news update4Weekly news update4
Weekly news update4
 
Advantages of BTE Hearing Aids
Advantages of BTE Hearing AidsAdvantages of BTE Hearing Aids
Advantages of BTE Hearing Aids
 
How to IPO 101
How to IPO 101How to IPO 101
How to IPO 101
 
Corso di dottorato su Ottimizzazione Strutturale: ROBUSTEZZA STRUTTURALE - Gk...
Corso di dottorato su Ottimizzazione Strutturale: ROBUSTEZZA STRUTTURALE - Gk...Corso di dottorato su Ottimizzazione Strutturale: ROBUSTEZZA STRUTTURALE - Gk...
Corso di dottorato su Ottimizzazione Strutturale: ROBUSTEZZA STRUTTURALE - Gk...
 
Lecture 2 math 2
Lecture 2 math 2Lecture 2 math 2
Lecture 2 math 2
 
Pemrograman berorientasi objek ii 13 mengakses sql server melalui visual basic
Pemrograman berorientasi objek ii   13 mengakses sql server melalui visual basicPemrograman berorientasi objek ii   13 mengakses sql server melalui visual basic
Pemrograman berorientasi objek ii 13 mengakses sql server melalui visual basic
 
Lec3
Lec3Lec3
Lec3
 
Surf rock pop
Surf rock popSurf rock pop
Surf rock pop
 
Presentacion de la profe doris
Presentacion de la profe dorisPresentacion de la profe doris
Presentacion de la profe doris
 
The man whose name is blotted out
The man whose name is blotted outThe man whose name is blotted out
The man whose name is blotted out
 
News file
News fileNews file
News file
 
Infograhpic on the Top Trends that will Shape Digital Marketing
Infograhpic on the Top Trends that will Shape Digital MarketingInfograhpic on the Top Trends that will Shape Digital Marketing
Infograhpic on the Top Trends that will Shape Digital Marketing
 
Mailcamp: Dave Worsell, GovDelivery (Driving Standards Agency)
Mailcamp: Dave Worsell, GovDelivery (Driving Standards Agency)Mailcamp: Dave Worsell, GovDelivery (Driving Standards Agency)
Mailcamp: Dave Worsell, GovDelivery (Driving Standards Agency)
 

Similar to Data Structures Chapter

Similar to Data Structures Chapter (20)

Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec2
Lec2Lec2
Lec2
 
Lec2&3_DataStructure
Lec2&3_DataStructureLec2&3_DataStructure
Lec2&3_DataStructure
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
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
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012
 
Link list
Link listLink list
Link list
 

More from Ibrahim El-Torbany (13)

Idea2
Idea2Idea2
Idea2
 
Cpp lernaufgabe linked_list
Cpp lernaufgabe linked_listCpp lernaufgabe linked_list
Cpp lernaufgabe linked_list
 
C++ examples &revisions
C++ examples &revisionsC++ examples &revisions
C++ examples &revisions
 
Lec6 mod linked list
Lec6 mod linked listLec6 mod linked list
Lec6 mod linked list
 
Lec5
Lec5Lec5
Lec5
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec1
Lec1Lec1
Lec1
 
Lec4
Lec4Lec4
Lec4
 
Ass logic
Ass logicAss logic
Ass logic
 
Math lecture 4 Part 1
Math lecture 4 Part 1Math lecture 4 Part 1
Math lecture 4 Part 1
 
Tutorial 1
Tutorial 1Tutorial 1
Tutorial 1
 
Lec1
Lec1Lec1
Lec1
 
Chapter 1 what is statistics
Chapter 1 what is statisticsChapter 1 what is statistics
Chapter 1 what is statistics
 

Data Structures Chapter

  • 1. 1 Data Structures and Abstract Data Types Chapter 2
  • 2. 2 Chapter Contents 1 Data Structures, Abstract Data Types and Implementations 2 Static Arrays 3 Multidimensional Arrays (optional) 4 Dynamic Arrays 5 C-Style Structs (optional) 6 Procedural Programming
  • 3. 3 Chapter Objectives • Look at ADTs, implementations in detail • Introduce arrays as ADTs • See arrays implemented as C++ static arrays • (Optional) Describe multidimensional arrays • Extend pointers to use in dynamic arrays • (Optional) Show use of C++ structs to model objects with multiple attributes • Show example of procedural programming paradigm
  • 4. 4 Data Structures, Abstract Data Types, and Implementations • Consider example of an airplane flight with 10 seats to be assigned • Tasks – List available seats – Reserve a seat • How to store, access data? – 10 individual variables – An array of variables
  • 5. 5 Data Structures, Abstract Data Types, and Implementations • Implementation consists of – Storage (data) structures – Algorithms for basic operations • Note following figure – C++ provides large collection of data types and structures
  • 6. 6 C++ Data TypesC++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
  • 7. Structured Data Type 7 A structured data type is a type that – Stores a collection of individual components with one variable name – And allows individual components to be stored and retrieved by their position within the collection
  • 8. 8 Arrays • Collection of data elements – All of same type – Each accessed by specifying position • Static array – Compiler determines how memory allocated • Dynamic array – Allocation takes place at run time
  • 9. 9 Single Dimension Arrays • Syntax: ElementType arrayName [CAPACITY]; ElementType arrayName [CAPACITY] = { initializer_list }; • Example: int b [10]; • Elements accessed by – name and [ ] operation b[5]
  • 10. 10 Character Arrays • Elements of an array may be of any type – Including characters • Example: char name [NAME_CAPACITY] = "John Doe"; • If array initialized shorter than specs – extra locations filled with null character
  • 11. 11 Subscript Operation • We have said elements accessed by name and [ ] numList[5] • Consider the [ ] to be an operator – The subscript operator – Performs address translation • Name of the array is a pointer constant – The base address
  • 12. Declare variables to store and total 3 blood pressures 12 int bp1, bp2, bp3; int total; 40024000 4004 bp2bp1 bp3 cin >> bp1 >> bp2 >> bp3; total = bp1 + bp2 + bp3;
  • 13. What if you wanted to store and total 1000 blood pressures? 13 int bp[1000]; // Declares an array of 1000 int values bp[0] bp[1] bp[2] . . . . bp[999] 5000 5002 5004 5006 . . . .
  • 14. One-Dimensional Array Definition 14 An array is a structured collection of components (called array elements), all of the same data type, given a single name, and stored in adjacent memory locations The individual components are accessed by using the array name together with an integral valued index in square brackets The index indicates the position of the component within the collection
  • 15. Another Example 15 • Declare an array called temps which will hold up to 5 individual float values float temps[5]; // Declaration allocates memory temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 number of elements in the array indexes or subscripts Base Address
  • 16. Declaration of an Array 16 • The index is also called the subscript • In C++, the first array element always has subscript 0, the second array element has subscript 1, etc. • The base address of an array is its beginning address in memory SYNTAX DataType ArrayName[ConstIntExpression];
  • 17. Yet Another Example 17 • Declare an array called name which will hold up to 10 individual char values char name[10]; // Declaration allocates memory number of elements in the array name[0] name[1] name[2] name[3] name[4] . . . . . name[9] 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 Base Address
  • 18. Assigning Values to Individual Array Elements 18 float temps[5]; int m = 4; // Allocates memory temps[2] = 98.6; temps[3] = 101.2; temps[0] = 99.4; temps[m] = temps[3] / 2.0; temps[1] = temps[3] - 1.2; // What value is assigned? temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 99.4 ? 98.6 101.2 50.6
  • 19. What values are assigned? 19 float temps[5]; // Allocates memory int m; for (m = 0; m < 5; m++) { temps[m] = 100.0 + m * 0.2 ; } temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 ? ? ? ? ?
  • 20. Now what values are printed? 20 float temps[5]; // Allocates memory Int m; . . . . . for (m = 4; m >= 0; m--) { cout << temps[m] << endl; } temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8
  • 21. Variable Subscripts 21 float temps[5]; // Allocates memory int m = 3; . . . . . . What is temps[m + 1] ? What is temps[m] + 1 ? temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8
  • 22. A Closer Look at the Compiler 22 float temps[5]; // Allocates memory To the compiler, the value of the identifier temps is the base address of the array We say temps is a pointer (because its value is an address); it “points” to a memory location temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8
  • 23. Initializing in a Declaration 23 int ages[5] ={ 40, 13, 20, 19, 36 }; for (int m = 0; m < 5; m++) { cout << ages[m]; } ages[0] ages[1] ages[2] ages[3] ages[4] 6000 6002 6004 6006 6008 40 13 20 19 36
  • 24. Passing Arrays as Arguments 24 • In C++, arrays are always passed by reference • Whenever an array is passed as an argument, its base address is sent to the called function
  • 25. In C++, No Aggregate Array Operations 25 • The only thing you can do with an entire array as a whole (aggregate) is to pass it as an argument to a function • Exception: aggregate I/O is permitted for C strings (special kinds of char arrays)
  • 26. Using Arrays as Arguments to Functions 26 Generally, functions that work with arrays require 2 items of information – The beginning memory address of the array (base address) – The number of elements to process in the array
  • 27. Example with Array Parameters 27 #include <iomanip> #include <iostream> void Obtain (int[], int); // Prototypes here void FindWarmest (const int[], int , int&); void FindAverage (const int[], int , int&); void Print (const int[], int); using namespace std; int main ( ) { // Array to hold up to 31 temperatures int temp[31] int numDays; int average; int hottest; int m; 27
  • 28. Example continued 28 cout << “How many daily temperatures? ”; cin >> numDays; Obtain(temp, numDays); // Call passes value of numDays and address temp cout << numDays << “ temperatures“ << endl; Print (temp, numDays); FindAverage (temp, numDays, average); FindWarmest (temp, numDays, hottest); cout << endl << “Average was: “ << average << endl; cout << “Highest was: “ << hottest << endl; return 0; } 28
  • 29. Memory Allocated for Array 29 temp[0] temp[1] temp[2] temp[3] temp[4] . . . . . temp[30] 6000 Base Address 50 65 70 62 68 . . . . . . int temp[31];// Array to hold up to 31 temperatures
  • 30. 30 void Obtain ( /* out */ int temp[] , /* in */ int number ) // User enters number temperatures at keyboard // Precondition: // number is assigned && number > 0 // Postcondition: // temp[0 . . number -1] are assigned { int m; for (m = 0; m < number; m++) { cout << “Enter a temperature : “; cin >> temp[m]; } } 30
  • 31. 31 void Print ( /* in */ const int temp[], /* in */ int number ) // Prints number temperature values to screen // Precondition: // number is assigned && number > 0 // temp[0 . . number -1] are assigned // Postcondition: // temp[0 . . number -1] printed 5 per line { int m; cout << “You entered: “; for (m = 0; m < number; m++) { if (m % 5 == 0) cout << endl; cout << setw(7) << temp[m]; } } 31
  • 32. 32 Using Arrays • Accessing array for output – See Fig. 1 • Accessing array for input from keyboard – See Fig. 2 • Note use of arrays as parameters – Must specify number of elements of array being used
  • 33. Figure1:Array Output Function void display(int theArray[], int numValues) /*----------------------------------------------------------------- Display values in an array of integers. Precondition: 0 <= numValues < capacity of theArray. Postcondition: The first numValues integers stored in theArray have been output to cout. -------------------------------------------------------------------------*/ { for (int i = 0; i < numValues; i++) cout « theArray[i] « 00 " . cout « endl; } 33
  • 34. Figure 2: Array Input Function #include <cassert> void read(IntArray theArray, int capacity, int numValues) /*------------------------------------------------------------------------- Input values into an array of integers from the keyboard. Preconditions: 0 <= numValues < capacity, which is the capacity of theArray. Postcondition: numValues integers entered from the keyboard have been stored in the first NumValues positions of theArray -------------------------------------------------------------------------/* { assert (numValues >= 0 && numValues <= capacity); for (int i = 0; i < numValues; i++) cin » theArray[i] ; } 34
  • 35. 35 #include <iostream> using namespace std; void main() { int Nums[4]; int Sum=0; cout<<"Enter 4 Numbers :n"; for(int i=0;i<4;i++) cin>>Nums[i]; for(int j=0;j<4;j++) Sum+=Nums[j]; cout<<"Sum = "<<Sum<<endl; }
  • 36. 36 Multidimensional Arrays • Consider multiple pages of the student grade book const int NUM_ROWS = 10, NUM_COLS = 5, NUM_RANKS = 10; typedef double ThreeDimArray[NUM_ROWS][NUM_COLS][NUM_RANKS]; . . .
  • 37. Example on Multidimensional Arrays • #include <iostream> using namespace std; • int main() • { • // A 2-Dimensional array • double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; • // Scan the array from the 3rd to the 7th member • cout << "Members of the array"; • cout << "nDistance [0][0]" << ": " << distance[0][0]; • cout << "nDistance [0][1]" << ": " << distance[0][1]; • cout << "nDistance [0][2]" << ": " << distance[0][2]; • cout << "nDistance [0][3]" << ": " << distance[0][3]; • cout << "nDistance [1][0]" << ": " << distance[1][0]; • cout << "nDistance [1][1]" << ": " << distance[1][1]; • cout << "nDistance [1][2]" << ": " << distance[1][2]; • cout << "nDistance [1][3]" << ": " << distance[1][3]; • cout << endl; return 0; • } • This would produce: Members of the array • Distance [0][0]: 44.14 Distance [0][1]: 720.52 • Distance [0][2]: 96.08 Distance [0][3]: 468.78 • Distance [1][0]: 6.28 Distance [1][1]: 68.04 • Distance [1][2]: 364.55 Distance [1][3]: 6234.12 37
  • 38. 38 Array of Array Declarations • An array of arrays – An array whose elements are other arrays
  • 39. 39 Array of Array Declarations • Each of the rows is itself a one dimensional array of values scoresTable[2] is the whole row numbered 2 scoresTable[2] is the whole row numbered 2 scoresTable [1][3]scoresTable [1][3]
  • 40. 40 Memory Allocation in 2-Dimensional Arrays • Elements stored in rowwise order • Also called column major order location [0][4] is followed in memory by location [1][0] location [0][4] is followed in memory by location [1][0]