Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

One Dimensional Array

1
"All students to receive arrays!" reports 2

Dr. Austin.

Declaring arrays

Stepping through arrays


Passing arrays
as parameters

Inspecting arrays

scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5 98 99
Motivations
Often you will have to store a
large number of values during
the execution of a program.

You need to read one hundred


numbers, compute their average, and
find out how many numbers are above
the average.

You have to declare one hundred


variables and repeatedly write
almost identical code one
hundred times. The numbers
must all be stored in variables in
order to accomplish this task.

3
4

Design Problem

 Consider a program to calculate class


average

Why??
5

Add to Design Problem

 Now your client says, I need to ALSO


calculate and display “deviations” from
the average

Describe why this will or will NOT work


6

Possible Solutions

 Enter in the scores again 


 Use 100 separate variables 
» and cout and cin commands
 Read (then re-read) from a file 
 The real answer …

Use arrays!!
7

Simple vs Structured Data Types

 Simple data type => data element


contains a single value
x : 15 avg : 84.35 ch : ‘A’

 Structured data type => a data element


contains a collection of data values
scores : 85 79 92 57 68 80

name : ‘C’ ‘L’ ‘Y’ ‘D’ ‘E’


8

Arrays

 Arrays are Structured Data Types


 They have a means of accessing
individual components
 Values can be retrieved from and stored
in the structure
scores : 100
85 79 92 57 68 80
0 1 2 3 4 5
cout << scores[2];
scores[0] = 100;
9

One Dimensional Array

 Structured collection of components


» All of the same type
 Structure given a single name
 Individual elements accessed by index
indicating relative position in collection
 Type of elements stored in an array can
be “just about” anything
 Index of an array must be an integer
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double myList [10];

myList[0] 5.6
myList[1] 4.5
myList[2] 3.3
myList[3] 13.2
myList[4] 4.0
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34.0

myList[7] 45.45

myList[8] 99.993

myList[9] 111.23

10
11
Base Address of an Array and Array in
Computer Memory
12

Use of Array for Our Problem

 Store elements in array as read in


 Go back and access for deviations

Note declaration
13

Declaring Arrays

 Syntax:
Data_type Array_name [constant];
 Note declaration from our example

Tells how many elements set aside


14

Declaring Arrays
 Example specifies an array…
» each element is an integer
» there is space for 100 elements
» The indicies are numbered 0 through 99

scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5 98 99
Declaring Array Variables
datatype arrayRefVar[arraySize];
Example:
double myList[10];

C++ requires that the array size used to declare an array must be a
constant expression. For example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong

But it would be OK, if size is a constant as follow:


const int size = 4;
double myList[size]; // Correct
15
16

Accessing Individual Components

 Use the name of the array


 Followed by an integer expression
inside the square brackets [ ]

scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5 98 99
Index can be:
max = scores[0];
- constant
for (x = 0; x < 100; x++)
- variable
if (scores[x] > max)
- expression
max = scores[x];
MUST be an integer
Using Indexed Variables

After an array is created, an indexed


variable can be used in the same way as a
regular variable.

For example, the following code adds the


value in myList[0] and myList[1] to myList[2].

myList[2] = myList[0] + myList[1];

17
18

Out of Bounds Index

 What happens if … float f_list [50];


f_list [100] = 123.456;

 C++ does NOT check for index out of


range
 Possible to walk off into “far reaches” of
memory -- clobbers ...
» other variable locations
» .exe code
» the operating system (??)
19

Initializing Arrays in Declarations

 Possible to declare the size & initialize

int results [5] = {14, 6, 23, 8, 12 }

 Possible to omit size at declaration


» Compiler figures out size of array

float prices [ ] = { 2.41, 85.06, 19.95, 3.91 }


Declaring, creating, initializing
Using the Shorthand Notation
double myList[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the
following statements:

double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

20
CAUTION

Splitting it would cause a syntax error. For


example, the following is wrong:

double myList[4];
myList = {1.9,
21 2.9, 3.4, 3.5};
Implicit Size
C++ allows you to omit the array size when
declaring and creating an array using an
initializer.

For example, the following declaration is fine:

double myList[] = {1.9, 2.9, 3.4, 3.5};

C++ automatically figures out how


many elements are in the array.

http://aline-costa.livejournal.com/
22
Partial Initialization

Case:

C++ allows you to initialize a part of the array.

the above statement assigns values 1.9, 2.9 to the first


two elements of the array. The other two elements will
be set to zero.

if an array is declared, but not


initialized, all its elements will
contain “garbage”, like all other
local variables.
23
24

Aggregate Operations

 Defn => an operation on the data


structure as a whole
» as opposed to operation on a SINGLE
element within the structure
 Example
» would be nice to read in a WHOLE
array
25

Lack of Aggregate Operations

 Would be nice but . . .


C++ does NOT have . . .
 Assignment operator for whole array
 Arithmetic operations for whole array
(think matrix)
 Comparisons for arrays (not even = =)
 Return of an array type by a function
How to Accomplish Aggregate 26

Operations?

 Most such tasks (assignment, read,


write) can be performed some other way
» write “classes” to provide these
functions
 Otherwise
» these operations must be performed
by the programmer
» element by element in a loop
Initializing arrays with random values

The following loop initializes the array myList with


random values between 0 and 99:

for (int i = 0; i < ARRAY_SIZE; i++)


{
myList[i] = rand() % 100;
}

27
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values

int main()
After the array is created
{
int values[5];
for (int i = 1; i < 5; i++) 0 0

{ 1 0
values[i] = i + values[i-1]; 2 0
} 0
3
values[0] = values[1] + values[4];
4 0
}

28
Trace Program with Arrays
i becomes 1

int main() After the array is created


{
int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 0
{
2 0
values[i] = i + values[i-1];
3 0
}
values[0] = values[1] + values[4]; 4 0
}

29
Trace Program with Arrays
i (=1) is less than 5

int main()
After the array is created
{
int values[5];
for (int i = 1; i < 5; i++) 0 0
{ 1 0
values[i] = i + values[i-1]; 2 0
}
3 0
values[0] = values[1] + values[4];
4 0
}

30
Trace Program with Arrays
After this line is executed, value[1] is 1

int main() After the first iteration


{
int values[5]; 0 0
for (int i = 1; i < 5; i++)
1 1
{
values[i] = i + values[i-1]; 2 0
} 3 0
values[0] = values[1] + values[4];
4 0
}

31
Trace Program with Arrays
After i++, i becomes 2

int main()
{ After the first iteration
int values[5];
for (int i = 1; i < 5; i++) 0 0

{ 1 1

values[i] = i + values[i-1]; 2 0

} 3 0

values[0] = values[1] + 4 0
values[4];
}

32
Trace Program with Arrays

i (= 2) is less than 5
int main()
{
int values[5]; After the first iteration
for (int i = 1; i < 5; i++)
{ 0 0
1
values[i] = i + values[i-1]; 1
0
} 2

3 0
values[0] = values[1] +
values[4]; 4 0

33
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

34
Trace Program with Arrays
After this, i becomes 3.

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

35
Trace Program with Arrays
i (=3) is still less than 5.

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

36
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = i + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

37
Trace Program with Arrays
After this, i becomes 4

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = i + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

38
Trace Program with Arrays
i (=4) is still less than 5

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = i + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

39
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

int main()
{ After the fourth iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = i + values[i-1]; 3 6

} 4 10

values[0] = values[1] + values[4];


}

40
Trace Program with Arrays
After i++, i becomes 5

int main()
{
int values[5]; After the fourth iteration
for (int i = 1; i < 5; i++)
{
values[i] = i + values[i-1]; 0 0
} 1 1
values[0] = values[1] + values[4]; 2 3
}
3 6

4 10

41
Trace Program with Arrays
i ( =5) < 5 is false. Exit the loop

int main()
{ After the fourth iteration

int values[5];
for (int i = 1; i < 5; i++) 0 0
{ 1 1
values[i] = i + values[i-1]; 2 3
} 3 6
values[0] = values[1] + values[4];
4 10
}

42
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)

int main()
{
int values[5]; 0 11
for (int i = 1; i < 5; i++)
{ 1 1
values[i] = values[i] + values[i-1]; 2 3
}
values[0] = values[1] + values[4]; 3 6
} 4 10

43
Printing arrays

To print an array, you have to print each element in


the array using a loop like the following:

for (int i = 0; i < ARRAY_SIZE; i++)


cout << myList[i] << " ";

44
Copying Arrays
Can you copy array using a syntax like this?
list = myList;
This is not allowed in
C++. You have to copy
individual elements from
one array to the other

for (int i = 0; i < ARRAY_SIZE; i++)


list[i] = myList[i];

45
Summing All Elements

Use a variable named total to store the sum. Initially


total is 0. Add each element in the array to total
using a loop like this:

double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
}

46
Finding the Largest Element
Use a variable named max to store the largest element.
Initially max is myList[0]. To find the largest element in
the array myList:

1) compare each element in myList with max,


2) update max if the element is greater than max.

double max = myList[0];


for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
max = myList[i];
}

47
Finding the index of the largest element

double max = myList[0];


int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
}
48
Random Shuffling
srand(time(0));
for (int i = 0; i < ARRAY_SIZE; i++)
{
// Generate an index randomly
int index = rand() % ARRAY_SIZE;
double temp = myList[i];
myList[i] = myList[index];
myList[index] = temp;
}

49
Shifting Elements
double temp = myList[0]; // Retain the first element
// Shift elements left
for (int i = 1; i < myList.length; i++)
{
myList[i - 1] = myList[i];
}
// Move the first element to fill in the last position
myList[myList.length - 1] = temp;

50
Problem: Lotto Numbers

Your grandma likes to play the Pick-10 lotto.


Each ticket has 10 unique numbers ranging
from 1 to 99. Every time she buys a lot of
tickets. She likes to have her tickets to cover
all numbers from 1 to 99. Write a program
that reads the ticket numbers and checks
whether all numbers are covered. Assume the
last number is 0 (0 will stop the input).
51
Example: LottoNumbers
Problem: Deck of Cards

The problem is to write a program that picks four cards


randomly from a deck of 52 cards. All the cards can be
represented using an array named deck, filled with initial
values 0 to 51, as follows:
const int NUMBER_OF_CARDS = 52;
int deck[52];
// Initialize cards
for (int i = 0; i < NUMBER_OF_CARDS; i++)
deck[i] = i;

deck[0] to deck[12] are Clubs, deck[13] to deck[25] are


Diamonds, deck[26] to deck[38] are Hearts, and deck[39] to
deck[51] are Spades.
53
Example: DeckOfCards
55

Design Problem
 Consider the task of
keeping track of data
about parts for
manufacture
» part number,
description, qty
needed, unit price
56

Parallel Array
 Use “Parallel” arrays
 One array each for part
num, descrip, qty, price partid desc qty price
 nth item in any one of
A100 xxx 5 1.23 0
the arrays associated
with same nth item of all
B25 yyy 23 8.95 1
the arrays
» string partid[]
» string desc[] 2
» int qty[]
» double price[]

You might also like