PF Lecture 20 22 Arrays
PF Lecture 20 22 Arrays
Arrays
Data types
2
Array Declaration
An array is a list containing
• a fixed number of entries AND
• all entries are the same type
Syntax:
type name [ numelements ];
Examples:
int grades[5]; // declares an array of 5 ints
float hoursWorked[7]; //An array of 7 floats
3
More on Arrays, proper C++
• An array can be made from ANY type.
bool answers[5];
• An array has a positive upper bound.
char alphabet[26];
• An array upper bound must be a constant.
int arrayOfOne[1];
• An array lower bound always starts at 0.
4
Zero-indexing
• So…
cout << dailyTemperatures[4] ;
Entries: 87 81 75 93 46
Index: 0 1 2 3 4
6
Example Array and Terms
int grades[5]; // subscripts 0..4
Entries: 87 81 75 93 46
Index: 0 1 2 3 4
7
Example Array Initialization
int grades[5]; // subscripts 0..4
Entries: 87 81 75 93 46
Index: 0 1 2 3 4
8
Other Array Initializations
• Initializing an array when declared:
char LetterGrades[3]={'A', 'B', 'C'};
int scores[6]={84,91,98,57,72,85};
• Array declared larger than #values:
float heights[26]={5.5, 4.9, 6, 4.5};
//Un-filled slots will default to zero
• Implicit Array sizing:
float heights[ ]={5.5, 4.9, 6, 4.5};
9
Other Array Initializations
• Implicit Array sizing:
int grades[ ]={92,89,75,60,92,-1};
System knows # elements. Do you?
Example:
cout << 'X' << setw(5) << grades[4] << 'X' << endl;
X 92X //3 spaces between the X and 9
12
Memory allocation
int scores[10];
Variable Byte Address Value
Declaration of array with scores[0] 4902340 87
14
Find the Errors
int measurements[-5]; // is this legal?
int size;
string names[size]; // what happens here?
15
Arrays and loops
16
Can print less than the whole array
int i=1;
while(i<4) {
cout << a[i+1]-a[i] << endl;
i++;
}
18
What does this code do?
int a[5]={1,3,6,4,2};
int b[5], bNextFreeIndex=0;
int i=0;
while(i<4) {
if (a[i]>3) {
b[bNextFreeIndex]=a[i];
bNextFreeIndex++;
}
i++;
} 19
Out-of-range indexing
• An index value not allowed by array declaration
is “out of range”
char a[10];
cin >> a[10]; // out of range!
20
Out-of-range indexing
int scores[4]={1,2},
idNum;
idNum=34253; ???
scores[5]=12; ???
scores[0] 1
cout << idNum; scores[1] 2
scores[2] 0
scores[3] 0
???
idNum 34253 12
??? 21
Array Index Out of Bounds
• If we have the statements:
double num[10];
int i;
• The component num[i] is valid if i = 0, 1, 2,
3, 4, 5, 6, 7, 8, or 9
• The index of an array is in bounds if the index
>=0 and the index <= ARRAY_SIZE-1
– Otherwise, we say the index is out of bounds
• In C++, there is no guard against indices that are
out of bounds
22
Review
• What is an Array?
• What is the syntax for declaring an array?
• What is required to define the upper bound?
• Define element, index, subscript, entry?
• How can we initialize arrays at time of
declaration?
• What is initialization doesn’t have enough
elements?
• What happens if an array index is negative or
above the upper bound?
23
Array Task:
Defining and Printing an Array
How to read the instructions?
24
Search an array for all
• What kind of statements are needed?
25
• Remaining CS1 Topics?
– Array elements as parameters in functions
– Arrays as parameters in functions
– Partially filled arrays (big arrays that are not full)
– string object is an object containing an array
– 2 D arrays (tables)
– Companion (parallel) arrays
– Vectors
– Recursion (not arrays but we need to cover this!)
26
Accessing Array Components
27
Some Restrictions on Array Processing
• Consider the following statements:
• Solution:
28
Some Restrictions on Array Processing
(continued)
• The following is illegal too:
• Solution:
29
Arrays as Parameters to Functions
• Arrays are passed by reference only
• The symbol & is not used when declaring an
array as a formal parameter
• The size of the array is usually omitted
– If provided, it is ignored by the compiler
30
Base Address of an Array and Array in
Computer Memory
• The base address of an array is the address,
or memory location of the first array
component
• If list is a one-dimensional array, its base
address is the address of list[0]
• When we pass an array as a parameter, the
base address of the actual array is passed to
the formal parameter
31
Functions Cannot Return a Value of
the Type Array
• C++ does not allow functions to return a value
of the type array
33
Array elements in functions
• Array element accepted as normal function
argument
Similar to…
int my_function(int n);
int a[10], b;
We can use array elements:
b=my_function(a[2]);
b=my_function(a[5]);
34
Array elements in Functions
• The base type of the array is the type of the
element: what does this do?
void swap(int &a, int &b);
int main() {
int array[] = { 1, 3, 5, 7, 9 }; // base type is int
for (int i = 0, j = 4; i < j; i++, j--)
swap(array[i], array[j]);
for (int i = 0; I < 5; i++)
cout << array[i] << endl;
}
35
Arrays in functions
We can pass (access to) the full array in a function
• Function declaration
void printArray(int myArray[], int size2print);
Important:
Just the name. No []s and no number
36
Array parameter syntax
• Array parameter declaration
type function( type array_name[], int size);
38
Roughly “pass by reference”
39
Roughly “pass by reference”
41
Programming with arrays
What are some things we do with arrays?
Spend some time thinking about the following.
Very common:
• Search – is number x in my array?
• Sort – arrange numbers from small to large
• Find max or min value – specific kind of search
• Compare two arrays, how would you do it?
• Use a partially filled array
42
Program with Partially Filled Array
• A program that reads a bunch of golf scores.
We’ll never have more than 100.
• It computes the average of the scores
• It finds the difference of each score and the
average score.
43
Program to show score difference
const int MAX_SIZE=100;
44
fill_array
45
Compute_average
// precondition: a is an array of number_used golf scores.
// returns the average of the golf scores.
double compute_average(const int a[], int number_used)
{
double sum = 0;
for (int i = 0; i < number_used; i++)
{
sum += a[i];
}
return sum / number_used;
}
46
Show_difference
47
Exercise – 02 Arrays (01)
Q1- Write a program that reads 10 integers in
an array, and calculates the Min, Max and Sum
of all array elements.
48
Arrays (01)
Q2 - Write a program that finds a given integer
“n” in an array of 10 integers (read the values of
array in main). If the value n is found, the
program should display found, else display “not
found”.
49
Array (01)
• Q-3 Change the previous program so that you
have function that tells you if a number is
present in array or not
51
Array (01) - Sorting
• Q-5 Write a program to Sort a given array of
integers 10 integers.
54
String – your first object
#include <string>
String data:
55
String – data
string name = "hannah";
Really looks like this in memory:
h a n n a h \0
Value [0] [1] [2] [3] [4] [5] [6]
[Index]
String data:
A string is essentially an array of characters, ending
with a '\0'
56
String – Member Functions
h a n n a h \0
[0] [1] [2] [3] [4] [5] [6]
length() - returns the length of the string
cout << name.length(); // actual chars (not \0)
6
[i] - returns the character at location I
cout << name[4];
a
http://www.cplusplus.com/reference/string/string/
57
More string functions
How to read a full line (spaces included)
string s;
getline(cin, s); // reads the string
//until the 'end of line'
58
More string functions
s.length() // total COUNT of characters
59
More string functions
How to read a full line (spaces included)
60
More string functions
s.length() // total COUNT of characters
61
More string related functions
#include <cstdlib>
62
Thank you